【问题标题】:Accessing collection form field from controller in Symfony2从 Symfony2 中的控制器访问集合表单字段
【发布时间】:2014-02-14 16:43:57
【问题描述】:

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

// ...
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();

但它不起作用。

【问题讨论】:

    标签: php forms symfony controller


    【解决方案1】:

    我想出了解决办法。因为集合是 ArrayCollection,所以您必须通过提供正确的索引来访问与您要访问的对象相对应的集合元素。因为这个集合中只有一个项目(一个单独的表单类型),所以下面的语句就可以了:

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

    换句话说,

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-09
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多