7

我有 todolist,我在其中显示三种形式的任务类型

$task1 = new Task();
$form1 = $this->createForm(new MyForm('f1'), $task1);

$task2 = new Task('fo');
$form2 = $this->createForm(new MyForm('f2'), $task2);

$task3 = new Task();
$form3 = $this->createForm(new MyForm('f3'), $task3);

现在的问题是我只有一个提交按钮。我怎样才能在一个控制器中保留这三个任务。用户也可以动态添加更多表单。

那么解决这个问题的方法是什么

4

3 回答 3

5

创建一个包含 s 集合的Form Model类。然后创建包含s的集合。这样,您将拥有一个包含任意数量任务的表单。TaskListTaskTaskListTypeTaskType

于 2012-08-01T20:37:17.810 回答
5

为了完整起见,请在下面找到一个完整的示例。

您应该创建一个代表所需形式的新模型。关键是您可能不想影响 Doctrine(例如,请参阅教义:模式:更新命令)。它可能会尝试为实际上并不存在的实体创建一个表。为避免这种情况,只需将模型类放在模型文件夹 (\src\Acme\Bundle\DemoBundle\Model\TaskList.php) 下。

假设以下是您的 TaskType 表单类:

<?php

namespace Acme\Bundle\DemoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TaskType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', null, array('read_only' => true))
            ->add('name');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'Acme\Bundle\DemoBundle\Entity\Task'
            )
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'acme_demo_task';
    }
}

这应该是您的 TaskList 模型类:

<?php

namespace Acme\Bundle\DemoBundle\Model;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Class TaskList
 * @package Acme\Bundle\DemoBundle\Model
 *
 * @ORM\Entity()
 */
class TaskList
{
    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     * @ORM\ManyToMany(targetEntity="\Acme\Bundle\DemoBundle\Entity\Task")
     */
    private $tasks;

    public function __construct()
    {
        $this->tasks = new ArrayCollection();
    }

    /**
     * @param \Acme\Bundle\DemoBundle\Entity\Task $task
     * @return $this
     */
    public function addTask(\Acme\Bundle\DemoBundle\Entity\Task $task)
    {
        $this->tasks[] = $task;

        return $this;
    }

    /**
     * @param \Acme\Bundle\DemoBundle\Entity\Task $task
     * @return $this
     */
    public function removeTask(\Acme\Bundle\DemoBundle\Entity\Task $task)
    {
        $this->tasks->remove($task);

        return $this;
    }

    /**
     * @return ArrayCollection
     */
    public function getTasks()
    {
        return $this->tasks;
    }

    /**
     * @param \Doctrine\Common\Collections\Collection $tasks
     * @return $this
     */
    public function setTasks(\Doctrine\Common\Collections\Collection $tasks)
    {
        $this->tasks = $tasks;

        return $this;
    }

    /**
     * @param \Knp\Component\Pager\Pagination\PaginationInterface $pagination
     * @return $this
     */
    public function setFromPagination(\Knp\Component\Pager\Pagination\PaginationInterface $pagination)
    {
        foreach ($pagination as $task) {
            $this->addTask($task);
        }

        return $this;
    }
}

并在 TaskListType 类下面找到:

<?php

namespace Acme\Bundle\DemoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TaskListType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'tasks',
                'collection',
                array(
                    'type' => new \Acme\Bundle\DemoBundle\Form\TaskType(),
                )
            )
            ->add('save', 'submit');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'Acme\Bundle\DemoBundle\Model\TaskList'
            )
        );
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'acme_demo_task_list';
    }
}

还有你的 services.yml(可选):

services:
    acme.demo.form.type.task_list:
        class: Acme\Bundle\DemoBundle\Form\TaskListType
        tags:
            - { name: form.type, alias: acme_demo_task_list }

和一个示例控制器:

