简体   繁体   中英

Symfony: choice_list with pre-selected values

I have an array field in my Entity called Type and I want to restrict the value that the user can specify for the field as this:

Type1      [] subtitle1        [] subtitle2         [] subtitle3

Type2      [] subtitle1        [] subtitle2         [] subtitle3

I managed to do this by creating choice form type and a little twig customization like this:

$form = $this->createFormBuilder($entity)
                ->add('name', 'text')
                ->add('type', 'choice', array(
                    'multiple' => true,
                    'choice_list' => new myBundle\Form\Extension\CustomChoiceList($param1,$param2),
                    'label' => 'my Label',
                    'expanded' => true
                ));// CustomChoiceList extends ChoiceList

my issue now is when i have an entity i want to edit, how can i show the user the same form but with some of the checkboxes checked?

I checked ChoiceList and it's creating the checkboxes by using ChoiceView class which has no checked option only label , value , data

Thanks

You can set the pre selected checkboxes with the "data" property

$form = $this->createFormBuilder($entity)
                ->add('name', 'text')
                ->add('type', 'choice', array(
                    'multiple' => true,
                    'choice_list' => new myBundle\Form\Extension\CustomChoiceList($param1,$param2),
                    'label' => 'my Label',
                    'expanded' => true,
                    'data' => 0 // Checks the first choise
                ));// CustomChoiceList extends ChoiceList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM