Search code examples
phpformssymfonysymfony-formsassert

Symfony Forms Assert


I have Event class that has a field like this :

class Event
{
    ......
    /**
     * @var datetime $date
     *
     * @ORM\Column(name="date_debut_inscri", type="datetime")
     * @Assert\GreaterThanOrEqual("today UTC")
     */
     protected $dateDebutInscri;
     ......
}

This field is hidden when a checkbox is checked and it's set to null in the controller, the problem is when this field is hidden the Assert error message still appears and that makes me unable to submit my form

I want it to be null by default and if the user chooses to fill this field it must be greater or equal than the current date

I was wondering if i could do soomething like :

* @Assert\GreaterThanOrEqual("today UTC") OR @Assert\IsNull()

where it requires only one of the two Assert to be true

PS : "dateDebutInscri" is in french and it means the date when the inscription to the event is open


Solution

  • I was able to so solve this problem using GroupSequence, it's explained here :

    http://symfony.com/doc/current/validation/sequence_provider.html

    Added some code to my Event class and it's all good

    use Symfony\Component\Validator\GroupSequenceProviderInterface;
    
    /**
     * @ORM\Table(name="event")
     * @ORM\Entity(repositoryClass="AppBundle\Repository\EventRepository")
     * @Assert\GroupSequenceProvider
     */
    class Event implements GroupSequenceProviderInterface
    {
    ......
       /**
        * @var datetime $date
        *
        * @ORM\Column(name="date_debut_inscri", type="datetime")
        * @Assert\GreaterThanOrEqual("today UTC", groups = {grp1})
        */
        protected $dateDebutInscri;
    ......
    
        public function getGroupSequence(){
                $groups = ['Default', 'Event'];
    
                if(!$this->getMyCheckBox())
                {
                    $groups[] = 'grp1';
                }
                return $groups;
        }
    }