2016-01-29 38 views
3

複選框的設置標籤我有3場A類:Symfony2的:從類型字段

$id, $name, $isChecked 

我有一個formtype,我想,那$ id字段的標籤是$ name字段。那可能嗎?

/** 
* @param FormBuilderInterface $builder 
* @param array $options 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('id') 
     ->add('name') 
     ->add('is_checked', 'checkbox', array(
      'required' => false, 
      'label' => //This should be the $name field 
     )) 
    ; 
} 

例如我有我的類$ id = 1,$ name =「Car」。 後來我想這樣的:

/** 
* @param FormBuilderInterface $builder 
* @param array $options 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add('id') 
     ->add('name') 
     ->add('is_checked', 'checkbox', array(
      'required' => false, 
      'label' => 'Car', 
     )) 
    ; 
} 

- >「車」字應該是我班的$name變量。或者我如何在我的Twig/Form中將我的整個課程作爲複選框?我只想要,我可以檢查我的複選框,但我知道,確定"isChecked"是真的,然後我與我的ID和我的姓名有關係。但用戶需要知道,哪個複選框是哪個值,所以我需要「名稱」作爲標籤

+0

第一部分我有點困惑,如果'id'字段是'name'字段,你說的是標籤...你的意思是'is_checked'字段的標籤嗎?你想要它和'name'的標籤是一樣的,還是你希望它設置爲'name'的當前值? –

+0

也許你想要那樣的東西? :http://stackoverflow.com/questions/32458489/build-a-form-having-a-checkbox-for-each-entity – fito

+0

我編輯我的問題,請看看。 – Zwen2012

回答

4

Symfony中有關於如何執行此操作的良好文檔 - 您想要執行的操作是modify the form based on the underlying data。你要做的就是在PRE_SET_DATA上添加一個表單事件,它與起始數據一起使用。你buildForm()函數現在應該是這樣的:

use Symfony\Component\Form\FormEvent; 
use Symfony\Component\Form\FormEvents; 

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

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { 
     $entity = $event->getData(); 
     $form = $event->getForm(); 

     // set default label if there is no data, otherwise use the name 
     $label = (!$entity || null === $entity ->getId()) 
      ? 'Default' 
      : $entity->getName() 
     ; 

     $form->add('is_checked', 'checkbox', array(
      'required' => false, 
      'label' => $label, 
     )); 
    }); 
} 

另一種方法是隻對實體數據傳遞到您的模板和手動設置標籤有,但上述方案是更傳統的方式。

+0

太棒了! Ist工作!謝謝! – Zwen2012