我对集合表单类型有问题。我的实体:
用户
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
我认为您可能很难在这里使用文本类型的集合字段,因为您想要的字段是复杂实体的集合,而不仅仅是字符串数组。
我建议为评论实体添加一个新的表单类型:
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();