3

对于我的学校项目,我正在开发一个数据库管理应用程序。这是我的第一个真正的 Zend Framework 应用程序。

现在,现在,我根据需要设置了 3 个值,邮政编码、电子邮件和电话。他们需要像这样(示例):

        $mail = $this->createElement('text', 'mail');
    $mail->setLabel('E-mail:')
            ->setAttrib('size', 50)->addValidator('StringLength', false, array(6, 40))->addValidator('EmailAddress', true)
            ->setRequired(true);
        $telephone = $this->createElement('text', 'telephone');
    $telephone->setLabel('Telephone:')
            ->setAttrib('size', 50)->addValidator('StringLength', false, array(10, 10))
            ->setRequired(true);

我怎样才能只需要其中一个?

我正在使用 Zend_Form,也正在使用 Displaygroups。

有人知道我的程序的解决方案吗?也许使用数组?

提前致谢,

约里特

更新

@brady.vitrano

好的,我的代码的第一部分现在看起来像这样:

<?php

class Application_Form_Validate_ContactMethodSelected
extends Zend_Validate_Abstract
{
const INVALID = 'invalid';

protected $_messageTemplates = array(
    self::INVALID => 'Must select at least one contact method'
);

public function isValid($value, $context = array())
{
     // You need to use your element names, consider making these dynamic
    $checkFields = array('telefoon','mobiel','mail');
    // Check if all are empty
    foreach ( $checkFields as $field ) {
        if (isset($context[$field]) && !empty($context[$field])) {
            // Only one value needs to return true..skip the rest
            return true;
        }
    }

    // All were empty, set your own error message
    $this->_error(self::INVALID);
    return false;
}

}

