EasyAdminBundle icon indicating copy to clipboard operation
EasyAdminBundle copied to clipboard

Allow add new entities in AssociationField

Open michaelKaefer opened this issue 3 years ago • 4 comments

  • Closes https://github.com/EasyCorp/EasyAdminBundle/issues/3523 (which was already closed but it seems that it should not have been closed)
  • Closes https://github.com/EasyCorp/EasyAdminBundle/issues/3646
  • Closes https://github.com/EasyCorp/EasyAdminBundle/issues/5267
  • Closes https://github.com/EasyCorp/EasyAdminBundle/issues/4065

An example for having an association from a product to categories, where the user can add new, not yet existing categories in the autocomplete select input which are persisted by the entity manager:


class ProductCrudController extends AbstractCrudController
{
    private EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public static function getEntityFqcn(): string
    {
        return Product::class;
    }

    public function configureFields(string $pageName): iterable
    {
        return [
            AssociationField::new('categories')
                // $datas is something like: ['T-Shirts', 'Sweaters'] - whatever the user types in
                ->autocomplete(function (array $datas, Product $product) {
                    foreach ($datas as $data) {
                        $category = (new Category())
                            ->setTitle($data)
                            ->setLocale($product->getLocale());
                        $this->entityManager->persist($category);
                        $product->addCategory($category);
                    }
                }),
        ];
    }
}

I created a reproducer: https://github.com/michaelKaefer/ea-reproducer/tree/feature/add-new-button-in-association-field

michaelKaefer avatar Jun 14 '22 20:06 michaelKaefer

@javiereguiluz This is finished from my side :) But as always there is no need to hurry!

michaelKaefer avatar Jun 17 '22 18:06 michaelKaefer

Thanks for this contribution. A bit clarification - this will only be able to handle associated entities like Category in your case which only needs 1 property "title". It will not be able to handle associated entities with multiple properties?

alyjee avatar Aug 09 '22 21:08 alyjee

@alyjee Yes, that's true. (But you could still define your custom format like "John Doe" and then parse the string into first name and last name on your own)

michaelKaefer avatar Aug 10 '22 06:08 michaelKaefer

@michaelKaefer thanks for the clarification.

alyjee avatar Aug 12 '22 19:08 alyjee

@michaelKaefer hi, any recommended workaround for this scenario while waiting to be merged or added support for multiple properties? thanks

nurradityam avatar Sep 09 '23 11:09 nurradityam

A nice solution. May i ask why is this closed?

bencagri avatar Sep 25 '23 10:09 bencagri