EasyAdmin - AssociationField creating new entries as tags

31 views Asked by At

I have seen multiple questions about AssociationField but still haven't found the answer to this specific case.

Problem: I have an entity (LOBExercise) with the following field: #[ORM\ManyToMany(targetEntity: LOBTag::class, inversedBy: 'LOBExercises')] private Collection $lob_tag;

In the LOBExerciseCrudController I have the following field:

 yield AssociationField::new('lob_tag')
        ->hideOnIndex()
        ->addCssClass('border-none')
        ->setFormTypeOptions([
            'by_reference' => true,
            'attr' => [
                'data-ea-widget' => "ea-autocomplete",
                'data-ea-autocomplete-allow-item-create' => 'true',
            ],
        ])
        ->setLabel('Tags');

I want to be able to create new Tags by adding them like this: image

However Symfony throws an error on this field because the new field is not in the database, which makes sense. The error is "Choice is not valid" which means the field is not in the pre approved options given to the field on page load.

I want to create the new entry in an event PRE_SUBMIT (and also thus pre validation)

I know in a Symfony form I can use this event to achieve this. However I can't get this to work in EasyAdmin

$builder->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
    $data = $event->getData();

    // Create new tags in the database

    $event->setData($data);
}

I have tried multiple different ways, like creating a custom form type, using a collection field, using EventSubcribers and Doctrine events.

My question mainly is how to use FormEvents(::PRE_SUBMIT) for an EasyAdmin field. This is a farely standard use case I think. I would appreciate some insight in how to achieve this behaviour in EasyAdmin.

0

There are 0 answers