Calls to isSumbitted() and isValid() result in “undefined method” error

这一生的挚爱 提交于 2021-02-05 12:26:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!