【问题标题】:Symfony2 form validation for multiple field require only oneSymfony2 表单验证多个字段只需要一个
【发布时间】:2015-08-04 11:39:31
【问题描述】:

我在一种形式中有 5 个字段,如下所示:

类 ItempriceFormType 扩展 AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('pergramprice', 'text', array('required' => false))
            ->add('eighthprice', 'text', array('required' => false))
            ->add('quarterprice', 'text', array('required' => false))
            ->add('halfprice', 'text', array('required' => false))
            ->add('ounceprice', 'text', array('required' => false))
    ;
}

public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'Acme\FrontBundle\Entity\Itemprice',
    ));
}

public function getName() {
    return 'items_price';
}

}

我只想验证一个字段意味着只需要 5 个字段中的一个字段。那么如何通过 symfony 2 验证来实现这一点。

提前致谢。

【问题讨论】:

    标签: validation symfony


    【解决方案1】:

    您可以使用自定义验证器基于多个字段进行验证,在您的 Itemprice 实体中定义 @Assert\Callback 注释并检查所有价格字段是否为空然后显示错误

    use Symfony\Component\Validator\Constraints as Assert;
    use Symfony\Component\Validator\ExecutionContextInterface;
    /**
     * @Assert\Callback(methods={"checkPriceValidation"})
     */
    class Itemprice
    {
        public function checkPriceValidation(ExecutionContextInterface $context)
        {
            $pergramprice = $this->getPergramprice();
            $eighthprice = $this->getEighthprice();
            $quarterprice = $this->getQuarterprice();
            $halfprice = $this->getHalfprice();
            $ounceprice = $this->getOunceprice();
            if(
            empty($pergramprice)
            && empty($eighthprice)
            && empty($quarterprice)
            && empty($halfprice)
            && empty($ounceprice)
            ){
                $context->addViolationAt('pergramprice', 'Please enter atleast one price');
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 2011-12-31
      相关资源
      最近更新 更多