我的收藏表格类型有问题。我的实体:
用户
use Doctrine\Common\Collections\ArrayCollection; /** * @OneToMany(targetEntity="Comment", mappedBy="user") */ protected $comments; public function __construct() { $this->comments= new ArrayCollection(); }
注释
/** * @ManyToOne(targetEntity="User", inversedBy="comments") * @JoinColumn(name="user_id", referencedColumnName="id") **/ protected $user;
Formbuilder:
$form = $silex['form.factory']->createBuilder('form', $user)
->add('comments', 'collection', array(
'type' => 'text',
'options' => array(
'required' => false,
'data_class' => 'Site\Entity\Comment'
),
))
->getForm();
并返回错误:
Catchable fatal error: Object of class Site\Entity\Comment could not be converted to string in C:\XXX\vendor\twig\twig\lib\Twig\Environment.php(331) : eval()'d code on line 307 Call Stack
答案 0 :(得分:1)
我认为你可能很难在这里使用文本类型集合字段,因为你想要一个复杂实体集合的字段而不仅仅是一个字符串数组。
我建议为评论实体添加新的表单类型:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class CommentType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('text', 'text', array());
}
public function getName() {
return 'comment';
}
public function getDefaultOptions(array $options) {
return array(
'data_class' => 'Site\Entity\Comment'
);
}
}
然后在原始的Formbuilder中,引用此类型:
$form = $silex['form.factory']->createBuilder('form', $user)
->add('comments', 'collection', array(
'type' => new CommentType(),
'options' => array(
'required' => false,
'data_class' => 'Site\Entity\Comment'
'allow_add' => true,
'allow_delete' => true
),
))
->getForm();