如何将模型转换器应用于Symfony2表单中的集合项?

spa*_*mat 7 php symfony

背景是

我有一个类型的Symfony2表单字段collection,其中集合项是entity类型.我使用Symfony 2.7.

问题是

到目前为止它仍然有效,但在这种情况下,我必须将模型数据转换器应用于Symfony Cookbook中描述的那些集合项.我使用这段代码:

<?php
$builder
    ->add(
        $builder
            ->create('items', 'collection', array(
                'type' => 'entity',
                'options' => array(
                    'class' => 'AppBundle:Item',
                    'property' => 'name',
                    'label' => 'Item',
                ),
                'label' => 'Items',
                'allow_add' => true,
                'allow_delete' => true,
                'delete_empty' => true,
                'prototype' => true,
                'required' => false,
            ))
            // $options['em'] is the entity manager
            ->addModelTransformer(new ItemToNumberTransformer($options['em']))
    )
;
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会将模型转换器应用于整个集合,而不是它的一个Item项.作为一种解决方法,我修改了变换器以使用项目/ ID的数组而不是仅使用单个项目/ id,但是这种类似于处理它的错误位置.在我看来好像这更像是一个语法问题.

问题是

有人知道如何将模型变换器应用于集合的每个项目吗?或者任何人都证实,由于Symfony框架中的限制,这根本不可能实现?

Pet*_*ley 9

我要说的collectionentity,您需要创建自己的类型,而不是创建类型.

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityManager;
/* Other use statements */

class ItemEntityType extends AbstractType
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new ItemToNumberTransformer($this->em));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'class'    => 'AppBundle:Item',
            'property' => 'name',
            'label'    => 'Item',
        ));
    }

    public function getParent()
    {
        return 'entity';
    }

    public function getName()
    {
        return 'appbundle_item_entity';
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其定义为服务

应用程序/配置/ services.yml

services:
    form.type.model.item_entity:
        class: AppBundle\Form\Type\ItemEntityType
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
          - {name: form.type, alias: appbundle_item_entity}
Run Code Online (Sandbox Code Playgroud)

现在,您可以将其指定为集合的类型

$builder
    ->create('items', 'collection', array(
        'type' => 'appbundle_item_entity'
        'label' => 'Items',
        'allow_add' => true,
        'allow_delete' => true,
        'delete_empty' => true,
        'prototype' => true,
        'required' => false,
    ))
Run Code Online (Sandbox Code Playgroud)

披露:我没有测试过这个,但它应该有效.