简体   繁体   中英

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.

  • Start date 2017-01-01 End date 2016-12-30 The form would be invalid.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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