【问题标题】:Array-type property and Form CollectionType with data transformer带有数据转换器的数组类型属性和 Form CollectionType
【发布时间】:2017-06-02 21:37:52
【问题描述】:

我有一个属性设置为数组的实体

/**
 * @ORM\Column(type="array")
 */
private $labels = [];

这个数据数组存储标签的翻译,如

[
   'en' => 'foo-in-English',
   'de' => 'foo-in-German',
   'ru' => 'foo-in-Russian'
]

我有一个表单,其类型为以下标签设置:

$builder
    ->add('labels', CollectionType::class);

请注意,entry_type 在此处默认(正确)为TextType。保持原样,模板将显示文本字段,例如:

Labels:       en: _____FOO IN ENGLISH____
              de: _____FOO IN GERMAN_____
              ru: _____FOO IN RUSSIAN____

但是,我希望以实际语言 name 而不是两个字母 code 作为标签来显示字段,例如:

Labels:       English: _____FOO IN ENGLISH____
              German:  _____FOO IN GERMAN_____
              Russian: _____FOO IN RUSSIAN____

我还想确保显示所有我选择/支持的语言 - 即使它们目前没有价值。

所以,这似乎是 DataTransformer 的合适位置,但尽我所能,我无法让这个概念在 Form 类内工作。似乎尝试转换集合类型的数据比文本等简单类型更困难(或不可能?)。

我已经通过在将数据提交到表单之前和在持久性之前处理表单之后转换控制器中的数据来克服这个问题。例如

    $this->transformTranslations($fooEntity);
    $form = $this->createForm(FooType::class, $fooEntity);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $fooEntity = $form->getData();
        $this->reverseTransformTranslations($fooEntity);
        $this->getDoctrine()->getManager()->persist($fooEntity);
        $this->getDoctrine()->getManager()->flush();
    ...

我想知道是否有人有更好的方法(例如如何使用普通数据或模型转换器)。我似乎在网上找不到太多关于使用数据转换器和集合类型的信息。蒂亚!

【问题讨论】:

    标签: forms symfony doctrine-orm


    【解决方案1】:

    我之前没有亲自使用过一个学说数组值,但是 您可以为每个翻译选项定义一个“默认”form class,如下所示:

    AppBundle\Form\LanguageStringEditorType.php

    class LanguageStringEditorType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder
                ->add('en', TextareaType::class, ['label' => 'English'])
                ->add('de', TextareaType::class, ['label' => 'German'])
                ->add('ru', TextareaType::class, ['label' => 'Russian'])
            ;
        }
    }
    

    如果您保持命名('en'、'de' 和 'ru')与数据数组键名相同,例如具有这样的(教义)实体:

    AppBundle\Entity\LanguageString.php

    class LanguageString {
        private $identifier;
        private $translations; // this is the doctrine array type
                               // however I didn't feel like setting up a database for this
                               // test so I'm manually filling it see the next bit
    
    ... Getter and setter things ...
    

    并为此创建一个类型:

    AppBundle\Form\LanguageStringType.php

    class LanguageStringType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder
                ->add('identifier')
                ->add('translations', LanguageStringEditorType::class, ['label' => 'Translations'])
            ;
        }
    }
    

    我们可以在控制器中使用它

    $data = new LanguageString();
    // fill some dummy content (not using database)..
    $data->setIdentifier('hello_world');
    $data->setTranslations([
        'en' => 'Hello world!',
        'de' => 'Hallo Welt!',
        'ru' => 'Привет мир'
    ]);
    
    $form = $this->createForm(LanguageStringType::class, $data);
    
    return $this->render('default/index.html.twig', [
        'form' => $form->createView()
    ]);
    

    其余的都是通过魔法完成的,不需要转换器。数据被放置在表单域中。并在使用handleRequest时设置为实体。请记住,数据键值与表单构建器名称相同。

    作为奖励,您已经在 LanguageStringEditorType 类中定义了所有默认语言字段,无论是否填写。

    【讨论】:

    • 感谢您花时间回答!对此,我真的非常感激!我想我需要一些更灵活的东西。我找到了一个答案,我将在下面分享:
    【解决方案2】:

    所以,我了解到我需要将我的两个需求分成不同的解决方案。首先,我创建了一个新的表单类型来代替我默认使用的文本类型:

        $builder
            ])
            ->add('labels', CollectionType::class, [
                'entry_type' => TranslationType::class
            ])
    

    这个类很简单,只是常规TextType的一个扩展:

    class TranslationType extends AbstractType
    {
        /**
         * @var LocaleApiInterface
         */
        private $localeApi;
    
        /**
         * TranslationType constructor.
         * @param LocaleApiInterface $localeApi
         */
        public function __construct(LocaleApiInterface $localeApi)
        {
            $this->localeApi = $localeApi;
        }
    
        /**
         * {@inheritdoc}
         */
        public function buildView(FormView $view, FormInterface $form, array $options)
        {
            $view->vars['label'] = array_search($view->vars['name'], $this->localeApi->getSupportedLocaleNames());
        }
    
        public function getParent()
        {
            return TextType::class;
        }
    }
    

    这满足了标签问题。其次,为了确保我的数据中包含所有受支持的语言环境,我使用了 FormEventListener:

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $supportedLocales = $this->localeApi->getSupportedLocales();
            $data = $event->getData();
            $labels = $data['labels'];
            foreach ($supportedLocales as $locale) {
                if (!array_key_exists($locale, $labels)) {
                    $labels[$locale] = $labels['en'];
                }
            }
            $data['labels'] = $labels;
            $event->setData($data);
        });
    

    这会将所需的键添加到数据中(如果它们尚不存在)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2014-04-26
      相关资源
      最近更新 更多