For update
public function updateEntity($entity)
{
$user = $this->getUser();
if (method_exists($entity, 'setUserId')) {
$entity->setUserId($user);
}
parent::updateEntity($entity);
}
For parsing data
public function persistEntity($entity)
{
$user = $this->getUser();
$userRoles = $user->getRoles();
if (method_exists($entity, 'setUserId') && $userRoles[0] != 'ROLE_ADMIN') {
$entity->setUserId($user);
}
$userId = $entity->getUserId()->getId();
$this->isExists($userId);
parent::updateEntity($entity);
}
Configure the custom class packages/easy_admin.yaml
easy_admin:
site_name: "Dashboard"
entities:
School:
controller: App\Controller\SchoolController
class: App\Entity\School
For removing data
protected function removeEntity($entity){
$userRoles = $this->getUser()->getRoles();
if($userRoles[0] != 'ROLE_ADMIN'){
$message = "You can not delete School <button onclick='history.go(-1);'>Back </button>";
die("$message");
}
parent::removeEntity($entity);
}
Finally class shows like
<?php
namespace App\Controller;
use App\Repository\SchoolRepository;
use App\Entity\School ;
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\EasyAdminFormType;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
class SchoolController extends EasyAdminController
{
//protected function newAction(){
//}
public function persistEntity($entity)
{
$user = $this->getUser();
$userRoles = $user->getRoles();
if (method_exists($entity, 'setUserId') && $userRoles[0] != 'ROLE_ADMIN') {
$entity->setUserId($user);
}
$userId = $entity->getUserId()->getId();
$this->isExists($userId);
parent::updateEntity($entity);
}
public function updateEntity($entity)
{
$user = $this->getUser();
if (method_exists($entity, 'setUserId')) {
$entity->setUserId($user);
}
parent::updateEntity($entity);
}
protected function removeEntity($entity){
$userRoles = $this->getUser()->getRoles();
if($userRoles[0] != 'ROLE_ADMIN'){
$message = "You can not delete School <button onclick='history.go(-1);'>Back </button>";
die("$message");
}
parent::removeEntity($entity);
}
private function isExists($userId){
$repository = $this->getDoctrine()->getRepository(School::class);
$schools = $repository->findOneBy(
['userId' => $userId]
);
if(!empty($schools)){
$message = "You can not create more than one School <button onclick='history.go(-1);'>Back </button>";
die("$message");
}
}
}