Last active
December 21, 2015 00:19
-
-
Save alxfv/6219436 to your computer and use it in GitHub Desktop.
Symfony ajax form validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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