lundi 16 avril 2018

How to preselect generated checkboxes in symfony 4?

Let's imagine that we want to assign categories to a post, we use an EntityType to generate them based on the amount of categories we have, so we just add the next block of code to our form:

->add('categories', EntityType::class, array(
   'class' => Category::class,
   'choice_label' => 'category_description',
   'multiple' => true,
   'expanded' => true,
   'required' => false,
))

And then save them to the database when the form is submitted, [many to many, using CollectionArray]:

foreach($post_data['categories'] as $form_category)
{
  $database_category = $database_manager->getRepository(PostCategory::class)->find($form_category->getId());
  $post->addCategory($database_category);
}

but what if i want to have those checkboxes preselected when i go to edit mode so the user knows which ones were selected last time, how would you approach that?

Also how would you remove one if it is deselected?




Aucun commentaire:

Enregistrer un commentaire