I have a simpleform:
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
));
}
I populate this form passing in an array key value, without using doctrine entities.
$this->createForm(new PricingType(), $defaultData);
The attribute 'data' should set the value only for the first time, instead overrides the value passed with the array.
If I remove the 'data' attribute, the radio button actually displays the value passed in the array.
Is there any way I can set the default value only for the first time?
In the entity for the data class that related to PricingType add a __construct():
__construct(){
$this->isdigital = 0;
}
Now in your controller when you create the $defaultData item which is form the entity Pricing
$defaultData = new Pricing();
This will have the default value you want and you do not need to have the 'data' => 0 line in your form class.
The only solution I found is You will need to add a form Event Listener POST_SET_DATA to dynamically set the default value if the values aren't set. For eg:
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
));
}
Please Note: The above code is not tested, but was rewritten to fit the questions scenario.