public function indexAction($page)
{
    ini_set('xdebug.max_nesting_level', 300); // this might be useful with deeply nested forms

    $search = $this->getRequest()->get(
        'search',
        array(
            'name' => '',
            'date' => '',
            'lang' => $this->container->getParameter('acme_core.default_lang')
        )
    );

    /**
     * @var \Doctrine\ORM\EntityManager $em
     */
    $em = $this->getDoctrine()->getManager();

    $paginator = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $em->getRepository('AcmeDemoBundle:Task')->getQueryFilteringByLangNameAndDate(
            $search['lang'],
            $search['name'],
            $search['date'] != '' ? new \DateTime($search['date']) : null
        ),
        $page,
        $this->getRequest()->get('elementsPerPage', 10)
    );

    $taskList = new TaskList();
    $taskList->setFromPagination($pagination);

    $form = $this->createForm('acme_demo_task_list', $taskList); // "acme_demo_task_list" has been defined in the services.yml file
    $form->handleRequest($this->getRequest());

    if ($form->isValid()) {
        foreach ($form->getData() as $task) {
            $em->merge($task);
        }
        $em->flush();
    }

    return $this->render(
        'AcmeDemoBundle:Task:index.html.twig',
        array(
            'search' => $search,
            'pagination' => $pagination,
            'form' => $form->createView()
        )
    );
}

我希望这有帮助!

于 2014-02-24T14:54:48.157 回答
4

我们遵循了“Francesco Casula”所展示的示例,并且效果很好。

出于 orur 的目的,我们不需要分页,所以这就是我们填充集合的方式(在 中controller):

$entities = $em->getRepository('AcmeBundle:Stock')->findAll();

$stockList = new StockList(); // This is our model, what Francesco called 'TaskList'

foreach ($entities as $entity) {
    $stockList->addStock($entity);
}

// StockListType() is what Francesco called TaskListType
$form = $this->createForm(new StockListType(), $stockList, array(
    'action' => $this->generateUrl('stock_take_update'),
    'method' => 'POST',
    'attr' => array('class' => 'form-horizontal'),
));

对于那些需要自定义表单集合输出的人,我们设法通过迭代来访问子表单{% for form in forms.children.stocks %}。'Stocks' 是我们的表单构建器中的字段名称(在 中StockListType):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'stocks', 'collection', array(
                'type' => new StockType(),
            )
        )
        ->add('submit', 'submit')
    ;
}

这就是我们最终在 twig 视图中使用的内容:

{{ form_start(forms) }}
    <table class="table table-stripped table-hover">
        <thead>
            <th>#</th>
            <th>Name</th>
            <th>Code</th>
            <th>Location</th>
            <th>Total</th>
            <th>Updated Toal</th>
        </thead>
        <tbody>
            {% set counter = 1 %}
            {% for form in forms.children.stocks %}
                <tr>
                    <div class="hidden">
                        {{ form_widget(form.name) }}
                        {{ form_widget(form.code) }}
                        {{ form_widget(form.location) }}
                        {{ form_widget(form.available) }}
                        {{ form_widget(form.assigned) }}
                        {{ form_widget(form.minLevel) }}
                        {{ form_widget(form.type) }}
                        {{ form_widget(form.colourCode) }}
                    </div>
                    <td>{{ counter }}</td>
                    <td>
                        {% if form.vars.data.name is defined %}
                            {{ form.vars.data.name }}
                        {% endif %}
                    </td>
                    <td>
                        {% if form.vars.data.code is defined %}
                            {{ form.vars.data.code }}
                        {% endif %}
                    </td>
                    <td>
                        {% if form.vars.data.location is defined %}
                            {{ form.vars.data.location }}
                        {% endif %}
                    </td>
                    <td>
                        {% if form.vars.data.total is defined %}
                            {{ form.vars.data.total }}
                        {% endif %}
                    </td>
                    <td>{{ form_widget(form.total) }}</td>
                </tr>
                {% set counter = counter + 1 %}
            {% endfor %}
        </tbody>
    </table>
    {{ form_widget(forms.submit) }}
{{ form_end(forms) }}
于 2014-08-01T14:15:39.950 回答