问题
I have a Symfony form that is created from createFormBuilder() in the controller. But under two IF statements the form should carry two different set of fields. My Symfony version is 3.4.
/src/AppBundle/Controller/DefaultController.php
Ex: This is the basic form.
$form = $this->createFormBuilder()
->add('name', TextType::class, ['required' => true]])
->add('email', EmailType::class, ['required' => true]])
->getForm();
if ($form->isSubmitted() && $form->isValid()) {
...
...
...
}
Now I need to append few more fields to this basic form when a condition becomes true. Shown below is what I did and it gives me an error.
$form = $this->createFormBuilder()
->add('name', TextType::class, ['required' => true]])
->add('email', EmailType::class, ['equired' => true]]);
if($a==true){
$form->add('username', TextType::class, ['required' => true]])
->add('password', PasswordType::class, ['required' => true]]);
}
$form->getForm();
if ($form->isSubmitted() && $form->isValid()) {
...
...
...
}
The error is:
Attempted to call an undefined method named "isSubmitted" of class "Symfony\Component\Form\FormBuilder".
How can I get this done? Append fields at multiple occasions under different conditions?
回答1:
Try:
$formbuilder = $this->createFormBuilder()
->add('name', TextType::class, ['required' => true]])
->add('email', EmailType::class, ['equired' => true]]);
if($a==true){
$formbuilder->add('username', TextType::class, ['required' => true]])
->add('password', PasswordType::class, ['required' => true]]);
}
$form = $formbuilder->getForm();
if ($form->isSubmitted() && $form->isValid()) {
...
...
...
}
来源:https://stackoverflow.com/questions/57765916/calls-to-issumbitted-and-isvalid-result-in-undefined-method-error