将多个表单传递给Symfony2中不同服务中定义的视图

时间:2014-03-02 19:58:51

标签: php symfony dependency-injection symfony-forms symfony-2.4

我正在处理我们使用DependencyInjection的项目,因此我在src\Common\CommonBundle\Resources\config\services.yml中有以下定义:

services:
    address.form:
        class: Wuelto\Common\CommonBundle\Controller\FormAddressController
        arguments: [@form.factory, @doctrine.orm.entity_manager]
    address_extra_info.form:
        class: Wuelto\Common\CommonBundle\Controller\FormAddressExtraInfoController
        arguments: [@form.factory, @doctrine.orm.entity_manager]

src\Company\RegisterCompanyBundle\Resources\config\services.yml

services:
    registercompany.form:
        class: Wuelto\Company\RegisterCompanyBundle\Controller\FormRegisterCompanyController
        arguments: [@form.factory, @doctrine.orm.entity_manager]

这是控制器背后的代码(只有一个,其余的只是类更改):

class FormAddressExtraInfoController {

    public function __construct(FormFactoryInterface $formFactory, EntityManager $em) {
        $this->formFactory = $formFactory;
        $this->em = $em;
    }

    private function getEntity($id) {
        $entity = new AddressExtraInfo();

        try {
            if (isset($id)) {
                $entity = $this->em->getRepository("CommonBundle:AddressExtraInfo")->find($id);
            }
        } catch (\Exception $e) {

        }

        return $entity;
    }

    public function getAction($id = null) {
        $entity = $this->getEntity($id);
        $form = $this->formFactory->create(new AddressExtraInfoType($id), $entity, array('method' => 'POST'));
        return array('formAddressExtraInfo' => $form->createView());
    }

}

所以这就是问题所在。在这些捆绑包之外的另一个控制器(\Website\FrontendBundle\Controller\sellerController.php)中,我试图通过使用这段代码来获取$formXXX视图:

$this->render('FrontendBundle:Seller:newSellerLayout.html.twig', array($this->get('registercompany.form')->getAction(), $this->get('address_extra_info.form')->getAction()));

但是我收到了这个错误:

  

变量" formCompany"在...中不存在   FrontendBundle:卖家:newCompany.html.twig第10行

原因?我没有按原样传递值,但如果我将它们传递为:

$this->render('FrontendBundle:Seller:newSellerLayout.html.twig', array('formCompany' => $this->get('registercompany.form')->getAction(), 'formAddressExtraInfo' => $this->get('address_extra_info.form')->getAction()));

然后错误转换为:

  

ContextErrorException:Catchable Fatal Error:传递给的参数1   Symfony \ Component \ Form \ FormRenderer :: renderBlock()必须是一个实例   Symfony \ Component \ Form \ FormView,给定数组

我不知道如何解决这个问题或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

错误是明确且有意义的,告诉您它需要FormView实例并且您已使用getAction()方法传递了数组,例如return array('formAddressExtraInfo' => $form->createView());您需要return $form->createView()

public function getAction($id = null) {
    $entity = $this->getEntity($id);
    $form = $this->formFactory->create(new AddressExtraInfoType($id), $entity, array('method' => 'POST'));
    return  $form->createView();
 /*createView() is an instance of Symfony\Component\Form\FormView 
  *which symfony expects while rendering the form
  */
}