如何动态更改symfony2表单字段的选项?

时间:2015-01-08 18:09:36

标签: symfony

在symfony 2.5.6中, 如何以symfony2形式动态更改选项,例如:

// src/AppBundle/Form/Type/TaskType.php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('task')
            ->add('dueDate', null, array('widget' => 'single_text'))
            ->add('save', 'submit');

       if (condition) {
          //how to change option of 'task' or 'dueDate' by example
          //something like this, but addOption doesn't exist and i don't find any usefull method
          $builder->get('dueDate')->addOption('read_only', true) 
       }

    }

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

需要使用活动吗?

  

http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

或者这个

foreach($builder->all() as $key => $field) {
    if ($key == 'dueDate')) {
         $options = $field->getOptions();
         $options = array_merge_recursive($options, array('read_only' => true));
         $builder->remove($key);
         $builder->add($key, $field->getName(), $options);
    }
}

#with 'Could not load type "dueDate"' error when i display my form in a browser!

怎么办?最佳做法?

谢谢!

1 个答案:

答案 0 :(得分:2)

我不知道你的最佳做法是什么意思,但为什么不这样做:

$builder
    ->add('dueDate', null, array('widget' => 'single_text'))
    ->add('save', 'submit');

$options = [
    KEY => VALUE,
    ....
];

if (condition) {
    $options = [
        ANOTHER_KEY => ANOTHER_VALUE,
        ....
    ];
}

$builder->add('task', TYPE, $options);

另一种方法是使用PRE_SUBMIT事件,类似这样......

$builder
    ->add('task')
    ->add('dueDate', null, array('widget' => 'single_text'))
    ->add('save', 'submit');

$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmit']);

....    

public function preSubmit(FormEvent $event)
{
    if (CONDITION) {
        $builder->remove('task');
        $builder->add('task', TYPE, $NEW_OPTIONS_ARRAY);
    }

}
相关问题