Php 将下拉列表添加到symfony 3表单

Php 将下拉列表添加到symfony 3表单,php,forms,symfony,Php,Forms,Symfony,我想在symfony版本3的表单中为类别添加一个dropdow字段,我已经尝试过解决方案,但每个都有自己的问题 首先获取所有类别并将它们传递到我的视图,然后显示它们: 行动: 视图: 我尝试的第二个解决方案是从我的类型生成下拉列表,因此在NewsType中,我将buildForm函数更改为以下内容: This form should not contain extra fields. /** * @param FormBuilderInterface $builder * @param a

我想在symfony版本3的表单中为类别添加一个dropdow字段,我已经尝试过解决方案,但每个都有自己的问题

首先获取所有类别并将它们传递到我的视图,然后显示它们: 行动:

视图:

我尝试的第二个解决方案是从我的类型生成下拉列表,因此在NewsType中,我将buildForm函数更改为以下内容:

This form should not contain extra fields.
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('categoryId', EntityType::class, [
            'class' => 'AppBundle:Category',
            'choice_label' => 'title',
        ])
        ->add('title')
        ->add('content')
    ;
}
通过这种方式,表单也可以很好地创建,但在提交后,返回了一个数据库异常,并表示:

使用参数[{},“asdf”,“asdf”]执行“插入新闻(类别id,标题,内容)值(?,?)”时发生异常:

可捕获的致命错误:类AppBundle\Entity\Category的对象无法转换为字符串

这意味着我的类别id作为对象传递

我该怎么办

顺便说一句,我的英语有点弱,请不要在我的帖子上加和减,我已经被禁止多次了


提前感谢。

symfony所要做的就是找到Category对象的字符串表示形式,以便填充选项字段

您可以通过以下两种方式解决此问题:

  • 在Category对象中,您可以创建一个
    \uuu toString
    方法

    public function __toString() {
    
        return $this->name; // or whatever field you want displayed
    
    }
    
  • 您可以告诉symfony使用哪个字段作为字段的标签。从

    $builder->add('attenting',ChoiceType::class,array(
    “选项”=>数组(
    新状态(状态::是),
    新状态(状态::否),
    新状态(状态::可能),
    ),
    
    'choice_label'=>'displayName',//symfony试图做的就是找到类别对象的字符串表示形式,以便填充选项字段

    您可以通过以下两种方式解决此问题:

  • 在Category对象中,您可以创建一个
    \uuu toString
    方法

    public function __toString() {
    
        return $this->name; // or whatever field you want displayed
    
    }
    
  • 您可以告诉symfony使用哪个字段作为字段的标签。从

    $builder->add('attenting',ChoiceType::class,array(
    “选项”=>数组(
    新状态(状态::是),
    新状态(状态::否),
    新状态(状态::可能),
    ),
    'choice_label'=>'displayName'//
    
    public function __toString() {
    
        return $this->name; // or whatever field you want displayed
    
    }
    
    $builder->add('attending', ChoiceType::class, array(
        'choices' => array(
            new Status(Status::YES),
            new Status(Status::NO),
            new Status(Status::MAYBE),
        ),
        'choice_label' => 'displayName',  // <-- where this is getDisplayName() on the object.
    ));