1

我正在开发一个我们使用的项目,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()));

但我得到这个错误:

第 10 行的 FrontendBundle:Seller:newCompany.html.twig 中不存在变量“formCompany”

原因?我没有按应有的方式传递值,但如果我将它们传递为:

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

然后错误转换为:

ContextErrorException:可捕获的致命错误:传递给 Symfony\Component\Form\FormRenderer::renderBlock() 的参数 1 必须是 Symfony\Component\Form\FormView 的实例,给定数组

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

4

1 回答 1

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
  */
}
于 2014-03-02T20:05:13.000 回答