Sunil Rawat
Sunil Rawat

Reputation: 709

Call to a member function get() on a non-object Symfony2

Hi I want to render a form in symFony2 with dynamic fields added to it. So I have wrote code in controller as:

public function getDataAction(){
    $handler = new AnotherClass();
    $object = $handler->getForm($getAdditionalData);
}

and "AnotherClass" defined as following:

class AnotherClass extends  Controller implements requiredInterface{

public  function getForm($formData){
 //Here i want to write Logic to render a dynamic form with dynamic fields
    $form = $this->createFormBuilder($formData)
             ->setAction($this->generateUrl('me_route_go'))

        // Set form field of additional data
         foreach ($formData as $k => $v) {
             $form->add($k, 'text');
         }

         //Create form and submit button
         $form = $form->add('submit', 'submit')->add('Cancel', 'reset')->getForm();
         $form = $form->getForm();
     }
  }

 }

But here I am getting following error:

Error: Call to a member function get() on a non-object.

return $this->container->get('form.factory')->createBuilder($type, $data, $options);

Please suggest what could be the issue.

thanks in advance..

Upvotes: 1

Views: 662

Answers (1)

Raphaël Malié
Raphaël Malié

Reputation: 4002

Your controller AnotherClass requires the Dependency Injection Container since you are extending the base Controller class, you have to set it after you instantiate it :

public function getDataAction(){
    $handler = new AnotherClass();
    $handler->setContainer($this->container);
    $object = $handler->getForm($getAdditionalData);
}

You can also create it as a service :

services.yml

name.of.your.service:
    class:     Path\To\AnotherClass
    calls:
        - [setContainer, [ "@service_container" ]]

And then :

public function getDataAction(){
    $handler = $this->get('name.of.your.service');
    $object = $handler->getForm($getAdditionalData);
}

Upvotes: 3

Related Questions