无法在Symfony Dynamic表单中显示下拉列表

9rygscc1  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(135)

我显示子类别,但得到以下错误:
Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader::getIdValue():参数#1($object)必须是类型?object,字符串给定,在C:\xampp\htdocs\demo_app\vendor\symfony\form\ChoiceList\ArrayChoiceList.php第181行调用

$formModifier = function(FormInterface $form, Category $category = null){
       
        $subCategories = null === $category ? [] : $category->getSubCategories();
        $subCategoryChoices = [];
        foreach ($subCategories as $subCategory) {
            $subCategoryChoices[$subCategory->getId()] = $subCategory->getName();
        }
        $form->add('sub_category',EntityType::class,[
            'class' => SubCategory::class,
            'choices' => $subCategoryChoices,
        ]);
    };

根据文档,如果我执行以下操作:

$formModifier = function(FormInterface $form, Category $category = null){
       
        $subCategories = null === $category ? [] : $category->getSubCategories();
        $form->add('sub_category',EntityType::class,[
            'class' => SubCategory::class,
            'choices' => $subCategories ,
        ]);
    };

我得到以下错误:

Object of class App\Entity\SubCategory could not be converted to string
jckbn6z7

jckbn6z71#

所以我用下面的代码解决了这个问题。

public function __toString()
    {
        return $this->name;
    }

相关问题