我正在构建一个从 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/