Symfony2 处理表单类中的提交


Symfony2 Handling Submit in Form Class

这是我的疑问:

因此,我根据文档创建了表单类:http://symfony.com/doc/current/book/forms.html#creating-form-classes

// src/AppBundle/Form/Type/TaskType.php
namespace AppBundle'Form'Type;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'Form'FormBuilderInterface;
class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('task')
            ->add('dueDate', null, array('widget' => 'single_text'))
            ->add('save', 'submit');
    }
    public function getName()
    {
        return 'task';
    }
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
        'data_class' => 'AppBundle'Entity'Task',
        ));
    }
}

但是我不知道在哪里放置提交处理程序。在 http://symfony.com/doc/current/book/forms.html#handling-form-submissions 中,它与其他所有内容一起放在控制器中,并在(...#forms 和学说)中提示您该怎么做,但它没有说明(或者我找不到它)关于使用表单类时确切的位置以及如何处理提交。一点帮助将不胜感激。

提前谢谢你

使用表单类型,因此您不必继续创建相同的表单,或者只是为了保持独立。

表单操作仍由控制器处理。
给定您的示例表单类型类,如下所示;

public function taskAction(Request $request)
{
    // build the form ...
    $type = new Task();
    $form = $this->createForm(new TaskType(), $type);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        // do whatever you want ...
        $data = $form->getData(); // to get submitted data
        // redirect, show twig, your choice
    }
    // render the template
}

看看Symfony表单的最佳实践。

如果您需要为表单提供一些验证后逻辑,则可以创建一个表单处理程序,该处理程序还将嵌入验证或侦听 Doctrine 事件。

但这只是更复杂的用法;)的提示

否则,Rooneyl的答案就是你要找的。