简体   繁体   English

Zend_Validate_Db_RecordExists或为空值

[英]Zend_Validate_Db_RecordExists or empty value

I've got a (hopefuly) simple task, and my google fu has failed me. 我完成了一个(充满希望的)简单任务,而我的Google Fu使我失败了。 Basically, I've got a form with a select which contains an empty value and then number of ids given content can belong to. 基本上,我有一个带有select的表单,其中包含一个空值,然后给定内容的ID数可以属于。 What I want to do is - validate if the given ids exist, but only if a value is set. 我想做的是-验证给定ID是否存在,但仅在设置了值的情况下。 This: 这个:

$field = new Zend_Form_Element_Select('field');
$field->addValidator(
    new Zend_Validate_Db_RecordExists(
        array(
            'table' => 'categories',
            'field' => 'id'
        )
));

takes care of the checking if the given id exists, but I'm not able to find any way to omit this if value is empty. 负责检查给定的id是否存在,但是如果value为空,我将找不到任何方法来忽略它。 One way to do this would be to move this logic to isValid method, but I'm hoping there's nicer way to accomplish this task. 一种方法是将该逻辑移至isValid方法,但我希望有更好的方法来完成此任务。

Try to set this form element as not required: 尝试根据需要设置此表单元素:

$field->setRequired(false);

When element is not required and is not filled, validators queue won't be run. 如果不需要元素且未填充元素,则不会运行验证程序队列。

Quick example which works for me: 对我有用的快速示例:

// Zend_Form form body
$this->addElement('select', 'category', array(
        'label' => 'Choose category',
        'required' => false,
        'multiOptions' => array(
                null => 'No category selected',
                '1' => 'One',
                '2' => 'Two',   
        ),
        'validators' => array(
                array('Db_NoRecordExists', false, array(
                        'schema' => 'public',
                        'table' => 'category',
                        'field' => 'id',    
                )), 
        ),
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM