修改Symfony 2形成行为

时间:2012-01-20 11:15:11

标签: jquery symfony symfony-forms

我正在使用Symfony 2.

我的表单工作方式如下:

  • 表单以Ajax(JQuery)

  • 提交
  • 如果我的表单中有错误,我会收到包含所有错误消息的XML响应


    <errors>
    <error id="name">This field cannot be blank</error>
    <error id="email">This email address is not valid</error>
    <error id="birthday">Birthday cannot be in the future</error>
    </errors>

  • 如果表单中没有错误,我会收到带有重定向网址的XML响应

    <redirect url="/confirm"></redirect>

  • 我的问题是:我怎样才能“永远”改变Symfony 2中表单的行为,以便我可以使用如下控制器:

    public function registerAction(Request $request)
    {
    $member = new Member();

    $form = $this->createFormBuilder($member)
    ->add('name', 'text')
    ->add('email', 'email')
    ->add('birthday', 'date')
    ->getForm();

    if($request->getMethod() == 'POST') {
    $form->bindRequest($request);

    if($form->isValid()) {
    // returns XML response with redirect URL
    }
    else {
    // returns XML response with error messages
    }
    }

    // returns HTML form
    }

感谢您的帮助,

此致

2 个答案:

答案 0 :(得分:1)

表单处理程序也是我如何做的。验证formHandler中的表单,并根据formHandler的响应在控制器中创建json或xml响应。

<?php
namespace Application\CrmBundle\Form\Handler;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Application\CrmBundle\Entity\Note;
use Application\CrmBundle\Entity\NoteManager;

class NoteFormHandler
{
    protected $form;
    protected $request;
    protected $noteManager;

    public function __construct(Form $form, Request $request, NoteManager $noteManager)
    {
        $this->form = $form;
        $this->request = $request;  
        $this->noteManager = $noteManager;
    }

    public function process(Note $note = null)
    {
        if (null === $note) {
            $note = $this->noteManager->create();
        }

        $this->form->setData($note);

        if ('POST' == $this->request->getMethod()) {
            $this->form->bindRequest($this->request);

            if ($this->form->isValid()) {
                $this->onSuccess($note);

                return true;
            } else { 
                $response = array();
                foreach ($this->form->getChildren() as $field) {
                    $errors = $field->getErrors();
                    if ($errors) {
                        $response[$field->getName()] = strtr($errors[0]->getMessageTemplate(), $errors[0]->getMessageParameters());
                    }
                }

                return $response;
            }
        }

        return false;
    }

    protected function onSuccess(Note $note)
    {
        $this->noteManager->update($note);
    }
}

这只会为每个字段返回1条错误消息,但它对我来说很有用。

答案 1 :(得分:0)

考虑将此逻辑封装在“表单处理程序”服务中,类似于FOSU​​serBundle中的操作:

https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Form/Handler/RegistrationFormHandler.php