Synfony 2.8必须填写两个字段之一

时间:2018-12-11 16:10:05

标签: forms symfony required checked

我有此表单,我想检查两个字段(numberPlateexpirationDate)之一是否填写。

这是我的buildForm

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('type', ChoiceType::class, array(
            'choices_as_values' => true,
            'required' => true,
            'label' => 'Tipo Veicolo',
            'empty_data' => '',
            'empty_value' => '',
            'attr' => array('class'=> 'form-control select2'),
            'choices' => array('Auto' => 'Auto', 'Moto' => 'Moto', 'Camper' => 'Camper' ,'Barca' => 'Barca')
        ))
         ->add('numberPlate', TextType::class, array(
                'label' => 'Targa',
                'required' => false,
                'attr' => array(
                    'class'=> 'form-control',
                    'minlength' => 5,
                    'maxlength' => 7
                    )
            ))
         ->add('expirationDate', DateTimeType::class, array(
             'label' => 'Scadenza',
             'widget' => 'single_text',
             'input'  => 'datetime',
             'format' => 'dd/MM/yyyy',
             'attr' => array('class'=> 'form-control')
         ))
    ;
}

1 个答案:

答案 0 :(得分:2)

通过向您的实体添加callback constraint,可以确保其中一个字段不为空。

namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class YourModel
{
   /**
     * @Assert\Callback
     */
    public function validate(ExecutionContextInterface $context)
    {
        if (!$this->numberPlate && !$this->expirationDate) {
            $context->buildViolation('Targa or Scadenza is required')
              //optionally display the error at the numberPlate field, omit to display at the top of the form errors
              ->atPath('numberPlate')
              ->addViolation()
              ;
        }
    }
}

然后根据需要更新您的Scadenza字段。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        //...
         ->add('expirationDate', DateTimeType::class, array(
             'label' => 'Scadenza',
             'required' => false,
             'widget' => 'single_text',
             'input'  => 'datetime',
             'format' => 'dd/MM/yyyy',
             'attr' => array('class'=> 'form-control')
         ))
    ;
}

提交表单后,它将执行YourModel::validate方法,如果numberPlateexpirationDateempty,它将失败$form->isValid()。 / p>

请确保在进行更改后清除缓存,以刷新注释。

  

注意:这将适用于此实体模型所使用的任何/所有形式,   分开验证,您将需要实施validation groups