添加约束以比较提交表单中的两个输入

时间:2017-05-29 13:09:55

标签: php symfony-3.2

提交了包含开始日期和结束日期的表单,我需要Constraint来检查结束日期是否晚于开始日期。

问题是我无法攻击约束到表单本身,只能攻击字段,因此我只能得到字段值,没有来自其他表单输入的值。

以下是尝试使用回调约束的代码。

class MyCustomType extends AbstractType
{
/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('dateFrom', null, [
        'constraints' => [
            new NotBlank([
                'message' => 'Error'
            ])
        ],
    ])
    ->add('dateTo', null, [
        'constraints' => [
            new NotBlank([
                'message' => 'Error!'
            ]),
            new Callback(function($object, ExecutionContextInterface $context, $payload) {
                // Ėobject there is the field on which i check the constraint and i have no possible way to get the dateFrom value here
            })
        ],
    ])

例如:

  • 开始日期2017-01-01 截止日期2018-01-01 表格有效。

  • 开始日期2017-01-01 截止日期2016-12-30 表格无效。

1 个答案:

答案 0 :(得分:0)

 $form=$builder
    ->add('dateFrom', null, [
        'constraints' => [
            new NotBlank([
                'message' => 'Error'
            ])
        ],
    ])
    ->add('dateTo', null, [
        'constraints' => [
            new NotBlank([
                'message' => 'Error!'
            ]),
            new Callback(function($object, ExecutionContextInterface $context, $payload) {
                // Ėobject there is the field on which i check the constraint and i have no possible way to get the dateFrom value here
            })
        ],
    ]);

//Before submit controll date.
$builder->addEventListener(FormEvents::PRE_SUBMIT,function (FormEvent $event)
{

    //Form data
    $data=$event->getData();
    if($data['dateFrom']>$data['dateTo'])
    {
        //valid
    }
    else
    {
        //not valid
    }

}