获取子formType事件中的父对象

时间:2016-01-20 11:23:15

标签: symfony symfony-forms

我创建了两种表单类型,如下所示

EmailOptInType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
            $_1 = $event->getData();
            $_2 = $event->getForm()->getData();
            $_3 = $event->getForm()->getParent()->getData();
            $form = $event->getForm();         
        });
}

/**
 * @return string
 */
public function getParent()
{
    return 'checkbox';
}

和SubscribeType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('email', 'text', array(
            'label'    => 'Sign up to news',
            'required' => true,
            'attr'     => array(
                'placeholder' => 'Enter your email to subscribe',
            ),
        ))
        ->add('email_opt_in', 'newsletter_opt_in', array(
            'data'  => true
        ));
}

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    parent::configureOptions($resolver);

    $resolver->setDefaults(array(
        'data_class' => 'Bundle\Entity\Customer',
    ));
}

如您所见,subscribeType表单包含opt in表单。是否可以在子表单EmailOptInType?

的事件侦听器中获取父表单数据

在上面的片段中,$ _1返回一个布尔值true,表示选中的复选框,$ _2返回相同的值,$ _3返回一个空的客户对象。

是否可以获取刚刚创建/提交的客户对象?

1 个答案:

答案 0 :(得分:2)

在构建表单时(例如在控制器中),您可以将客户对象传递给表单选项:

$customer = $myRepository->find($customerID);
$form = $this->createForm(SubscribeType::class, $customer, ['customer' => $customer]);

新的SubscribeType.php:

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
    ->add('email', 'text', array(
        'label'    => 'Sign up to news',
        'required' => true,
        'attr'     => array(
            'placeholder' => 'Enter your email to subscribe',
        ),
        'customer' => $options['customer']
    ))
    ->add('email_opt_in', 'newsletter_opt_in', array(
        'data'  => true
    ));
}

public function configureOptions(OptionsResolver $resolver)
{
    parent::configureOptions($resolver);

    $resolver->setDefaults(array(
        'data_class' => 'Bundle\Entity\Customer',
        'customer'   => null
    ));
}

新的EmailOptInType.php:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $customer = $options['customer'];
    $builder
        ->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($customer) {
            //do thing with $customer
            $_1 = $event->getData();
            $_2 = $event->getForm()->getData();
            $_3 = $event->getForm()->getParent()->getData();
            $form = $event->getForm();         
        });
}

public function configureOptions(OptionsResolver $resolver)
{
    parent::configureOptions($resolver);

    $resolver->setDefaults(array(
        //[...]
        'customer'   => null
    ));
}