Skip to content

Instantly share code, notes, and snippets.

@alxfv
Last active December 21, 2015 00:19
Show Gist options
  • Select an option

  • Save alxfv/6219436 to your computer and use it in GitHub Desktop.

Select an option

Save alxfv/6219436 to your computer and use it in GitHub Desktop.
Symfony ajax form validation
<?php
* @Route("/{id}/edit", name="user_edit")
* @Template()
*/
public function editAction($id)
{
/** @var $dm \Doctrine\ODM\MongoDB\DocumentManager */
$dm = $this->get('doctrine_mongodb')->getManager();
/** @var $repository */
$repository = $dm->getRepository('UserBundle:User');
$user = $repository->find($id);
$form = $this->createFormBuilder($user, [
'validation_groups' => ['settings'],
'attr' => ['novalidate' => 'novalidate']
])
->add('firstName', 'text', ['required' => false])
->add('lastName', 'text')
->add('captcha', 'captcha')
->add('save', 'submit')
->getForm()
;
$request = $this->getRequest();
$form->handleRequest($request);
if ($form->isValid()) {
$dm->persist($user);
$dm->flush();
$url = $this->generateUrl('user_edit', ['id' => $id]);
if ($request->isXmlHttpRequest()) {
return new JsonResponse(['redirect' => $url]);
}
return $this->redirect($url);
}
else {
if ($request->isXmlHttpRequest()) {
$captcha = $form->get('captcha')->createView();
return new JsonResponse(['img' => $captcha->vars['captcha_code']], 400);
}
}
$view = $form->createView();
return ['form' => $view];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment