【问题标题】:Symfony: Access an unmapped form field from a CollectionType in ControllerSymfony:从控制器中的 CollectionType 访问未映射的表单字段
【发布时间】:2020-03-01 06:16:24
【问题描述】:

我在 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 实体的数组,而不是表单本身。

所以换句话说,问题是:在表单集合中,我如何访问子 forms,而不是子 entities

【问题讨论】:

    标签: php symfony


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-09
      • 2017-01-15
      • 1970-01-01
      • 2016-10-12
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      相关资源
      最近更新 更多