symfony 如何使用EasyAdmin在ChoiceField中列出实体?

bksxznpy  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(200)

我正在尝试使用EasyAdmin Bundle在表单中设置选项。下面是控制器内部的代码。
我得到这个错误消息:Expected argument of type "App\Entity\Author or null", "int" given at property path "author".
实际上ChoiceField返回Author对象的id。**如何在表单提交后以时尚的方式将id转换为对象?**我目前正在为每个字段使用DataTransformers来解决这个问题。但这是一个非常繁重的解决方案。这意味着为每个字段创建1个DataTransform类。
文档没有给予任何关于如何处理选择的提示:https://symfony.com/doc/3.x/EasyAdminBundle/fields.html
谢谢

  • 我在Linux Mint上使用EasyAdmin 3 + Symfony 5。*

在App\Admin\PostCrudController中:

public function configureFields(string $pageName): iterable
    {
        return [
            // ...
            ChoiceField::new('author')->setChoices(fn() => $this->getAuthorChoices()),
        ];
    }

    private function getAuthorChoices(): array
    {
        $choices = [];
        foreach($this->authorRepository->findAll() as $i => $author) {
            $choices[$author->getFullName()] = $author->getId();
        }
        return $choices;
    }
mw3dktmi

mw3dktmi1#

实际上,解决方案非常简单:使用AssociationField类型代替ChoiceField。ChoiceField类型仅用于手动传递数组。要列出实体,AssociationField是明确的,并且自动完成所有操作。这在文档中没有精确说明,因为字段引用尚未编写。

vhmi4jdf

vhmi4jdf2#

就像你在EasyAdmin 4.0中所做的那样,例如,当你没有关联字段时,你甚至不应该在数据库中保存该字段,而只是使用该字段来过滤另一个关联字段(即关联字段)。
范例:
你有三张table

State(id,description,code)

county(id, description, state_id)

Person(id,name,county_id)

如果我们注意到在Person表中我们没有State表的id,因为在County表中我们已经有了state_id,通过county_id字段,我们可以访问它并恢复state_id,现在我创建了一个字段来通过State组合过滤County
它们是两个依赖的组合,我必须首先选择State,以便在另一个组合中,它只显示所选State的县,我在EasyAdmin 4的CRUD中发言。

相关问题