2012-11-13 30 views
1

我有兩個實體,A和B. A與B.使用集合字段類型的選項每個孩子實體數據

我嵌入一個裏面有五名B形成一個一對多的關係表格使用collection字段類型。爲了做到這一點,我在AController中創建了5個A-B關係。我想這樣做是使用每個這種B實體的領域建立自己的標籤形式收藏。

所以,我有以下代碼:

//AController 
$a = new A(); 

//Followinf returns an array of 5 B entities 
$bs = $this->getDoctrine->getEntityManager()->getRepository('MyBundle:B')->findBy(array(
    'field' => 'value', 
)); 

foreach ($bs as $b) { 
    $a->addB($b); 
} 

$form = $this->createForm(new AType(), $a); 

return array(
    'a' => $a, 
    'form' => $form->createView(), 
); 

//AType 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('a_field') 
     ->add('another_field') 
     ->add('bs', 'collection', array(
       'type' => new BType(), 
       'options' => array(
        'label' => 'i want to configure it depending on current B data', 
       ) 
       )) 
     ; 
} 

我發現這個相關主題:

Symfony form - Access Entity inside child entry Type in a CollectionType

但要注意,因爲它訪問子窗體中的數據,這是不同的。我想從父窗體訪問子數據並將其用於集合中的每個子標籤。

我知道我可以訪問使用$builder->getData()->getBs();孩子數據,但我想不出如何在以後使用它爲每一個孩子的形式。

我知道還有我能做到這一點的看法,通過實體循環和使用循環索引手動呈現每個集合元素,但我想這樣做的形式。

非常感謝。

回答

0

我想你想:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $data=someProcessingFunction($builder->getData()->getBs()); 
    $builder 
     ->add('a_field') 
     ->add('another_field') 
     ->add('bs', 'collection', array(
       'type' => new BType(), 
       'options' => array(
        'label' => $data, 
       ) 
       )) 
     ; 
} 

其可能與不談,你可以在一個單獨的$ builder-添加的東西到年底>添加通話:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('a_field'); 
    $builder->add('another_field'); 
    $data=someProcessingFunction($builder->getData()->getBs()); 
    $builder->add('bs', 'collection', array(
       'type' => new BType(), 
       'options' => array(
        'label' => $data, 
       ) 
       )) 
     ; 
} 

如果您正在尋找用於標籤每一個唯一然後這第二種方法是爲更好:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('a_field'); 
    $builder->add('another_field'); 

    $data=someProcessingFunction($builder->getData()->getBs()); 
    foreach ($data as $k=>$v){ 
    $builder->add('b'.$k, null, array(
        'label' => $v, 
       )) 
     ; 
    } 
} 

或類似

相關問題