Symfony3 Form EntityType

时间:2016-09-03 18:44:41

标签: forms symfony

我正在使用Symfony3,在为EntityType :: class

创建表单时遇到以下错误

我的实体名称空间 项目\ CoreBundle \实体\ CountryEntity

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, ['label' => 'Name *', 'attr' => ['data-help'  => 'enter language name here.']])
        ->add('iso', TextType::class, ['label' => 'ISO *', 'attr' => ['data-help'  => 'enter language code here.']])
        ->add('defaultLanguage', EntityType::class,
            array(
                'class' => 'Project\CoreBundle\Entity\CountryEntity'
            )
        )
        ->getForm();
    ;
}

引发可捕获的致命错误:类Project \ CoreBundle \ Entity \ CountryEntity的对象无法转换为字符串

任何帮助都会有用,谢谢

1 个答案:

答案 0 :(得分:3)

因为EntityType是ChoiceType的扩展,它需要知道如何将实体呈现给表单。如果您未传递任何信息,则会尝试使用__toString()方法。如果未定义,则会出现此错误。

您可以为字段指定__toString()选项,而不是实现choice_label,该选项应该是属性的路径规范,应该显示。例如,您的CountryEntity类可能具有name属性:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, ['label' => 'Name *', 'attr' => ['data-help'  => 'enter language name here.']])
        ->add('iso', TextType::class, ['label' => 'ISO *', 'attr' => ['data-help'  => 'enter language code here.']])
        ->add('defaultLanguage', EntityType::class,
            array(
                'class' => 'Project\CoreBundle\Entity\CountryEntity',
                'choice_label' => 'name'
            )
        )
        ->getForm();
    ;
}

另请参阅http://symfony.com/doc/current/reference/forms/types/entity.html上的EntityType文档。

祝你好运