Symfony2中表单字段的动态变化属性

时间:2014-09-10 06:58:59

标签: php symfony

我有这段代码:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', ['required' => true])
        ->add('item', ['required' => true])
        ->add('isItem', ['empty_value' => true])
        ->sdd('submit')
    ;
}

其中:名称是字符串, isItem 是布尔字段。我想根据 isItem 值动态更改 item 字段的属性。

1 个答案:

答案 0 :(得分:0)

这可以通过Form Eventsdocumentation)来实现。

例如,您可以像这样收听FormEvents::PRE_SUBMIT事件:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', ['required' => true])
        ->add('item', ['required' => true])
        ->add('isItem', ['empty_value' => true])
        ->sdd('submit')
    ;

    $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
}

public function onPreSubmit(FormEvent $event)
{
    $data   = $event->getData();
    $form   = $event->getForm();
    $entity = $form->getData();

    if ($data['isItem']) {
        // do something
    } else
        // do something else
    }
}