php - Symfony 2 - 每个实体实例的表单

标签 php forms symfony

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

所以我想创建一种包含所有时间段的表单。我的代码基于 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/

相关文章:

php - 有没有办法从 PDOException 中获取 sql 语句?

php - MYSQL 为每个新用户创建一行

PHP 阻止一个人多次按“提交”

javascript - Ajax 表单提交进度功能失败?

php - 使用 symfony/form 输入标签

php - 创建昨天的时间戳并将该范围内的所有时间戳分组

php - 将 excel 导入多个表 - PHP 和 MYSQL (codeigniter)

javascript - 选择不会显示自己并且选择一个选项将不起作用

.htaccess - 共享主机上的 symfony2

forms - 实体形式问题与 Symfony2 关系多对多