douweng9427 2016-01-08 12:43
浏览 18
已采纳

Symfony - 验证值是否以组合框形式重复

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

  • 写回答

1条回答 默认 最新

  • doutuo2829 2016-01-08 14:29
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line