Accessing a form field from a subscriber (of a form event) in Symfony2

你。 提交于 2019-12-08 00:17:03

问题


I'm following the tutorial How to Dynamically Generate Forms Using Form Events. I'm stuck on the creation of AddNameFieldSubscriber:

$subscriber = new AddNameFieldSubscriber($builder->getFormFactory());

My question is simple: how FormFactory can access and modify an arbitrary form field previously created by the $builder? And why we are passing the FormFactory instead of the $builder itself?

Assuming we have just two fields ("name" and "price") in the builder:

class ProductType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $subscriber = new AddProductTypeSubscriber($builder->getFormFactory());
        $builder->addEventSubscriber($subscriber);

        $builder->add('name');
        $builder->add('price');
    }

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

I'd like to set required = false (just an example) in the subscriber:

class ProductTypeSubscriber implements EventSubscriberInterface
{
    private $factory;

    public function __construct(FormFactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(DataEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        if (null === $data) return;

        // Access "name" field and set require = false
    }
}

回答1:


I could be wrong about it this, but I don't believe you can change a form's attributes after its been created. However, you can add to the form.

Instead of adding the 'name' field in ProductType::buildForm, you can defer this to the subscriber:

if (!$data->getId()) {
    $form->add($this->factory->createNamed('text', 'name', null, array('required' => false)));
} else {
    $form->add($this->factory->createNamed('text', 'name'));
}


来源:https://stackoverflow.com/questions/9661026/accessing-a-form-field-from-a-subscriber-of-a-form-event-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!