如何将 Symfony 表单中的默认选项与新选项合并

Cor*_*ISE 3 php symfony-forms symfony

我有一个表单和一个子表单,我想合并定义为默认值的约束值和根表单添加的约束值。

我的子表单:

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']),
            ])
        ;
    }

}
Run Code Online (Sandbox Code Playgroud)

我使用新的约束选项将表单添加到根目录:

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

正如预期的那样,约束选项现在包含 3 个元素,并且回调约束未合并。我尝试了这个解决方案:Default Options for symfony 2 forms are being overridden not merged but the callback method似乎没有被调用

谢谢,科朗坦

Ash*_*son 6

在您的父表单类型上尝试类似的操作:

...

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(...),
            ...
        ]);
    });
}

...
Run Code Online (Sandbox Code Playgroud)