2012-01-20 2 views
0

Я использую Symfony 2.Изменение 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 с перенаправлением URL
 

    <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

Обработчик формы является как я это делаю. Подтвердите форму в формеHandler и создайте ответ json или xml в контроллере в зависимости от ответа от формыHandler.

<?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 сообщение об ошибке в поле, но это делает трюк для меня.

Смежные вопросы