formssymfonycheckboxrequired

What is the right approach to validate multiple checkboxes at once in Symfony2 (one required)?


Let's say we have a Symfony2 form containing 3 checkboxes (A, B, C) and we want the user to tick at least one checkbox in order to validate the form, so any combination ([A], [B], [C], [A,B], [A,C], [B,C] ,[A,B,C]) would return true and no selection [] returns false.

What is the right approach to achieve this using Symfony validators on Doctrine objects?

Edit:
Each checkbox is mapped to it's own column in the database using Doctrine @ORM\Column(type="boolean")


Solution

  • Problem solved.

    Based on Symfony2 Class Constraint Validator documentation and on Added info on changes to setting validation subpath to UPGRADE-2.1.md

    In my entity class I've added:

    class Message
    {
    
      // ...
    
      // check if user selected at least one network to publish the message
      public function isNetworkSelected(ExecutionContext $context)
      {
        if (!$this->network_twitter && !$this->network_facebook && !$this->network_googleplus)
        {
          $context->addViolationAtSubPath('network_facebook', 'Please select at least one network', array(), null);
        }
      }
    
      // ...
    
    }
    

    In validation.yml:

    MY\MessageBundle\Entity\Message
        constraints:
            - Callback:
                methods:   [isNetworkSelected]