Search code examples
symfony

Symfony Form Validation getters always triggering/failing


I'm using Symfony's Validator Getter Component In conjunction with symfony forms.

In one of my entities files, I have:

use Symfony\Component\Validator\Constraints as Assert;

class StudentPaper
{
   .....
   /**
    * @Assert\IsTrue(message = "You must include a paper with your submission")
    */
   public function hasPaper()
   {
       // I originally had logic that checked the validity, but just 
       // changed the return value to 'true' to prove that it's not working.
       return true;
   }
}

Unfortunately, the validation always fails (even when I hardcore the return value to be true). The validation code doesn't seem to be executed, and the form triggers the error. I even tried replacing it with IsFalse and hard coding false. Same result.

Anyone come across this?

Symfony 2.8. PHP 5.6.15


Solution

  • Well, I can't fully explain what the actual problem is (because I don't know), but I did find a solution.

    In my StudentPaper entity I had

     /**
     * Bidirectional - Student Papers have one file.
     *
     * @ORM\OneToOne(targetEntity="StudentPaperFile", inversedBy="student_paper", cascade={"persist", "remove"}, orphanRemoval=true)
     * @ORM\JoinColumn()
     * @Assert\Valid()
     */
    protected $paper;
    

    as a property. Turns out that having a property named paper AND a validation getter called hasPaper() was causing unexpected behavior. As soon as I changed the function name from hasPaper() to hasTesting() or hasSubmittedPaper then the getter worked as it was intended.

    So the solution is that the getter function cannot be get/is/has + a mapped property name.