修改Symfony 2形成行为



我正在使用Symfony 2。

我的表格工作方式如下:

  • 表单在Ajax(JQuery)中提交

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

<错误><错误id="name">此字段不能为空<错误><错误id="电子邮件">此电子邮件地址无效<错误><错误id="生日">生日不可能在未来<错误><错误>
  • 如果我的表单中没有错误,我会收到一个带有重定向URL的XML响应
<重定向url="/confirm">lt/重定向>
  • 我的问题是:如何"永远"改变Symfony 2中表单的行为,以便使用如下控制器:
公共函数registerAction(Request$Request){$member=new member();$form=$this->createFormBuilder($member)->add('name','text')->添加("邮件"、"电子邮件")->add("生日"、"日期")->getForm();if($request->getMethod()=='POST'){$form->bindRequest($request);if($form->isValid()){//返回带有重定向URL的XML响应}其他{//返回带有错误消息的XML响应}}//返回HTML表单}

谢谢你的帮助,

问候,

表单处理程序也是我的工作方式。在formHandler中验证表单,并根据来自formHandler的响应在控制器中创建json或xml响应。

<?php
namespace ApplicationCrmBundleFormHandler;
use SymfonyComponentFormForm;
use SymfonyComponentHttpFoundationRequest;
use ApplicationCrmBundleEntityNote;
use ApplicationCrmBundleEntityNoteManager;
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条错误消息,但它对我来说很有用。

考虑将此逻辑封装在"表单处理程序"服务中,类似于FOSUserBundle:中的操作

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

最新更新