2014-09-02 82 views
1

我有一個集合表單類型的問題。我的實體:Silex框架集合表單類型

用戶

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

你有一個'__toString()'函數在'Comment'上? – Maerlyn 2014-09-02 05:21:39

+0

當我添加__toString()它的工作,但其他形式與添加註釋不工作。 – user3735229 2014-09-02 10:07:50

+0

你可以請發佈模板? – 2014-09-02 13:01:07

回答

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();