Zend Framework:需要三个值中的一个

时间:2011-07-13 16:31:59

标签: php zend-framework zend-form require requiredfieldvalidator

对于我的学校项目,我正在研究数据库管理应用程序。 这是我第一个真正的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。

是否有人知道我的计划的解决方案?也许使用数组?

提前致谢,

JorritK

更新

@ 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 个答案:

答案 0 :(得分:13)

要考虑的一个好方法是write a custom validator元素。

在您的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()

<强> EDIT2

您必须将自定义验证程序设置为链中的第一个验证程序,并在失败时中断。此外,您必须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 **/
}

答案 1 :(得分: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
}

这是&#34; isContactMethodSelected&#34;方法。您只需将其添加到当前控制器类中即可。

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;
    }

答案 2 :(得分: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;
    }

    //...

}

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

答案 3 :(得分: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));