Symfony EasyAdmin如何为其他实体创建CRUD删除操作链接
在Symfony EasyAdmin中创建跨实体删除操作的CRUD链接
你当前的问题是用linkToUrl生成的删除链接没触发EasyAdmin的删除确认弹窗,直接跳主页——这是因为EasyAdmin的删除操作要求POST请求,且需要CSRF令牌验证,普通GET链接满足不了这两个条件。
下面给两种可行的解决方法:
方法1:用表单提交模拟删除请求(贴合EasyAdmin原生逻辑)
通过隐藏表单提交POST请求,同时带上CSRF令牌,还能自定义确认弹窗:
- 先在CRUD控制器里定义Action,指定自定义模板:
$deleteOrder = Action::new(TrainingParticipantCrud::DELETE_ORDER, "删除自定义") ->setTemplatePath('admin/actions/delete_order.html.twig');
- 创建对应的Twig模板(
templates/admin/actions/delete_order.html.twig):
{% set order = entity.getTrainingOrder %} {% set deleteUrl = ea_url() ->unsetAll() ->setController('App\\Controller\\Admin\\TrainingOrderCrudController') ->setAction('delete') ->setEntityId(order.getId()) %} <form method="post" action="{{ deleteUrl }}" onsubmit="return confirm('确定要删除该订单吗?');"> <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ order.getId()) }}"> <button type="submit" class="btn btn-danger">删除自定义</button> </form>
方法2:自定义后台Action处理删除(更灵活)
直接在当前CRUD控制器里写删除逻辑,绕开跨控制器的URL跳转问题:
- 在
TrainingParticipantCrudController中添加自定义Action方法:
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext; use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; public function deleteOrderAction(AdminContext $context, AdminUrlGenerator $adminUrlGenerator, EntityManagerInterface $em) { /** @var TrainingParticipant $participant */ $participant = $context->getEntity()->getInstance(); $order = $participant->getTrainingOrder(); // 执行删除 $em->remove($order); $em->flush(); // 重定向回当前列表页 return new RedirectResponse($adminUrlGenerator ->unsetAll() ->setController(self::class) ->setAction('index') ->generateUrl() ); }
- 把Action链接到这个自定义方法:
$deleteOrder = Action::new(TrainingParticipantCrud::DELETE_ORDER, "删除自定义") ->linkToCrudAction('deleteOrderAction') ->setCssClass('btn btn-danger');
原代码失效的原因
- EasyAdmin原生的
DELETE操作只接受POST请求,GET请求会被安全拦截并跳转到主页 - 直接生成的URL没有携带CSRF令牌,过不了Symfony的安全验证
内容的提问来源于stack exchange,提问作者Dariusz Rup
相关产品推荐
相关产品推荐

