Home > Software design >  EasyAdmin automatically set up a user_id when adding a new entry to an entity
EasyAdmin automatically set up a user_id when adding a new entry to an entity

Time:04-15

I'm using easyadmin with my online learning website project for school. Teachers can add formations, sections which are attached to formations, and lessons which belong to sections. I set up three cruds for each, and queries so the logged in user can only see content they created.

The issue is that when adding a new entry, easyadmin doesn't set up the logged in user_id in the database, and I get the following error: An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null

I get where it's coming from, you can't add an entry to the database without the user_id since it's not nullable, but I can't seem to find where I can set up easyadmin so it always passes the user_id when adding a new entry. Can you edit the add action somewhere?

Thanks!

CodePudding user response:

As shown in the docs example code below, you need to manually set the user on your entity (currently logged-in user is returned by $this->getUser()) in your AbstractCrudController::createEntity method.

//    src: https://symfony.com/bundles/EasyAdminBundle/current/crud.html#creating-persisting-and-deleting-entities
// copied: 2022-04-13

namespace App\Controller\Admin;

use App\Entity\Product;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;

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

    public function createEntity(string $entityFqcn)
    {
        $product = new Product();
        $product->createdBy($this->getUser());

        return $product;
    }

    // ...
}
  • Related