2012-07-26 50 views
0

如何在呈現表單時爲集合中的第一個項目設置只讀選項?Symfony表單集合只讀第一項

我簡單的模型:

對我的模型
class Main 
{ 
    public $others; 
} 

class Other 
{ 
    public $field1; 

    public $field2; 
} 

簡單的表單類型:

class MainType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('others', 'collection', array(
       'type' => new OtherType(), 
       'allow_delete' => true, 
       'allow_add' => true, 
       'by_reference' => false, 
      )) 
     ; 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'App\MyBundle\Entity\Main', 
     )); 
    } 

    public function getName() 
    { 
     return 'maintype'; 
    } 
} 

class OtherType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('field1') 
      ->add('field2') 
     ; 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'App\MyBundle\Entity\Other', 
     )); 
    } 

    public function getName() 
    { 
     return 'othertype'; 
    } 
} 

而且簡單的操作方法,我的控制器

//... 
public function indexAction($id) 
{ 
    $main = new Main(); 

      $other1 = new Other(); 
    $other1->field1 = 'a'; 
    $other1->field2 = 'b'; 
    $main->others[] = $other; 

      $other2 = new Other(); 
    $other2->field1 = 'c'; 
    $other2->field1 = 'd'; 
    $main->others[] = $other; 

    $form = $this->createForm(new MainType(), $main); 

    //...isValid, persist, flush... 
} 
//... 

我可以做一個條件手動渲染時表格,但我想知道是否可以在表格代碼中輸入這樣的限制。

回答

2

目前不可能讓集合的行具有不同的選項。我邀請您在issue tracker上創建功能請求,如果您覺得這將是一個有價值的補充。

+0

+1只是好奇@Bernhard。實體字段類型也是這種情況嗎?如果有人希望只爲實體字段類型的第一個條目設置讀取,那麼這可能嗎? – Mick 2013-02-16 11:40:43

+0

這取決於您是否將該字段渲染爲下拉菜單,複選框或單選按鈕? – 2013-04-17 22:59:24