Home > Software engineering >  Symfony CollectionType -> EntryType -> Form with params
Symfony CollectionType -> EntryType -> Form with params

Time:11-25

I have two forms, the first allows me to add a project ProjectType, the second is a form allowing to add contributors to the project ProjectContactType.

In the first form I get entity Company with resolver

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('name', TextType::class)
        ->add('projectContacts', CollectionType::class, [
            'label' => false,
            'entry_type' => ProjectContactType::class,
            'by_reference' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ]);
}

public function configureOptions(OptionsResolver $resolver): void
{
    $resolver
        ->setDefaults([
            'data_class' => Project::class,
        ])
        ->setRequired([
            'company',
        ]);
}

I would like to be able to receive in my second form this same entity.

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('user', EntityType::class, [
            'placeholder' => 'Choisir un client',
            'required' => true,
            'class' => User::class,
            'choice_label' => function (User $user) {
                return $user->getFirstName() . " " . $user->getLastName();
            }
        ]);
}

public function configureOptions(OptionsResolver $resolver): void
{
    $resolver
        ->setDefaults([
            'data_class' => ProjectContact::class,
        ]);
}

My goal is to be able to filter users by the company entity.

Thank you.

CodePudding user response:

You should be able to pass ProjectType's company onto ProjectContactType like this:

Make the company required in ProjectContactType:

public function configureOptions(OptionsResolver $resolver): void
{
    $resolver
        ->setDefaults([
            'data_class' => ProjectContact::class,
        ])
        ->setRequired([
            'company',
        ]);
}

Then (in ProjectType) pass the company from ProjectType's options to ProjectContactType:

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder
        ->add('name', TextType::class)
        ->add('projectContacts', CollectionType::class, [
            'label' => false,
            'entry_type' => ProjectContactType::class,
            'by_reference' => false,
            'allow_add' => true,
            'allow_delete' => true,
            'entry_options' => [
                'company' => $options['company'], 
            ],
        ]);
}
  • Related