Symfony2: set a default value from a database in the form of select radio buttons?

New to symfony2, I have a simple table with two fields.

Since the alert field is a boolean, I declared the form as follows:

 public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('message', 'text', array('label' => "Message")) ->add('alert', 'choice', array( 'choices' => array(1 => 'Yes', 0 => 'No'), 'expanded' => true, 'multiple' => false, 'label' => "Are you agree?", 'attr' => array('class' => 'well') )); } 

It works when I create a new record, but when I try to edit the record, the "alert" option stored in the database is not set in the form (radio button).

How to set the state of a database on a form?

+4
source share
2 answers

You have 2 options.

Try using the data attribute in formbuilder.

 $builder ->add('message', 'text', array('label' => "Message")) ->add('alert', 'choice', array( 'choices' => array(1 => 'Yes', 0 => 'No'), 'expanded' => true, 'multiple' => false, 'label' => "Are you agree?", 'data' => $entity->getAlert(), 'attr' => array('class' => 'well') )); 

Or: When creating a form in symfony, you usually pass a data object to that form. This car fills all the values.

 $this->createForm(new FormType(), $entity); 
+3
source

To complete Rico Hamme's answer, here's how you do it.

 public function myFunc() { .... $entity = $this->getDoctrine() ->getRepository('AcmeFooBundle:Entity') ->find($id); if ($entity) { $form = $this->createForm(new EntityType(), $entity); ... } } 

EDIT

To end my answer, here is what EntityType might look like :

 class EntityType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { //This is just soe $builder->add('alert', 'choice', array( 'choices' => array(1 => 'Yes', 0 => 'No'), 'expanded' => true, 'multiple' => false, 'label' => "Are you agree?", 'attr' => array('class' => 'well') )); } public function getName() { return 'entity'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Acme\FooBundle\Entity\Entity', )); } } 
+1
source

All Articles