Symfony2 form validation always returning ERROR: This value should not be blank

11,423

Solution 1

I've just had the same problem. I got a global error ERROR: This value should not be blank, but there was not any errors to a specific field.

nifr was right, validation is in fact applied to the underlying object. The question is whether or not the object is valid after the form has applied the submitted data to it. http://symfony.com/doc/current/book/forms.html#form-validation

The reason for this problem is that some fields of the object are not valid after a form submission and these fields are not included in the form. To solve this problem, you can pass valid data to the fields of the object before validation, or use validation groups to validate the object against only some of the constraints on the class.

Solution 2

remove the following:

token:
     - NotBlank: ~

from src/Ibw/JobeetBundle/Resources/config/validation.yml

Solution 3

as @cheesemacfly mentioned, your problem is in the "token" field

it's asserted to be "not blank" but it is not included in the form, that's why the error is not bound to any of the form fields and is rather a global error for the form because the validation happens on the entity, not on the form(different than in symfony 1.4) and so the validation mechanism can't bind it to a field in a form because this property(token) doesn't have a field in the form

Share:
11,423
Rafael Adel
Author by

Rafael Adel

About me

Updated on June 15, 2022

Comments

  • Rafael Adel
    Rafael Adel almost 2 years

    I have a strange problem using a form in Symfony2.

    First i've added the validation as annotations inside the entity class Job here:

    class Job
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;
    
        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         * @Assert\NotBlank()
         * @Assert\Choice(callback="getTypeValues")
         */
        protected $type;
    
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\NotBlank()
         */
        protected $company;
    
        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        protected $logo;
    
        /**
         * @Assert\Image()
         */
        protected $file;
    
        /**
         * @ORM\Column(type="string", length=255, nullable=true)
         * @Assert\Url()
         */
        protected $url;
    
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\NotBlank()
         */
        protected $position;
    
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\NotBlank()
         */
        protected $location;
    
        /**
         * @ORM\Column(type="text")
         * @Assert\NotBlank()
         */
        protected $description;
    
        /**
         * @ORM\Column(type="text")
         * @Assert\NotBlank()
         */
        protected $how_to_apply;
    
        /**
         * @ORM\Column(type="string", length=255, unique=true)
         * @Assert\NotBlank()
         */
        protected $token;
    
        /**
         * @ORM\Column(type="boolean", nullable=true)
         */
        protected $is_public;
    
        /**
         * @ORM\Column(type="boolean", nullable=true)
         */
        protected $is_activated;
    
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\NotBlank()
         * @Assert\Email()
         */
        protected $email;
    
        /**
         * @ORM\Column(type="datetime")
         */
        protected $expires_at;
    
        /**
         * @ORM\Column(type="datetime")
         */
        protected $created_at;
    
        /**
         * @ORM\Column(type="datetime", nullable=true)
         */
        protected $updated_at;
    
        /**
         * @ORM\ManyToOne(targetEntity="Category", inversedBy="jobs")
         * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
         * @Assert\NotBlank()
         */
        protected $category;
    }
    

    I've created a JobType class and used it inside a form. So i can add jobs.

    class JobType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('type', 'choice', array('choices' => Job::getTypes(), 'expanded' => true))
                ->add('category')
                ->add('company')
                ->add('file', 'file', array('label' => 'Company logo', 'required' => false))
                ->add('url')
                ->add('position')
                ->add('location')
                ->add('description')
                ->add('how_to_apply', null, array('label' => 'How to apply?'))
                ->add('is_public', null, array('label' => 'Public?'))
                ->add('email')
            ;
        }
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                    'data_class' => 'Ibw\JobeetBundle\Entity\Job',
                ));
        }
    
        public function getName()
        {
            return 'job';
        }
    }
    

    Here's my controller:

    public function createAction(Request $request)
    {
        $entity = new Job();
        $form = $this->createForm(new JobType(), $entity);
        $form->handleRequest($request);
    
        if($form->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
    
            return $this->redirect($this->generateUrl('ibw_job_preview', array(
                    'company'   => $entity->getCompanySlug(),
                    'location'  => $entity->getLocationSlug(),
                    'position'  => $entity->getPositionSlug(),
                    'token'     => $entity->getToken(),
                )));
        } else {
            return new Response(var_dump($form->getErrorsAsString()));
    //            return new Response($form->getErrorsAsString());
    //          return $this->render('IbwJobeetBundle:Job:new.html.twig', array(
    //                  'form' => $form->createView(),
    //              ));
        }
    }
    

    Now when i do var_dump($form->getErrorsAsString()) I get:

    string 'ERROR: This value should not be blank.
    type:
        0:
            No errors
        1:
            No errors
        2:
            No errors
    category:
        No errors
    company:
        No errors
    file:
        No errors
    url:
        No errors
    position:
        No errors
    location:
        No errors
    description:
        No errors
    how_to_apply:
        No errors
    is_public:
        No errors
    email:
        No errors
    ' (length=355)
    

    Or when i do var_dump($form->getErrors()) I get:

    array (size=1)
      0 => 
        object(Symfony\Component\Form\FormError)[614]
          private 'message' => string 'This value should not be blank.' (length=31)
          protected 'messageTemplate' => string 'This value should not be blank.' (length=31)
          protected 'messageParameters' => 
            array (size=0)
              empty
          protected 'messagePluralization' => null
    

    I have no idea what generates this ERROR: This value should not be blank. error. I'm having hard times figuring it out. Any help would be greatly appreciated.

    • Ken Hannel
      Ken Hannel over 10 years
      Are you getting these errors on the GET requests when the form should be displayed in the view or do you mean when you POST the form to the controller to process the form?
    • stwe
      stwe over 10 years
      Is just an idea ... I think you should either @Assert\NotBlank() OR using the callback function - not both.
    • Rafael Adel
      Rafael Adel over 10 years
      @KenHannel This happens when the POST controller process the posted form. So yea in the POST request.
    • Rafael Adel
      Rafael Adel over 10 years
      @stwe Just tried to remove NotBlank() still no good. The same problem occurs.
    • stwe
      stwe over 10 years
      have you cleared your cache?
    • Rafael Adel
      Rafael Adel over 10 years
      @stwe Although i'm using the development environment but yea, i've cleared it.
    • cheesemacfly
      cheesemacfly over 10 years
      $token => @Assert\NotBlank()?
    • Rafael Adel
      Rafael Adel over 10 years
      @cheesemacfly You mean i should remove the assertion ?
    • cheesemacfly
      cheesemacfly over 10 years
      Yeah, try to see of it helps!
    • Nicolai Fröhlich
      Nicolai Fröhlich over 10 years
      Don't forget to clear your (symfony+apc/opcode) cache after changing assert annotations ...
    • Rafael Adel
      Rafael Adel over 10 years
      Removing NotBlank from $token did it !.. But i wonder why ? I haven't included $token in the form anyway !
    • Nicolai Fröhlich
      Nicolai Fröhlich over 10 years
      Validation in the first place does not have anything to do with the form but the entity itself. you should create a validation-group for the form and second one to validate your entity once the token has been set.
    • Rafael Adel
      Rafael Adel over 10 years
      @nifr I've added validation group and it's working. But i'm not quite following why the error is raised here. Could you elaborate more?
    • Peter Bailey
      Peter Bailey over 10 years
      Post the template/view that renders the form. I'm guessing that you might have a hidden field that isn't rendered (like a csrf token or something)
    • sintetico82
      sintetico82 about 10 years
      The problem is that the NotBlanck validator not add properti name when add validation error. See source code: NotBlank and for example a Date . I don't know why NotBlank not add name of propertie
  • Wykk
    Wykk almost 9 years
    Mark this as right answer, this helped me to get my form valid.