我被Form Collection困住了。我想创建一个表单来处理同一类型的多个entties。
所以我有几个实体Timetick
和Employee
// Timeetick-Entity
class Timetick
{
private $timetickId;
private $timeStart;
private $timeEnd;
/**
* @ORM\ManyToOne(targetEntity="MyBundle\Entity\Employee", inversedBy="timeticks")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="employee_id", referencedColumnName="employee_id", nullable=false)
* })
*/
private $emplyoee;
public function getEmployee() { /*...*/ }
public function getStart() {}
public function getEnd() {}
}
// Employee-Entity
class Employee
{
private $employeeId;
private $name;
/**
* @ORM\OneToMany(targetEntity="MyBundle\Entity\Timetick", mappedBy="employee")
*/
private $timeticks;
public function getTimeticks() { /*...*/ }
}
// TimetickType for generating a Timetick-Form
class TimetickType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('timeStart' 'time', array(/*....*/)
->add('timeEnd', 'time', array(/*....*/));
}
public function getName() { /*....*/ }
}
class MyCombinedForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// continas only 'timeticks'
$builder->add('timeticks', 'collection', array(
'type' => new TimetickType()
));
}
}
有时我必须更新在某个日期找到的实体,有时候不止一个。因此,我希望以一种“大”形式查看/编辑和处理每个找到的实体的表单块集合。所以我只有一个表单只有一个提交按钮,但每个找到的实体有几个“数据部分”
为了实现这个目的,我试图按照上述页面中的说明进行操作,但没有成功
// $data is an instance of Employee, so i can access Timeticks just by $data->getTimeticks->toArray()
$data = $this->getDoctrine()->getRepository('MyBundle:Employee')->myCustomFindMethod( $criteria );
$form = $this->createForm(new MyCombinedForm(), $data);
每次我得到例外:
表单的视图数据应该是标量,数组或\ ArrayAccess的实例,>类型,但是类MyBundle \ Entity \ Timetick的实例。您可以通过将>设置“data_class”选项设置为“MyBundle \ Entity \ Timetick”或添加视图>转换器来避免此错误,该转换器将类MyBundle \ Entity \ Timetick的实例转换为>标量,数组或实例\ ArrayAccess。
所以我按照建议并将'data_class'添加到ny MyCombinedForm
FormType o现在看起来像这样:
class MyCombinedForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// continas only 'timeticks'
$builder->add('timeticks', 'collection', array(
'type' => new TimetickType(),
'data_class' => 'MyBundle\Entity\Timetick', //ADDED!
));
}
}
但是现在又生了另一个Aception:
表单的视图数据应该是MyBundle \ Entity \ Timetick类的实例,但它是>类Doctrine \ ORM \ PersistentCollection的实例。您可以通过将>“data_class”选项设置为null或通过添加将类Doctrine \ ORM \ PersistentCollection的实例>转换为MyBundle \ Entity \ Timetick实例的视图转换器来避免此错误。
我该怎么做错了?!