2015-06-20 38 views
0

我在ZF2網站創建了一個表單,在這裏我已經解決了很多問題: Zend Framework 2 - Submitting a form(請參見查找代碼)。
現在我有另一個問題:在我的控制器中,無論如何,form->isValid()都會返回true。我的目標是通過PHP進行驗證,然後通過Ajax告訴用戶是否一切正常。我想我的InputFilter出了問題,或者它沒有正確地連接到我的表單。
有什麼建議嗎?提前致謝。Zend Framework 2 - 編寫和設置一個好的InputFilter

回答

0

解決了這個問題。 把所有的校驗器都放在與作業相同的班級中;這是(窮人)官方文檔和一些論壇話題在這裏和其他地方的混合體。 Form類現在看起來像這樣:

<?php 
namespace Site\Form; 

use Zend\Form\Form; 
use Zend\Form\Element; 
use Zend\InputFilter\Input; 
use Zend\InputFilter\InputFilter; 
use Zend\Validator; 

class ContactForm extends Form { 
    public function __construct($name=null, $options=array()) { 
     parent::__construct ($name, $options); 

     $this->setAttributes(array(
      "action" => "./", 
     )); 


     $nameInput = new Element\Text("nome"); 
     $nameInput->setAttributes(array(
      "placeholder" => "Nome e cognome", 
      "tabindex" => "1" 
     )); 

     $this->add($nameInput); 

     $emailInput = new Element\Text("email"); 
     $emailInput->setAttributes(array(
      "placeholder" => "Indirizzo e-mail", 
      "tabindex" => "2" 
     )); 

     $this->add($emailInput); 

     $phoneInput = new Element\Text("phone"); 
     $phoneInput->setAttributes(array(
      "placeholder" => "Numero di telefono", 
      "tabindex" => "3", 
     )); 

     $this->add($phoneInput); 

     $messageArea = new Element\Textarea("messaggio"); 
     $messageArea->setAttributes(array(
      "placeholder" => "Scrivi il tuo messaggio", 
      "tabindex" => "4" 
     )); 

     $this->add($messageArea); 

     $submitButton = new Element\Button("submit"); 
     $submitButton 
      ->setLabel("Invia messaggio") 
      ->setAttributes(array(
       "type" => "submit" 
      )); 

     $this->add($submitButton); 

     $resetButton = new Element\Button("reset"); 
     $resetButton 
     ->setLabel("Cancella") 
     ->setAttributes(array(
       "type" => "reset" 
     )); 

     $this->add($resetButton); 

     $inputFilter = new InputFilter(); 

     $nome = new Input("nome"); 
     $nome->getValidatorChain() 
     ->attach(new Validator\StringLength(3)); 

     $email = new Input("email"); 
     $email->getValidatorChain() 
     ->attach(new Validator\EmailAddress()); 

     $phone = new Input("phone"); 
     $phone->getValidatorChain() 
     ->attach(new Validator\Digits()); 

     $message = new Input("messaggio"); 
     $message->getValidatorChain() 
     ->attach(new Validator\StringLength(10)); 

     $inputFilter->add($nome) 
        ->add($email) 
        ->add($phone) 
        ->add($message); 

     $this->setInputFilter($inputFilter); 
    } 
} 
?> 

我會稍後嘗試工廠,但現在,這個工程。