2017-01-09 92 views
0

我想將一個對象從控制器傳遞給我的表單生成器,以便稍後可以將它用於我的ChoiceType字段。我如何實現這一目標?從控制器傳遞一個對象到表單類型

這是我的控制器:

$choices   = []; 
    $table2Repository = $this->getDoctrine()->getRepository('SwipeBundle:Company'); 
    $table2Objects = $table2Repository->findAll(); 

    foreach ($table2Objects as $table2Obj) { 
     $choices[$table2Obj->getId()] = $table2Obj->getId() . ' - ' . $table2Obj->getName(); 
    } 

    $form = $this->createForm(SubAgentType::class, $choices, array(
     'action'=>$this->generateUrl('backend_sub_agent_create'), 
     'method'=>'POST' 
    )); 

這是我SubAgentType.php

class SubAgentType extends AbstractType { 

    protected $choices; 

    public function __construct (Choices $choices) 
    { 
     $this->choices = $choices; 
    }  

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 

     $builder->add('company_id', ChoiceType::class, array(
      'mapped' => false, 
      'choices' => $choices, 
     )); 

問題是我得到的錯誤如下。

Catchable Fatal Error: Argument 1 passed to MyBundle\Form\SubAgentType::__construct() must be an instance of MyBundle\Form\Choices,

回答

0

要回復你的問題:

myform.type: 
    class: AppBundle\Form\MyFormType 
    arguments: 
     - '@doctrine.orm.entity_manager' 
    tags: 
     - { name: form.type } 
在MyFormType

在services.yml文件

/** 
* @var EntityManagerInterface 
*/ 
protected $em; 

/** 
* LicenseeType constructor. 
* 
* @param EntityManagerInterface $em 
*/ 
public function __construct(EntityManagerInterface $em) 
{ 
    $this->em = $em; 
} 

/** 
* @param FormBuilderInterface $builder 
* @param array    $options 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $choices   = []; 
    $table2Repository = $this-em->getRepository('SwipeBundle:Company'); 
    $table2Objects = $table2Repository->findAll(); 

    foreach ($table2Objects as $table2Obj) { 
     $choices[$table2Obj->getId()] = $table2Obj->getId() . ' - ' . $table2Obj->getName(); 
    } 

    ... 

但是,很顯然,你不需要這樣做,如果你正確定義你的實體關係。

+0

'沒有擴展能夠加載「myform.type」的配置' – phpmeter

0

嘗試解決您的構造函數中SubAgentType,$選擇並不需要是選擇的子類型:

public function __construct ($choices) 
{ 
    $this->choices = $choices; 
} 

如果你在你的控制器注入一個數組,那麼構造函數必須接受一個數組。

+0

它仍然不能工作 – phpmeter

+0

但你應該有另一種行爲,現在是什麼? – Rawburner

相關問題