Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

How to set required depends on choice type in symfony?

In have the form builder :

 $formBuilder->add('customDuplicatedId', TextType::class,
            [
                'required' => false,
                'data' => implode(",", $duplicatedIds),
                'mapped' => false,
                'help' => "Enter singleCheck Id separate by ',' "
            ]
        )
        ->add('isDuplicated', ChoiceType::class,
            [
                'required' => true,
                'data' => $entity->getSingleCheck()->isDuplicated(),
                'mapped' => false,
                'label' => 'Hidden (duplicated)',
                'expanded' => true,
                'choices'  => [
                    'Yes' => true,
                    'No' => false,
                ],
                'placeholder' => false
            ]);

I would like when user choose Yes, the text input will required. When user choose No , the text input will not required. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it by using a Callback constraint. It is almost like defining a custom constraint (and definitely the way to go if you plan on reusing the logic) but you can use a closure or other callable directly in the form type (check the reference).

->add('customDuplicatedId', TextType::class,
    [
        // Other options omitted
        'constraints' => new Callback(
            function($duplicateId, ExecutionContextInterface $context) {
                // Get the field we depend on by traversing the form
                // Current field: customDuplicateId
                $duplicated = $context->getObject()
                      // Parent: Form
                      ->getParent()
                      // Field isDuplicated -> value
                      ->get('isDuplicated')->getData();
                // 'choices' returns a bool in this case, so just apply logic
                if ($duplicated && empty($duplicateId)) {
                    $context->buildViolation('This value is required')
                        ->atPath('customDuplicatedId')
                        ->addViolation();
                }
            }
        ),
    ]
)

It is also possible to set the constraint globally in the form defaults without binding it to an specific field and use the context to access the targets. In a case like this where you need access to multiple fields it might be clearer. In that situation the first argument will be empty and getObject will return the form itself (so there's no need to call getParent).

In a custom form type class:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'constraints' => // ...
    ]);
}

Creating a builder in a controller (extending AbstractController):

$builder = $this->createFormBuilder($data, [ 'constraints' => /* ... */ ]);
$builder->add(/* ... */);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...