Symfony 2-每个实体实例的表格 [英] Symfony 2 - Form for each instance of entity

查看:44
本文介绍了Symfony 2-每个实体实例的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间段"功能,用户必须能够编辑每个时间段的开始和结束.

I have a Timeslot functionality where the user has to be able to edit the start and end of each slot.

所以我想创建一种包含alle时隙的表单.我的代码基于symfony文档中的这篇文章: http://symfony.com/doc/current/cookbook/form/form_collections.html 问题在于,在本文中,应该将集合实例分配给某种父实体.就我而言,这些时隙是独立的,并且与另一个实体没有关系(在此阶段是无关紧要的).

So I would like to create one form that contains alle timeslots. I based my code on this article in symfony docs: http://symfony.com/doc/current/cookbook/form/form_collections.html The problem is that in this article, there's some kind of parent entity to which the collection instances should be assigned to. In my case, the timeslots are standalone and do not have a relation with another entity (that is relevent at this stage).

所以..我的问题:如何使用我的时隙创建一组表单?

So.. my question: How do I create a collection of forms with my timeslots?

Controller.php

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:

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';
    }
}

有什么想法吗? 预先感谢!

Any thoughts? thanks in advance!

推荐答案

将数组而不是实体传递给表单.表单可以很好地处理.

Pass an array instead of an entity to your form. The form can process either just fine.

$timeslots = $this->getDoctrine()->getRepository("ScheduleBundle:Timeslot")->findAll();

$formData = array('timeslots' => $timeslots);

$timeslots_form = $this->createFormBuilder($formData) ...

这篇关于Symfony 2-每个实体实例的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