T Max
T Max

Reputation: 31

Symfony CollectionList

I have:

    ->add('skills', CollectionType::class, array(
        'entry_type' => TagType::class,
        'allow_add'  => true,
        'allow_delete' => true,
    ))

In the form builder with TagType being

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('id', IntegerType::class);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Tag',
    ));
}

What I am trying to do is to post just the tag ID's in the form but render the form with fetched names for those tags. I have attempted to:

if($request->getMethod() == 'POST')
{
  $form_arr = $request->request->get('form');
  $skills = (array_key_exists('skills', $form_arr)) ? $form_arr['skills'] : array();
  foreach($skills as $key => $role) { $skills[$key] = $role['id']; }
  if(count($skills) > 0)
  {
    $em->clear();
    $roles = $em->getRepository('AppBundle:Tag')->findById($skills);
    $project->setSkills($roles);
  }
}

but as soon as we reach $form->handleRequest($request); the whole form is rendered absent names for tags.

Upvotes: 2

Views: 79

Answers (1)

Moein
Moein

Reputation: 184

Symfony already provides you a solution for these cases. It's called data transformers.

There is an example similar to what you're trying to do.

http://symfony.com/doc/2.8/cookbook/form/data_transformers.html#creating-a-reusable-issue-selector-field

I recommend you to read the whole article from the beginning.

Upvotes: 2

Related Questions