Zaman zaman uygulamanın sonucuna göre doğrulama, hata veya bilgilendirme acıyla, kullanıcıyı bir kerelik kullanımaya açık olan bir sayfaya yönlendiririz. Bu gibi işlemler için session kullanılır.


User controller


Varsayalım ki bir tane kullanıcı yaratıyoruz.


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


Yukarıdaki controller ile kullanıcı buraya yönlendirilir.


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 dosyası


İlgili mesajımız burada gösterilir.


{% 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 %}