简体   繁体   English

添加约束以比较提交形式中的两个输入

[英]Add constraint to compare two inputs in submitted form

A form with start and end dates is submitted and i need a Constraint which would check if the end date is later than start date. 带有开始日期和结束日期的表单已提交,我需要一个约束条件 ,该约束条件将检查结束日期是否晚于开始日期。

The problem is that i can not attack a Constraint to the form itself, only to the field thus i can only get the field value, no values from other form inputs. 问题是我不能对表单本身进行约束,而只能对字段进行约束,因此我只能获取字段值,而不能从其他表单输入获取值。

Here is the code which tries to use the callback 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
            })
        ],
    ])

For example: 例如:

  • Start date 2017-01-01 End date 2018-01-01 The form would be valid. 开始日期2017-01-01结束日期2018-01-01该表格将有效。

  • Start date 2017-01-01 End date 2016-12-30 The form would be invalid. 开始日期2017-01-01结束日期2016-12-30表格无效。

 $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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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