我在Symfony应用程序中使用easy-admin 。我的实体是通过Doctrine管理的。
我有一个实体fieldTemplate
链接到实体Field
并Position
通过多对一关系。
// App\Entity\FieldTemplate.php
/**
* @ORM\Entity(repositoryClass="App\Repository\FieldTemplateRepository")
*/
class FieldTemplate
{
/**
* @ORM\OneToMany(targetEntity="App\Entity\Position", mappedBy="fieldTemplate", cascade={"persist"}, orphanRemoval=true)
*/
private $positions;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Field", mappedBy="template", cascade={"persist"}, orphanRemoval=true)
*/
private $fields;
}
// App\Entity\Field.php
/**
* @ORM\Entity(repositoryClass="App\Repository\FieldRepository")
*/
class Field
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\FieldTemplate", inversedBy="fields", cascade={"persist"})
*/
private $template;
}
// App\Entity\Position.php
/**
* @ORM\Entity(repositoryClass="App\Repository\PositionRepository")
*/
class Position
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\FieldTemplate", inversedBy="positions")
* @ORM\JoinColumn(nullable=false)
*/
private $fieldTemplate;
}
使用侦听器,如果已经链接到模板,我想阻止删除或编辑模板fields
,并强制用户创建一个新模板。
// app\Listener\FieldTemplateListener.php
class FieldTemplateListener
{
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if($entity instanceof FieldTemplate)
{
if (count($entity->getFields()))
throw new AccessDeniedException("this template has already field it cannot be changed");
}
}
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getObject();
if($entity instanceof FieldTemplate)
{
if(count($entity->getFields()))
throw new AccessDeniedException('this template has already fields it cannot be removed');
}
}
}
它注册在我的services
#App\config\services.yaml
services:
App\EventListener\FieldTemplateListener:
tags:
- { name: doctrine.event_listener, event: preRemove, priority: 500 }
- { name: doctrine.event_listener, event: preUpdate, priority: 500 }
当我尝试删除模板时,会引发错误,但两者都会positions
被fields
删除,当我尝试编辑时,不会引发错误......
有人看到我做错了吗?