首页 文章

修改Symfony 2形成行为

提问于
浏览
0

我正在使用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>
  • 如果表单中没有错误,我会收到带有重定向URL的XML响应
<redirect url="/confirm"></redirect>
  • My question is :如何更改"forever" 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 回答

  • 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个错误消息,但它对我有用 .

  • 0

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

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

相关问题