在非对象Symfony2上调用成员函数get()

时间:2016-10-04 09:19:31

标签: symfony

您好我想在symFony2中添加一个表单并添加动态字段。 所以我在控制器中编写了代码:

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

和“AnotherClass”定义如下:

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();
     }
  }

 }

但是我在这里得到以下错误:

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

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

请提出可能存在的问题。

提前感谢..

1 个答案:

答案 0 :(得分:3)

您的控制器AnotherClass需要依赖注入容器,因为您正在扩展基本Controller类,您必须在实例化它之后设置它:

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

您也可以将其创建为服务:

services.yml

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

然后:

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