Symfony:从 Controller 中的 CollectionType 访问未映射的表单字段 [英] Symfony: Access an unmapped form field from a CollectionType in Controller

查看:34
本文介绍了Symfony:从 Controller 中的 CollectionType 访问未映射的表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form collection like this in 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 实体的数组,而不是表单本身.

...I'm getting an array of the Child entities, not the forms themselves.

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

So the question in other words is: In a form collection, how can I access the child forms, not the child entities?

推荐答案

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

I couldn't find a solution anywhere, so I'm posting how I finally solved it:

/** @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

这篇关于Symfony:从 Controller 中的 CollectionType 访问未映射的表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