Advertisement
Guest User

Untitled

a guest
Jul 9th, 2016
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. /**
  2.  * @Route("/foobar")
  3.  * @return Response
  4.  */
  5. public function fooAction()
  6. {
  7.     $form = $this->createForm(SomeFooType::class);
  8.  
  9.     $token = $this->get('security.csrf.token_manager')
  10.         ->getToken('some_foo')
  11.         ->getValue();
  12.  
  13.     $data = [
  14.         'name'    => 'john',
  15.         'surname' => 'doe',
  16.         '_token'  => $token
  17.     ];
  18.  
  19.     $form->submit($data);
  20.  
  21.     if ( $form->isSubmitted() ) {
  22.         if ( $form->isValid() ) {
  23.             return new Response("Form submitted and valid");
  24.         }
  25.  
  26.         $errors = $form->getErrors(TRUE, TRUE);
  27.  
  28.         return new Response("Form submitted BUT not valid: " . (count($errors) ? $errors[0]->getMessage() : ""), 400);
  29.     }
  30.  
  31.     return new Response("Form not submitted!");
  32. }
  33.  
  34.  
  35. class SomeFooType extends AbstractType
  36. {
  37.     public function buildForm(FormBuilderInterface $builder, array $options)
  38.     {
  39.         $builder
  40.             ->add('name', TextType::class, [
  41.                 'label'       => 'First name:',
  42.                 'constraints' => [
  43.                     new NotBlank()
  44.                 ]
  45.             ])
  46.             ->add('surname', TextType::class, [
  47.                 'constraints' => [
  48.                     new NotBlank()
  49.                 ]
  50.             ]);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement