2014-02-14 49 views
4

我正在构建一个表单,它是从Symfony2中的两个不同类型类(使用第二个类型的集合类型)呈现的,我无法从控制器的集合字段中访问数据。下面是外formBuilders方法的代码:从Symfony2中的控制器访问集合表单字段

// ... 
class EmployeeCreateType extends AbstractType 
{ 
public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      // ... 
      ->add('positions', 'collection', array(
       'type' => new PositionCreateType(), 
       'label' => ' ', 
       'allow_add' => false, 
       'prototype' => false, 
      )); 
    } 
// ... 

,这里是从PositionCreateType内buildForm方法的代码:

// ... 
    class PositionCreateType extends AbstractType 
    { 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('title', 'choice', array(
       'label' => 'Title: ', 
       'choices' => array(
        'Senior Engineer', 
        'Staff', 
        'Engineer', 
        'Senior Staff', 
        'Assistant Engineer', 
        'Technique Leader', 
       ), 
       'expanded' => true, 
       'multiple' => false, 
      )) 
      ->add('department', 'choice', array(
       'label' => 'Department: ', 
       'choices' => array(
        'd001' => 'Marketing', 
        'd002' => 'Finance', 
        'd003' => 'Human Resources', 
        'd004' => 'Production', 
        'd005' => 'Development', 
        'd006' => 'Quality Management', 
        'd007' => 'Sales', 
        'd008' => 'Research', 
        'd009' => 'Customer Service', 
       ), 
        'expanded' => true, 
        'multiple' => false, 
      )); 
    } 
    // ... 

我想从我的控制器访问该部门领域,但我无法弄清楚如何去做。我试过做类似

$form->get('positions')->get('department')->getData(); 

但它不工作。

回答

3

我想出了解决方案。由于集合是ArrayCollection,因此必须通过提供正确的索引来访问与要访问的对象相对应的集合元素。因为有了这个集合(单独的表单类型)中只有一个项目,下面的语句做的伎俩:对应

$form->get('positions')->getData()->get('0')->getDepartment(); 

换句话说,

$form->get('positions')->getData()->get('0') 

返回实体(位置)我单独的表单类型,PositionCreateType()。