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

Php symfony2-单选按钮默认数据覆盖实际值,php,forms,symfony,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

我有一个简单的表单:

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
));
}
我通过传入数组键值填充此表单,而不使用条令实体

$this->createForm(new PricingType(), $defaultData);
属性“data”只应第一次设置该值,而应覆盖随数组传递的值

如果删除“data”属性,单选按钮实际上会显示在数组中传递的值


是否有任何方法可以仅在第一次设置默认值?

在与PricingType add a__construct()相关的数据类的实体中:

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

$defaultData = new Pricing();

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

我找到的唯一解决方案是,如果未设置值,您需要添加表单事件侦听器POST\u SET\u data来动态设置默认值。 例如:


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

很遗憾,我没有为此表单使用实体,只需传递数组键值,但您正在使用某些内容填充$defaultData数组。在将数据加载到此数组时,可以将逻辑添加到集合中。如果数据字段为空,则设置为0。
$defaultData = new Pricing();
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
 ));
}