SymfonyとDoctrineの記事になります。
私の環境の各バージョンは次の通りです。
Symfony 3.4
Doctrine 2.12
This is the method when you want to make the default state selected when you create a Checkbox from Entity.
This is effective when you want to set a default value in addition to EntityType.
How to create a Checkbox from EntityType
Reference : EntityType Field
This time it is Checkbox, but of course you can also create Radio and Select.
In the case of Checkbox, it will be as follows.
(Detailed method of creating FORM itself is omitted. It is how to create Field information.)
(Please describe the acquisition part of Entity of class according to the development environment.)
use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... $builder->add('shop', EntityType::class, [ 'class' => 'AppBundle:Shop', 'choice_label' => 'name', 'expanded' => true, 'multiple' => true, ]);
By the way, it is possible to make Select and radio by changing expanded
and multiple
.
Element Type | Expanded | Multiple |
---|---|---|
select tag | false | false |
select tag (with multiple attribute) | false | true |
radio buttons | true | false |
checkboxes | true | true |
How to make Checkbox default value checked from Entity Type
Make the initial value (default) when the page is opened checked.
use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... $builder->add('shop', EntityType::class, [ 'class' => 'AppBundle:Shop', 'choice_label' => 'name', 'expanded' => true, 'multiple' => true, 'data' => $this->shopRepository->findAll(), ]);
You can set the initial value (default) by using data
.
This time I’m getting the whole thing from the shopRepository to select all the “shop” checkboxes.
(Please describe the acquisition part of the repository according to the development environment.)
By the way, if you want to check only the shops with IDs 1 and 5, write as follows.
$this->shopRepository->findBy(['id' => [1,5]]),
Summary
I briefly explained how to create a checkbox using EntityType.
See below for more detailed usage.
Reference : EntityType Field