Symfony:如何向孩子添加字段表单?

时间:2015-12-28 15:01:08

标签: symfony symfony-forms

我有一个字段类型实体,呈现为复选框我想为每个复选框添加一个textarea类型的字段,我该怎么做?

代码:

// OfferType.php
$builder
    ->add('payment_method', new OfferPaymentType(), [
        'required' => false,
        'mapped' => false,
        'expanded' => true,
        'multiple' => true,
    ])
;

// OfferPaymentType.php
class OfferPaymentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('payment', null, [
                'multiple'    => true,
                'expanded'    => true,
                'compound'    => true,
            ])      
        ;

        $factory = $builder->getFormFactory();

        $formModifier = function (FormInterface $form, $payments = null) use ($factory) {
            foreach ($form as $child) {
                //dump($child);die;
                $child->add(
                    $factory->createNamed('metadata', 'textarea', null, [
                        'auto_initialize' => false,
                        'compound'    => true,
                    ]),
                    null,
                    ['compound' => true]
                );

            }
        };

        $builder->get('payment')->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                $data = $event->getData();
                $formModifier($event->getForm(), $data);
            }
        );
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'multiple'           => true,
            'expanded'           => true,
            'class'              => 'AppBundle:OfferPayment',
            'data_class'         => 'AppBundle\Entity\OfferPayment',
            'translation_domain' => 'app',
            'compound'           => true,
        ));
    }

    public function getName()
    {
        return 'offer_payment';
    }
}

1 个答案:

答案 0 :(得分:1)

您需要创建一个自定义表单类型,其中包含两个嵌入字段,一个复选框和一个textarea

   class OfferPaymentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('payement', 'checkbox')
                ->add('metadata', 'textarea');
    }
}

在您的表单中输入您将执行类似

的操作
    class CustomType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('payment_method', 'collection', array(
                'type'         => new OfferPaymentType(),
                'allow_add'    => true,
                'allow_delete' => true
            )
        );

    }
}