Symfony:从Controller中的CollectionType访问未映射的表单字段

时间:2019-11-04 22:06:12

标签: php symfony

我在Symfony 3.4中有一个这样的表单集合:

// MainType.php

$builder->add('children', CollectionType::class, ['entry_type' => ChildType::class]);
// ChildType.php

$builder->add('myField', null, ['mapped' => false]);
// plus more fields, mapped to the underlying `Child` entity
// Controller

$form = $this->createForm(MainType::class, ['children' => $children]);
$form->handleRequest($request);
if ($form->isSubmitted() and $form->isValid()) {
    // How can I access the data of `myField` here?
}

使用通常的方法进行操作

$data = $form->getData();

...我正在获取Child实体的数组,而不是表单本身。

换句话说,问题是:在表单集合中,如何访问子表单,而不是子实体

1 个答案:

答案 0 :(得分:2)

我在任何地方都找不到解决方案,所以我发布了我最终解决方案的方法:

/** @var Symfony\Component\Form\Form $formChild */
foreach ($form->get('children') as $formChild)
{
    $formChild->get('myField')->getData(); // That's it!
}

基本原理在https://symfony.com/doc/current/form/without_class.html

中有解释
相关问题