-1

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!

hzlh
  • 29
  • 6
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Apr 13 '22 at 20:04

1 Answers1

0

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;
    }

    // ...
}
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31