EasyAdminBundle icon indicating copy to clipboard operation
EasyAdminBundle copied to clipboard

Unable to use empty_data for entities with required (non-null) arguments

Open zmitic opened this issue 7 months ago • 0 comments

Describe the bug When an entity has required arguments in the constructor, we must use empty_data callable. Later in the controller, fetching that newly created entity is done like this:

// controller
$form = $this->createForm(MyFormType::class); // notice that second argument is null (default); that triggers empty_data
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid() && $newEntity = $form->getData()) {
    // here $newEntity is what empty_data created

    $repository->persist($newEntity);
}

To Reproduce Most simple entities:

class Category{}

class Product
{
    public function __construct(
        public Category $category, // notice: it is not nullable, $category must be injected
    )
    {}
}

and Product CRUD controller like:

public function configureCrud(Crud $crud): Crud
{
    return $crud
        // other options
        ->setFormOptions([
            'empty_data' => $this->emptyData(...),
        ]);
}

private function emptyData(FormInterface $form): Product
{
    $category = $form->get('category')->getData(); // assertion for static analysis not shown

    return new Product($category);
}

Additional context From loose check of the code, AbstractCrudController#308-309 would need minimal changes.

Instead of:

$entityInstance = $newForm->getData();
$context->getEntity()->setInstance($entityInstance);

if ($newForm->isSubmitted() && $newForm->isValid()) {

a tiny change to:

if ($newForm->isSubmitted() && $newForm->isValid() && $entityInstance = $newForm->getData()) {
    $context->getEntity()->setInstance($entityInstance);

should do the job.

zmitic avatar May 28 '25 13:05 zmitic