2015-06-20 36 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); 
    } 
} 
?> 

我会稍后尝试工厂,但现在,这个工程。