如何在Symfony2中为CollectionType字段使用CallbackTransformer?

时间:2016-06-15 07:32:57

标签: symfony symfony-forms

美好的一天。 我无法理解如何为CollectionType使用CallbackTransformer。 我用收集字段(SecondForm)编写FirstForm。 如何使用Callbacktransformer填写SecondForm?

FirstForm

<?php

namespace True\AdminBundle\Form\Type;

/* uses */

class FirstFormType extends AbstractType
{
    public function buildForm (FormBuilderInterface $builder, array $options)
    {
        $builder->add('qwe', CollectionType::class, [
            'label' => 'Any label',
            'required' => false,
            'prototype' => true,
            'allow_add' => true,
            'allow_delete' => true,
            'mapped' => false,
            'entry_type' => SecondCollectionFormType::class,
            'entry_options'  => array(
                /* send some options to second form */
            ),
        ]);
        $builder->get('qwe')
            ->addModelTransformer(new CallbackTransformer(
                function ($tagsAsArray) {
                    // Problem HERE
                    $result['qwe'][] = ['logo' => '222', 'description' => '123'];
                    return $result;
                },
                function ($tagsAsString) {
                    $result['qwe'][] = ['logo' => '222', 'description' => '123'];
                    return $result;
                }
            ))
        ;
        $builder
            ->add('submit', SubmitType::class, [
                'label' => 'Save',
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'fields' => null,
            'descriptions' => null,
            'em' => null,
            'template' =>  null,
            'sectionName' => null,
            'doctrine' => null,
            'websiteId' => null,
        ));
    }

    public function getBlockPrefix()
    {
        return 'backend_form';
    }
}

和第二个表格

<?php
namespace True\AdminBundle\Form\Type;
/* uses */

class SecondCollectionFormType extends AbstractType
{
    public function buildForm (FormBuilderInterface $builder, array $options)
    {
        $builder->add('logo', TextType::class, [
            'label' => $label,
            'required' => false,
            'mapped' => false,
            ]);
        $builder->add('description', TextareaType::class, [
            'label' => $label,
            'required' => false,
            'mapped' => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'fields' => null,
            'descriptions' => null,
        ));
    }

    public function getBlockPrefix()
    {
        return 'backend_collection_form';
    }

}

0 个答案:

没有答案
相关问题