我有一个时间段功能,用户必须能够编辑每个时间段的开始和结束。
所以我想创建一种包含所有时间段的表单。我的代码基于 symfony 文档中的这篇文章:http://symfony.com/doc/current/cookbook/form/form_collections.html 问题在于,在本文中,应该将集合实例分配给某种父实体。就我而言,时隙是独立的,与另一个实体没有关系(在这个阶段相关)。
所以..我的问题:如何使用我的时间段创建表单集合?
Controller .php
/**
* @Route("/settings", name="settings")
* @Template()
*/
public function settingsAction()
{
$timeslots = $this->getDoctrine()->getRepository("ScheduleBundle:Timeslot")->findAll();
$timeslots_form = $this->createFormBuilder()
->add('timeslots', 'collection', array(
'type' => new TimeslotType(),
))
->add('save', 'submit')
->getForm();
return array(
'timeslots' => $timeslots_form->createView()
);
}
TimeslotType.php:
class TimeslotType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('start', 'time', array(
'input' => 'datetime',
'widget' => 'choice',
))
->add('end', 'time', array(
'input' => 'datetime',
'widget' => 'choice',
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Oggi\ScheduleBundle\Entity\Timeslot'
));
}
/**
* @return string
*/
public function getName()
{
return 'timeslot';
}
}
有什么想法吗? 提前致谢!
最佳答案
将数组而不是实体传递到表单。该表单可以很好地处理。
$timeslots = $this->getDoctrine()->getRepository("ScheduleBundle:Timeslot")->findAll();
$formData = array('timeslots' => $timeslots);
$timeslots_form = $this->createFormBuilder($formData) ...
关于php - Symfony 2 - 每个实体实例的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25485325/