symfony2 - 单选按钮默认数据覆盖实际值

时间:2014-06-05 16:26:57

标签: php forms symfony

我有一个简单的形式:

public function buildForm(FormBuilderInterface $builder, array $option){
  $builder
    ->setMethod('POST')
    ->add('isdigital', 'choice', array(
      'choices' => array('0' => 'no', '1' => 'yes'),
  'expanded' => true,
      'multiple' => false,
      'data'=> 0
));
}

我填充此表单传入数组键值,而不使用doctrine实体。

$this->createForm(new PricingType(), $defaultData);

属性'数据'应该只设置第一次的值,而不是覆盖与数组一起传递的值。

如果我删除了'数据'属性,单选按钮实际显示数组中传递的值。

有没有办法我只能第一次设置默认值?

2 个答案:

答案 0 :(得分:0)

在与PricingType相关的数据类的实体中添加__construct():

__construct(){
    $this->isdigital = 0;
}

现在在您的控制器中创建$ defaultData项目,该项目构成实体定价

$defaultData = new Pricing();

这将具有您想要的默认值,您不需要'data'=>表单类中的0行。

答案 1 :(得分:0)

我找到的唯一解决方案是,如果未设置值,则需要添加表单事件侦听器POST_SET_DATA以动态设置默认值。 例如:

use Symfony\Component\Form\FormEvents; //Add this line to add FormEvents to the current scope
use Symfony\Component\Form\FormEvent; //Add this line to add FormEvent to the current scope

public function buildForm(FormBuilderInterface $builder, array $option){
   //Add POST_SET_DATA Form event
   $builder->addEventListener(FormEvents::POST_SET_DATA,function(FormEvent $event){
       $form = $event->getForm(); //Get current form object
       $data = $event->getData(); //Get current data 
       //set the default value for isdigital if not set from the database or post
       if ($data->getIsdigital() == NULL){ //or $data->getIsDigital() depending on how its setup in your entity class
           $form->get('isdigital')->setData(**YOUR DEFAULT VALUE**); //set your default value if not set from the database or post 
       }
  });
  $builder
    ->setMethod('POST')
    ->add('isdigital', 'choice', array(
      'choices' => array('0' => 'no', '1' => 'yes'),
      'expanded' => true,
      'multiple' => false,
      //'data'=> 0    //Remove this line
 ));
}

请注意:以上代码未经过测试,但经过重新编写以适应问题场景。

相关问题