【问题标题】:Symfony2 Handling Submit in Form ClassSymfony2 处理表单类中的提交
【发布时间】:2015-03-26 08:45:29
【问题描述】:

这是我的疑问:

所以我根据文档创建了表单类: 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-and-doctrine) 中提示您要做什么,但它什么也没说(或者我找不到)当您使用表单类时,究竟在哪里以及如何处理提交。一点帮助将不胜感激。

提前谢谢你

【问题讨论】:

    标签: php forms symfony doctrine-orm submit


    【解决方案1】:

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

    表单动作仍然在控制器中处理。
    给定您的示例表单类型类,例如;

    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 best practices 的表格。

    【讨论】:

      【解决方案2】:

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

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

      否则,Rooneyl 的答案就是您要找的。​​p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-10
        • 1970-01-01
        • 2017-01-26
        • 2016-11-10
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 2013-04-22
        相关资源
        最近更新 更多