2013-11-15 64 views
0

我有2個實體:索納塔聯繫configureFormFields使用自定義表單類型

1提問

/** 
* @ORM\Table() 
* @ORM\Entity 
*/ 
class Question 
{ 
    /** 
    * @ORM\Column(type="smallint", nullable=false) 
    */ 
    private $type; 

    /** 
    * @ORM\Column(type="string", length=255) 
    */ 
    private $test_field; 

    /** 
    * @ORM\OneToMany(targetEntity="Option", mappedBy="question") 
    */ 
    private $options; 
} 

2.選項

/** 
* @ORM\Table() 
* @ORM\Entity 
*/ 
class Option 
{ 
    /** 
    * @ORM\ManyToOne(targetEntity="Question", inversedBy="options") 
    * @ORM\JoinColumn(name="question_id", referencedColumnName="id") 
    */ 
    private $question; 

    /** 
    * @ORM\Column(type="string", length=255, nullable=true) 
    */ 
    private $field_for_question_type_x; 

    /** 
    * @ORM\Column(type="string", length=255, nullable=true) 
    */ 
    private $field_for_question_type_y; 

    /** 
    * @ORM\Column(type="string", length=255, nullable=true) 
    */ 
    private $field_for_question_type_z; 
} 

基礎上Question類型有需求使用不同的formType,其中只包含一些Option字段。

例如:

Questiontype = X應該與字段形式$field_for_question_type_x

Questiontype = Y應該與字段$field_for_question_type_y

等形式

我還那些不同formTypes創建所以問題是我怎麼能告訴索納塔管理$formMapper添加這種形式的集合(基於Question實體類型)?

目前,它看起來像這樣:

protected function configureFormFields(FormMapper $formMapper) 
{ 
    $Question = $this->getSubject(); 

    $formMapper->add('test_field'); 

    if ($Question->getId()) { 
     $formMapper->with('Options'); 

     switch ($Question->getType()) { 
      case 'X': 
       // Here I would need to add collection of \My\Bundle\Form\OptionXType() 
       $formMapper->add('options', ????????); 
       break; 
      case 'Y': 
       // Here I would need to add collection of \My\Bundle\Form\OptionYType() 
       $formMapper->add('options', ????????); 
       break; 
     } 
    } 
} 

什麼應該被添加到提供這樣的功能?

回答

0

答案是很簡單:

->add('options', 'sonata_type_collection', 
    array(), 
    array(
     'edit' => 'inline', 
     'inline' => 'table', 
     'admin_code' => $type_based_admin_code # each has custom form configuration 
    ) 
)