class Application_Form_Nieuwkandidaat extends Zend_Form
{

public function init()
{
     $this->setMethod('post');
    $DB = Zend_Db_Table::getDefaultAdapter();


    $telefoon = $this->createElement('text', 'telefoon');
    $telefoon->setLabel('Telefoon:')
            ->setAttrib('size', 50)->addValidator('StringLength', false,array(10,10));
    $telefoon->addValidator(new Application_Form_Validate_ContactMethodSelected());
    $mobiel = $this->createElement('text', 'mobiel');
    $mobiel->setLabel('Mobiel:')
            ->setAttrib('size', 50)->addValidator('StringLength', false,array(10,10));
    $mobiel->addValidator(new Application_Form_Validate_ContactMethodSelected());
    $mail = $this->createElement('text', 'mail');
    $mail->setLabel('E-mail:')
            ->setAttrib('size', 50)->addValidator('StringLength', false,array(6,40))->addValidator('EmailAddress', true);
    $mail->addValidator(new Application_Form_Validate_ContactMethodSelected());

点击提交按钮后它不会显示消息。我还应该改变什么?感谢您的帮助!

4

4 回答 4

13

一个很好的解决方案是为元素编写一个自定义验证器。

在您的isValid方法中,您必须根据$context其他值进行检查。就像是:

编辑

/** /library/Application/Form/Validate/ContactMethodSelected.php **/

class Application_Form_Validate_ContactMethodSelected 
    extends Zend_Validate_Abstract
{
    const INVALID = 'invalid';

    protected $_messageTemplates = array(
        self::INVALID => 'Must select at least one contact method'
    ); 

    public function isValid($value, $context = array())
    {
         // You need to use your element names, consider making these dynamic
        $checkFields = array('phone','email','address');
        // Check if all are empty
        foreach ( $checkFields as $field ) {
            if (isset($context[$field]) && !empty($context[$field])) {
                // Only one value needs to return true..skip the rest
                return true;
            }
        }

        // All were empty, set your own error message
        $this->_error(self::INVALID);
        return false;   
    }

}

现在,您必须告诉元素使用该验证器。因此,请更改您的表单init()方法。

 $mail->addValidator(new Application_Form_Validate_ContactMethodSelected());
 $telephone->addValidator(new Application_Form_Validate_ContactMethodSelected());

不要忘记:一旦你有了自己的自定义验证器,你就必须isRequired()从每个元素中删除 。

编辑2

您必须将自定义验证器设置为链中的第一个验证器并在失败时中断。另外,你必须setAllowEmpty()假。

$telefoon = $this->createElement('text', 'telefoon');
$telefoon->setLabel('Telefoon:')
        ->setAttrib('size', 50)->setAllowEmpty(false)
        ->addValidator(new Application_Form_Validate_ContactMethodSelected(),true)
        ->addValidator('StringLength', false,array(10,10));
$mobiel = $this->createElement('text', 'mobiel');
$mobiel->setLabel('Mobiel:')
        ->setAttrib('size', 50)->setAllowEmpty(false)
        ->addValidator(new Application_Form_Validate_ContactMethodSelected(),true)
        ->addValidator('StringLength', false,array(10,10));
$mail = $this->createElement('text', 'mail');
$mail->setLabel('E-mail:')
        ->setAttrib('size', 50)->setAllowEmpty(false)
        ->addValidator(new Application_Form_Validate_ContactMethodSelected(),true)
        ->addValidator('StringLength', false,array(6,40))->addValidator('EmailAddress', true);

接下来,您必须isValid使用以下内容更新该方法:

public function isValid($value, $context = array())
{
    // You need to use your element names, consider making these dynamic
    $checkFields = array('telefoon','mobiel','mail');
    // Check if all are empty
    foreach ( $checkFields as $field ) {
    if (isset($context[$field]) && !empty($context[$field])) {

        if (!empty($value)) {
            // This is the element with content... validate as true
            return true;
        }
        // we are going to return false and no error
        // to break validation chain on other empty values
        // This is a quick hack, don't have time to invest in this
        return false;
        }
    }

    // All were empty, set your own error message
    $this->_error(self::INVALID);
    return false;
}

现在,您必须在使用此验证器的代码中添加另一个条件。我们必须要求表单没有任何错误消息。

if ($form->isValid($_POST) || !count($form->getMessages())) {
    /** Valid, now you can process **/
} else {
    /** Not valid **/
}
于 2011-07-13T17:05:34.293 回答
3

我认为最好的方法是最简单的方法。您不必编写任何自定义验证器。在表单验证之后,您只需检查所需值之一是否显示为非空,因为这样您就可以访问过滤和验证的表单值。

if ($form->isValid($_POST)) {

    // get filtered and validated form values
    $params = $form->getValues();

    // check if there is a selected contact method
    if (isContactMethodSelected ($params)) {
       // the form is Valid!

    } else {
       // not valid
    }


} else {
    // not valid
}

这是“isContactMethodSelected”方法。您可以简单地将其添加到当前控制器类中。

private function isContactMethodSelected ($params) {

        // define array with the contact methods as they appear in the $params as keys
        $checkFields = array('telefoon','mobiel','mail');

        // check if there is at least one contact method selected
        foreach ($checkFields as $field) {
            if (isset($params[$field]) && !empty($params[$field])) {
                return true;
            }
        }

        return false;
    }
于 2011-11-11T08:14:13.730 回答
1

我认为最简单和最快的解决方案是覆盖表单本身的 isValid 函数

class Application_Form_Nieuwkandidaat extends Zend_Form
{

    //...

    public function isValid($data)
    {
        $valid = parent::isValid($data);
        if ( ! $data['mail'] && ! $data['telephone'] && ! $data['postcode'] ){
            $this->addError('Please supply one of email, telephone or postcode');
            $valid = false;
        }
        return $valid;
    }

    //...

}

一个小功能,与表单相关,易于理解,不太可能失败,不太可能成为困难错误的来源。

于 2011-11-11T09:15:30.600 回答
0

去除那个

$foo->setRequired();

您不想根据需要设置的两个方法....

$telephone->setLabel('Telephone:')
          ->setAttrib('size', 50)
          ->addValidator('StringLength', false, array(10, 10))
          ->setRequired(true);

变成

$telephone->setLabel('Telephone:')
          ->setAttrib('size', 50)
          ->addValidator('StringLength', false, array(10, 10));
于 2011-07-13T16:33:48.620 回答