简体   繁体   中英

Symfony - Validate if the values are not repeated in a combobox form

I have a form with a combobox and when submited the points values can not be repeated

The form

->add('points', 'choice', array(
                    'attr' => array('class' => 'form-control m-b'),
                    'choices' => array(
                        '0' => '0',
                        '1' => '1',
                        '2' => '2',
                        '3' => '3',
                        '4' => '4',
                        '5' => '5',
                        '6' => '6',
                        '7' => '7',
                        '8' => '8',
                        '9' => '9',
                        '10' => '10',
                    )
                ))

the version of symfony is 2.6

Any help will be appreciated

You need a custom validation for this and you can create a custom validation using callbacks as follows.

Assuming points property as an array

On your entity class

If you are using annotation as a validation format:

class Author
{
    private $points;

    /**
     * @Assert\Callback
     */
    public function validate(ExecutionContextInterface $context)
    {
        if(sizeof(array_unique($this->points)) !== sizeof($this->points)){
            $context->buildViolation('Values must be unique')
                    ->atPath('points')
                    ->addViolation();
        }
    }
}

If you are using YAML as a validation format, in this case you need to remove from validate function above:

/**
 * @Assert\Callback
 */

...

# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\Author:
    constraints:
        - Callback: [validate]

For more information about Callbacks please refer to Symfony Callbacks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM