Sonata Admin Bundle的configureActionButtons注入BoothTypeRepository报错求解
问题解决方法
错误根因
你收到的报错本质是调用方法传参错误:Doctrine 的 EntityManagerInterface::getRepository() 方法要求传入的参数是对应实体类的全限定名,而非 Repository 类本身的类名,你传入了 BoothTypeRepository::class 自然会被判定为无效实体类。
方案1:快速修复现有代码
假设你对应的 BoothType 实体命名空间为 App\Entity\BoothType,直接修改获取 Repository 一行的代码即可:
public function configureActionButtons($action, $object = null): array { $list = parent::configureActionButtons($action, $object); // 仅修改 getRepository 内的参数为实体类名 $handles = $this->getConfigurationPool()->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository(\App\Entity\BoothType::class) ->findAll(); foreach($handles as $handle) { $list['new_' . $handle] = [ 'attr' => $handle, 'template' => 'CRUD/button_new_booth_type.html.twig' ]; } unset($list['new']); return $list; }
方案2:规范注入 BoothTypeRepository(更推荐)
不需要手动从容器中获取 Doctrine 服务,直接通过控制器构造方法注入 Repository 即可,代码更简洁易维护:
- 首先在控制器头部引入依赖,通过构造方法注入
use App\Repository\BoothTypeRepository; class YourCrudController extends AbstractCrudController { // Symfony 自动注入 BoothTypeRepository public function __construct( private BoothTypeRepository $boothTypeRepository ) {} // 其他原有方法保持不变 }
- 调整 configureActionButtons 方法的调用逻辑
public function configureActionButtons($action, $object = null): array { $list = parent::configureActionButtons($action, $object); // 直接调用注入的 Repository 方法即可 $handles = $this->boothTypeRepository->findAll(); foreach($handles as $handle) { $list['new_' . $handle] = [ 'attr' => $handle, 'template' => 'CRUD/button_new_booth_type.html.twig' ]; } unset($list['new']); return $list; }
校验项
如果修改后仍有异常,检查 BoothTypeRepository 是否正确关联了实体:
- Symfony 6+ 版本确认 BoothTypeRepository 类上标注了
#[Repository(entityClass: BoothType::class)]注解 - 旧版本确认 doctrine.yaml 中配置了 BoothType 实体和 BoothTypeRepository 的关联关系
内容的提问来源于stack exchange,提问作者FortuneSoldier
相关产品推荐
相关产品推荐

