Symfony 2 Catchable Fatal Error: Object of class UserCategory could not be converted to string

Symfony 2 Catchable Fatal Error: Object of class UserCategory could not be converted to string

我尝试建立一个分类系统。我喜欢我的用户可以用类别标记。所以我放了一个 Array Collection 和一个“ManyToMany”,但它不起作用,无论我做什么,我都会收到此错误“Catchable Fatal Error : Object of class Shoontgo \ CoreBundle \ Entity \ UserCategory couldn't be converted to string ".

如果有人能帮助我,我想我继续寻找解决方案就不会有头发了...

           $userCategories = new ArrayCollection();

        foreach ($form->getCategories()->getLibCategory() as $category) {
            $userCategories->add($category);
        }

        $user->addCategory($userCategories);

我的表单类型:

            ->add('category', CollectionType::class, array(
            'entry_type' => UserCategoryType::class,
            'allow_add'    => true,
        ))

我的看法:

<div class="form-group">
   <label class="col-sm-4 control-label">Catégories<span class="text-danger">*</span></label>
    <div class="col-sm-6">
      {{ form_errors(form.category) }}
      <ul id="category-list" data-prototype="{{ form_widget(form.category.vars.prototype)|e }}">
        {% for cat in form.category %}
           {{ form_errors(cat) }}
           <div class="form-group">
              {{ form_widget(cat,{'attr' : {'class' : 'form-control', 'placeholder' : "", 'data-parsley-required' : 'data-parsley-required'}}) }}
           </div>
        {% endfor %}
      </ul>
      <a href="#" id="add-another-category">Add another category</a>
    </div>

提前致谢! 克里斯托夫

当实体没有 __toString() 方法时,总是会出现该错误。 Symfony 组件 Form 经常使用此方法为 <select>.

生成值

当我使用 EntityTypeField 并且忘记在选项中定义属性 choice_label 时,我总是遇到这个错误。也许在您的 CategoryUserType 中您使用了该表单类型而忘记定义选择标签。

您需要向

添加一个方法
Shootngo\CoreBundle\Entity\UserCategory

实体class...

public function __toString()
{
  return 'My string version of UserCategory'; // if you have a name property you can do $this->getName();
}

在生成 select 选项时 php 会自动使用 __toString() 方法将实体对象转换为文本...

嗯,我找到了你的两个答案的解决方案,谢谢:)

表单类型: ->添加('category', 'entity', 数组( 'class' => "CoreBundle:Category", 'property' => "libCategory", 'multiple' => 正确, 'expanded' => 真 ))

对象用户:

    /**
 * @ORM\ManyToMany(targetEntity="Shootngo\CoreBundle\Entity\Category", cascade={"persist"})
 * @ORM\JoinTable(name="sng_member_categories")
 */
private $category;

在构造函数中定义属性 $category 上的 ArrayCollection()。

这是可行的 :D