Search code examples
phpsymfonysymfony-formssymfony-2.8

Symfony 2.8 Form Builder isn't working


I have been making many Symfony forms within the controller and it is somewhat easier to me. But recently I have created a project in Symfony 2.8 which apparently is the version 2.8.34. However in there when I used the usual form builder it gave me the following error.

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

This is the source which game me the above error.

public function testAction(Request $request) {
    $form = $this->createFormBuilder()
            ->add('name', 'text', array('required' => true))
            ->add('phone', 'text', array('required' => true));

    return $this->render('AppBundle:Home:test.html.twig', array('form' => $form->createView()));

}

My project does not have any entities as it only sends captured data of this from through an API.

What I am doing wrong? This code worked in Symfony 2.8 other projects but this seems no longer working for me.


Solution

  • You just need to get the form out of the builder:

    $form = $this->createFormBuilder()
            ->add('name', 'text', array('required' => true))
            ->add('phone', 'text', array('required' => true))
            ->getForm();
    

    In fact createView is a method of Symfony\Component\Form\Form while in your example $form is an instance of Symfony\Component\Form\FormBuilder.