调用 isSumbitted() 和 isValid() 导致 "undefined method" 错误

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

我有一个从控制器中的 createFormBuilder() 创建的 Symfony 表单。但是在两个 IF 语句下,表单应该包含两组不同的字段。我的 Symfony 版本是 3.4.

/src/AppBundle/Controller/DefaultController.php

例如:这是基本形式。

$form = $this->createFormBuilder()
    ->add('name', TextType::class, ['required' => true]])
    ->add('email', EmailType::class, ['required' => true]])
    ->getForm();

if ($form->isSubmitted() && $form->isValid()) {
        ...
        ...
        ...
}

现在我需要在条件变为真时向此基本表单追加几个字段。下面显示的是我所做的,它给了我一个错误。

$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()) {
        ...
        ...
        ...
}

错误是:

Attempted to call an undefined method named "isSubmitted" of class "Symfony\Component\Form\FormBuilder".

我怎样才能完成这项工作?在不同条件下多次追加字段?

尝试:

$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()) {
        ...
        ...
        ...
}