Stevan Tosic
Stevan Tosic

Reputation: 7199

Use Symfony form options in Collection class

// Controller Part

 $form = $this->createForm($formType, $user, [ 'id' => $user->getId() ]);

// Form Type part

 public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $id = $options['id'];

        $builder->add('profile_person_affiliations', CollectionType::class, array(
            'label' => 'Affiliation',
            'entry_type' => \SciProfileBundle\Form\ProfilePersonAffiliationType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'prototype' => true,
            'prototype_name' => '__name__',
            'by_reference' => false,
        ));

    }

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'id' => null
    ));
}

// Collection form type part

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $id = $options['id'];

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'SciProfileBundle\Entity\ProfilePersonAffiliations',
            'id' => null
        ));
    }

I need to use options in collection. For now I can use id in Parrent Form Type but not in Collection Form type. What is best practice to get options data form in child - Collection form type?

Upvotes: 0

Views: 308

Answers (1)

jkucharovic
jkucharovic

Reputation: 4244

You can use entry_options:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $id = $options['id'];

    $builder->add('profile_person_affiliations', CollectionType::class, array(
        'label' => 'Affiliation',
        'entry_type' => \SciProfileBundle\Form\ProfilePersonAffiliationType::class,
        'entry_options' => array('my_custom_option' => $id),
        'allow_add' => true,
        'allow_delete' => true,
        'prototype' => true,
        'prototype_name' => '__name__',
        'by_reference' => false,
    ));

}

Upvotes: 2

Related Questions