Slim flash messages not working inside try {} catch() {}


#1

I’m working with the Slim version 2.6.1 (due to some limitation in the company current PHP version) and when trying to use flash messages inside of a try { } catch() {} block the messages are not stored in the session when the template is rendered.

For example, the code below works fine:

$objValidation = FormValidator::isValidData($post);

if($objValidation->bolHasError)
{
   $app->flash('objValidation', serialize($objValidation));
   $app->flash('selectedData', $post);
   return $app->redirect('/app/edit/form/components/');
} 

But if I start using a try block, like below, then the flash message is not stored in the $_SESSION:

try {    
    $objValidation = FormValidator::isValidData($post);

    if($objValidation->bolHasError)
    {
       $app->flash('objValidation', serialize($objValidation));
       $app->flash('selectedData', $post);
       return $app->redirect('/app/edit/form/components/');
    } 
}
catch(Exception $e) {
    # do something
}

There are any limitations of scope for using the flash messages in that way?


#2

I’ve figured out that the try block create a “isolated scope”. So, I tried to to put a return false before the redirect to test if the in next page the flash message would show up. And finally the flash message was stored in the $_SESSION variable (of course the redirection was not executed, but at least I’ve discovered that the issue is related with the try scope).

Then, the solution I found was to raise an exception and do the redirect inside the catch block. Like this:

$objValidation = FormValidator::isValidData($post);

if($objValidation->bolHasError)
{
    throw new Exception('validation_error');
}

and then capture the error into the catch block:

catch(Exception $e)
{
    if($e->getMessage() == 'validation_error')
    {
        $app->flash('objValidation', serialize($objValidation));
        $app->flash('formData', $post);

        return $app->redirect('/api/form/change/components/');
    }
}

In that way I was able to get the flash message into template.


#3

if you use template engine twig
setup this

$container[‘flash’] = function ($c) {
return new \Slim\Flash\Messages;
};

set in controller
echo $this->flash->addMessage(‘message’, “Akun Anda Di Block {$delay} Detik.”);
$result = $response->withRedirect(’/’);

it’s work