从Symfony2中的订户(表单事件)访问表单字段

时间:2012-03-12 02:25:53

标签: symfony symfony-forms

我正在关注教程How to Dynamically Generate Forms Using Form Events。我坚持创造AddNameFieldSubscriber

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

我的问题很简单:FormFactory如何访问和修改$builder之前创建的任意表单字段?为什么我们传递的是FormFactory而不是$builder本身?

假设我们在构建器中只有两个字段(“name”和“price”):

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'; }
}

我想在订阅者中设置required = false(仅作为示例):

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 个答案:

答案 0 :(得分:1)

我可能错了,但我不相信你可以在创建后更改表单的属性。但是,您可以添加到表单。

您可以将此推迟发送给订阅者,而不是在ProductType::buildForm中添加“名称”字段:

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