Zend框架形式非理性行为

时间:2009-08-30 15:52:57

标签: php html zend-framework zend-form

让我们用一段简短的代码片段开始,我将用它来证明我的观点:

$title = new Zend_Form_Element_Text('title', array(
    'label' => 'Title',
    'required' => false,
    'filters' => array(
        'StringTrim',
        'HtmlEntities'
    ),
    'validators' => array(
        array('StringLength', false, array(3, 100))
    ),
));

这条重要的路线是:

'required' => false,

这意味着输入字段不是必需的,您可以在不填写表单的情况下提交表单。但是,如果您选择填写此字段,这也意味着任何过滤器和验证器都不适用。

常识告诉我这是一种非理性的行为。我理解与HTML输入字段相关的“必需”一词的方式:如果没有填写,则不需要的输入字段应返回NULL但如果用户决定填充它,则过滤器和验证器都应该应用它。这对我来说是有意义的。你是否同意我或我的常识不是很常见?

现在更实际的问题,因为这是Zend_Form的行为,我怎样才能实现不像上面描述的那样工作的必需字段(如果用户没有输入任何内容它返回NULL,否则通常应用过滤器和验证器)。

2 个答案:

答案 0 :(得分:3)

对你的问题不是一个完整的答案,但由于评论没有语法格式;这是一个过滤器,可用于使字段值为空时为空。

class My_Filter_NullIfEmpty implements Zend_Filter_Interface
{
    public function filter( $value )
    {
          // maybe you need to expand the conditions here
        if( 0 == strlen( $value ) )
        {
            return null;
        }
        return $value;
    }
}

关于所需部分: 我不确定。您可以尝试在Nabble上搜索ZF邮件列表:

http://www.nabble.com/Zend-Framework-Community-f16154.html

或订阅他们的邮件列表,并向他们提问。通过Nabble,或直接通过framework.zend.com上的地址: http://tinyurl.com/y4f9lz

编辑: 好的,所以现在我自己做了一些测试,因为你所说的一切对我来说都是直观的。你的例子适合我。这就是我用过的:

<?php

class Form extends Zend_Form
{
    public function init()
    {

        $title = new Zend_Form_Element_Text('title', array(
                'label' => 'Title',
                'required' => false,
                'filters' => array(
                    'StringTrim',
                    'HtmlEntities',
                    'NullIfEmpty' // be sure this one is available
                ),
                'validators' => array(
                    array('StringLength', false, array(3, 100))
                ),
            ));

        $this->addElement( $title );
    }
}

$form = new Form();

$postValues = array( 'title' => '' ); // or
$postValues = array( 'title' => '        ' ); // or
$postValues = array( 'title' => 'ab' ); // or
$postValues = array( 'title' => ' ab ' ); // or
$postValues = array( 'title' => '<abc>' ); // all work perfectly fine with me

// validate the form (which automatically sets the values in the form object)
if( $form->isValid( $postValues ) )
{
    // retrieve the relevant value
    var_dump( $form->getValue( 'title' ) );
}
else
{
    echo 'form invalid';
}

?>

答案 1 :(得分:1)

实际上,您所描述的是您的期望,这正是Zend_Form的工作原理。如果将元素标记为不需要,则会发生以下情况:(a)如果没有传递值,则跳过验证,但如果(b)传递了值,则必须通过所有验证器才能生效。 / p> <> BTW,ZF邮件列表中提出ZF问题的最佳地点:http://framework.zend.com/archives