Corentin HEMBISE
Corentin HEMBISE

Reputation: 31

How to merge default options with new options in Symfony forms

I have a form and a subform and I would like to merge the constraints values defined as default and theses added by the root form.

My subform :

class DatesPeriodType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('start', DateType::class, [
                'constraints' => [
                    new Date(),
                ]
            ])
            ->add('end', DateType::class, [
                'constraints' => [
                    new Date(),
                ]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefault('error_bubbling', false)
            ->setDefault('constraints', [
                new Callback([$this, 'validate']),
            ])
        ;
    }

}

I add my form to the root with new constraints options :

        $builder
            ->add('judgmentPeriod', DatesPeriodType::class, [
                'constraints' => [
                    new Valid(),
                    new Callback([
                        'callback' => [$this, 'datesAreEmpty'],
                        'groups' => ['insertionPeriod'],
                    ]),
                    new Callback([
                        'callback' => [$this, 'validDates'],
                        'groups' => ['judgmentPeriod'],
                    ]),
                ]
            ])

As expected, the constraint options contains now 3 elements and the Callback constraint is not merged. I tried this solutions : Default Options for symfony 2 forms are being overridden not merged but the callback method not seems to be called

Thanks, Corentin

Upvotes: 3

Views: 1120

Answers (1)

Ashley Dawson
Ashley Dawson

Reputation: 109

Try something like this on your parent form type:

...

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setNormalizer('constraints', function (Options $options, $value) {
        // Merge the child constraints with the these, the parent constraints
        return array_merge($value, [
            new Assert\Callback(...),
            ...
        ]);
    });
}

...

Upvotes: 8

Related Questions