Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Based on what the outcome of a process is, we redirect user to a confirmation, error or notification page and these pages should only be accessed only once. To do this, we're going to use sessions so follow the steps below.


User controller


Assuming that we're creating an user.


class UserCreateController extends Controller
{
public function indexAction()
{
$form = $this->getForm();

return $this->render('MyUserBundle:User:user_create.html.twig',
array('form' => $form->createView()));
}

private function getForm()
{
return $this->createForm(new UserType(), new User(),
array('action' => $this->generateUrl('user_create')));
}

public function createAction(Request $request)
{
if ($request->getMethod() != 'POST')
{
return new Response('Invalid HTTP request!');
}

$form = $this->getForm();
$form->handleRequest($request);

if ($form->isValid() !== true)
{
return $this->render('MyUserBundle:User:user_create.html.twig',
array('form' => $form->createView()));
}

try
{
$submission = $form->getData();
$em = $this->getDoctrine()->getManager();

$user = new User();
$user->setName($submission->getName());
$user->setOrigin($submission->getOrigin());

$em->persist($user);
$em->flush();

$this->get('session')->getFlashBag()->add('notice',
array('status' => 'success', 'message' => 'User has been successfully created.'));
}
catch (Exception $e)
{
$this->get('session')->getFlashBag()->add('notice',
array('status' => 'fail', 'message' => 'User has failed.'));
}

return $this->redirect($this->generateUrl('notice'));
}
}

Notice controller


This is where user is redirected from User controller above.


class NoticeController extends Controller
{
public function indexAction()
{
if ($this->get('session')->getFlashBag()->has('notice') !== true)
{
return $this->redirect($this->generateUrl('home'));
}

return $this->render('MyUserBundle:Default:notice.html.twig');
}
}

Notice twig file


This is where notice message is displayed.


{% extends '::base.html.twig' %}

{% block body %}
{% for flashNotice in app.session.flashbag.get('notice') %}
<div class="flash-notice-{{ flashNotice.status }}">
{{ flashNotice.message }}
</div>
{% endfor %}
{% endblock %}