Search code examples
phpsymfonydatesymfony-formssymfony-3.3

Date after another date in symfony form


I have a form that contain 2 dates: start date(datedebut) and end date(datefin). I want the end date to be always after the start date. How can i do that?

My form type:

class ReservationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('datedebut',DateType::class,array(
                'widget' => 'choice',
                'years' => range(date('Y'), date('Y')+20),
            ))
            ->add('datefin',DateType::class,array(
                'widget' => 'choice',
                'years' => range(date('Y'), date('Y')+20),
            ))
            ->add('nbplaces')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bridge\TravelBundle\Entity\Reservation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'Bridge_TravelBundle_Reservation';
    }
}

Solution

  • Usually these kind of tasks are solved by adding validation constraints to check if value of one field is greater then the other. Implement callback validation constraint as stated in the documentation: http://symfony.com/doc/current/reference/constraints/Callback.html You can also create your custom class constraint validator and place validation logic there: http://symfony.com/doc/current/validation/custom_constraint.html

    This way whenever a user tries to submit value of datefin which is less than selected value of datedebut he will see a validation error and the form will not be processed.

    After that you can always add some javascript code that will filter available dates in datefin field after value in datedebut field is changed.

    Also you can use dynamic form modification to render the second date field (and filter its available dates on server side) only if value of the first one is submitted. Check this out: http://symfony.com/doc/current/form/dynamic_form_modification.html