FORSMILE
JA
Symfony2021/05/13

How to Make an EntityType Checkbox Checked by Default [Symfony]

This is how to set a checkbox created from an Entity to be checked by default.

Back to Blog

This is how to set a checkbox created from an Entity to be checked by default.

This method is effective not only for EntityType but also when you want to set default values for other types.

CREATING A CHECKBOX FROM AN ENTITYTYPE

This time it's a checkbox, but you can, of course, create radio buttons or select fields as well.

(Detailed instructions on how to create the FORM itself are omitted. This covers how to create field information.)

(Please write the part for retrieving the class Entity according to your development environment.)

javascript
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, by changing `expanded` and `multiple`, you can create select boxes or radio buttons.

select tag (with multiple attribute)

HOW TO MAKE AN ENTITYTYPE CHECKBOX CHECKED

We will set the initial value (default) to be checked when the page is opened.

javascript
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) using `data`.

In this case, to select all checkboxes for 'shop', we are retrieving all entries from `shopRepository`.

(Please write the part for retrieving the repository according to your development environment.)

By the way, if you only want to check shops with IDs 1 and 5, you would write it like this:

javascript
$this->shopRepository->findBy(['id' => [1,5]]),

SUMMARY

I've provided a brief explanation on how to create checkboxes using EntityType.

Recommended Symfony Books

There aren't many varieties, and the framework itself has a vast amount of information, so even introductory books can be quite substantial reads.

📦
Amazon で関連書籍・ツールを検索
Symfony PHP framework book
Amazonで探す →(アソシエイトリンク)