2012-01-20 26 views
0

我使用的Symfony 2修改Symfony的2種形式的行爲

我的形式工作方式是這樣的:

  • 形式在阿賈克斯提交(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> 

  • 我的問題是:我怎樣才能改變「永遠」的行爲在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 
    } 

感謝您的幫助,

問候,

回答

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個錯誤消息,但它爲我做了詭計。