Allow add new entities in AssociationField
- 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
@javiereguiluz This is finished from my side :) But as always there is no need to hurry!
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 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 thanks for the clarification.
@michaelKaefer hi, any recommended workaround for this scenario while waiting to be merged or added support for multiple properties? thanks
A nice solution. May i ask why is this closed?