php - 从 Symfony2 中的 Controller 访问集合表单字段

标签 php forms symfony controller

我正在构建一个从 Symfony2 中的两个不同类型类呈现的表单(使用第二个类型的集合类型),但我无法从 Controller 中的集合字段访问数据。下面是外部 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,
            ));
    }
    // ...

我想从我的 Controller 访问部门字段,但我不知道该怎么做。我试过做类似的事情

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

但它不起作用。

最佳答案

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

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

换句话说,

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

返回对应于我的单独表单类型 PositionCreateType() 的实体 (Position)。

关于php - 从 Symfony2 中的 Controller 访问集合表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21784850/

相关文章:

symfony - 驱动程序 : SQLSTATE[HY000] [1045] Access denied for user 'db_user' @'localhost' (using password: YES) 发生异常

php - 配置 PHP 以将错误存储在数据库中

php - Codeigniter Datamapper save() 实际上没有保存到数据库

php - 在另一个字符串中的某个单词之前插入字符串

php - 付款方式支票/汇票未显示在结帐页面中

html - 带有普通 HTML 的表单中单选输入中的多个值

php - Zend Form AJAX 弹出窗口与 jQuery

java - 在没有字段绑定(bind)的情况下使用表单错误?

php - 为什么 Symfony 2 中有两个 Cookie 类?

php - Symfony 2 Twig 表单功能不可用