【问题标题】:set the attributes in PHP 5在 PHP 5 中设置属性
【发布时间】:2012-06-03 02:35:05
【问题描述】:

在我的 Zend 框架中,我有两行,其中一行包含带有标签状态的状态下拉列表,另一行包含带有标签其他状态的文本框。下面是代码:

'state' => array('select', array(
            'required' => true,
            'decorators' => $elementDecorators,
            'label' => 'State:',
            'multiOptions' => $values["state"] 
        )),
        'other_state' => array('text', array(
            'required' => true,
            'filters'    => array('StringTrim'),
            'decorators' => $elementDecorators,
            'label' => 'Other State:',
            'class' => 'other_state', 
        ))

这里根据需要设置其他状态。只有当用户从状态下拉列表中选择“其他”值时,我才需要它。

【问题讨论】:

    标签: php jquery zend-framework


    【解决方案1】:

    客户端:

    jQuery解决方案:

    在这里显示您的 HTML 输出会有所帮助。但是如果选择了other,以下将添加所需的属性 - 这也将启用输入并禁用它,因此用户只能在其他状态下输入内容,如果他们选择其他:

    $("#state").change(function(){
        if ($(this).val() == "other"){
            $("#other_state").removeAttr("disabled");
            $("#other_state").attr("required", "required");
        }
        else {
            $("#other_state").removeAttr("required");
            $("#other_state").attr("disabled", "true");
        }
    });
    

    See a demo here

    上面将在客户端进行验证 - 使用 jQuery,但是如果用户关闭了 javascript,它将允许用户选择 other 并将 other_state 留空!


    服务器端:

    Zend 解决方案:

    您还应该在zend_form 中添加一些validation。但是,您不能以正常方式添加它们 - 如果您添加了一个验证器来说明 other_state 不能为空 - 当您选择一个状态并且您希望它为空时会出现错误。

    在您的表单类中,您可以覆盖 isValid 调用以添加您的自定义验证,请参阅discussion here还有另一个示例说明如何执行此操作here

        /** 
        /* override the isValid function of Zend_Form 
        /* to set a required field based on a condition 
         */ 
    
        public function isValid($value) {
                // Check the key exists in the stack, and if its set to other: 
                if (array_key_exists('state', $value) && $value['state'] == 'other') { 
                        // It is so make sure other_state is a required field:
                        $this->other_state->setRequired(true); 
                } 
                parent::isValid($value); 
        } 
    

    【讨论】:

      猜你喜欢
      • 2012-03-08
      • 2017-10-23
      • 1970-01-01
      • 2020-10-11
      • 2018-04-01
      • 1970-01-01
      • 2011-01-23
      • 2012-05-13
      • 2012-06-21
      相关资源
      最近更新 更多