Reputation: 615
I am using the Slim php framework for the first time, so far it has been excellent. I am using a library to handle validation on a user registration form and a session variable to store the input and throw the errors when needed.
I am getting an error telling me my session variable isn't defined. I am struggling to see where I am failing, the session start begins in app.php
and the following files exist:
Validator.php
namespace App\Validation;
use Respect\Validation\Validator as Respect;
use Respect\Validation\Exceptions\NestedValidationException;
class Validator
{
protected $errors;
public function validate($request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$this->errors[$field] = $e->getMessages();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
public function failed()
{
return !empty($this->errors);
}
}
ValidationErrorsMiddleware.php
namespace App\Middleware;
class ValidationErrorsMiddleware extends Middleware
{
public function __invoke($request, $response, $next)
{
$this->container->view->getEnvironment()->addGlobal('errors', $_SESSION['errors']);
unset($_SESSION['errors']);
$response = $next($request, $response);
return $response;
}
}
The error keeps throwing out pointing at this line:
$this->container->view->getEnvironment()->addGlobal('errors', $_SESSION['errors']);
I can see a session is being logged but without setting an isset
on this I want to know why it fails?
The actual error itself is: Notice: Undefined index: errors in...
UPDATE
app.php
$app->add(new \App\Middleware\ValidationErrorsMiddleware($container));
Middleware.php
namespace App\Middleware;
class Middleware
{
protected $container;
public function __construct($container)
{
$this->container = $container;
}
}
Upvotes: 1
Views: 1386
Reputation: 4952
Add a session middleware and start the session:
// Session middleware
$app->add(function (Request $request, Response $response, $next)
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
return $next($request, $response);
});
Upvotes: 0
Reputation: 4205
You can try like this code 100% working:
?php
namespace App\Middleware;
class OldInputMiddleware extends Middleware
{
public function __invoke($request, $response, $next)
{
/**
* To prevent Notice: Undefined index: old in app/Middleware/OldInputMiddleware.php on line 16
*/
if(empty($_SESSION['old'])){
$_SESSION['old'] = true;
}
$this->container->view->getEnvironment()->addGlobal('old', $_SESSION['old']);
$_SESSION['old'] = $request->getParams();
$response = $next($request, $response);
return $response;
}
}
Upvotes: 2