【问题标题】:What is best way to add required mark with label decorator - Zend使用标签装饰器添加所需标记的最佳方法是什么 - Zend
【发布时间】:2012-08-28 16:31:27
【问题描述】:

我有一个关于使用 Zend_Form_Decorator_Label 的问题,为了在需要表单元素时获得以下结果,我需要获取 Label-text *,我想知道如何以最可重用的方式实现它?

是写新的装饰器还是重写 zend_View_helper_FormLabel ? 也许还有其他方法可以实现这一目标?

任何帮助将不胜感激。

【问题讨论】:

    标签: zend-framework zend-form zend-form-element


    【解决方案1】:

    您可以在创建装饰器时添加以下选项之一:

    • optionalPrefix:当元素是可选时使用的标签前缀
    • optionalSuffix:当元素可选时使用的标签后缀
    • requiredPrefix:需要元素时使用的标签前缀
    • requiredSuffix:需要元素时使用的标签后缀

    代码示例:

    $elementDecorators = array(
        'ViewHelper',
        array('Label', array('requiredSuffix' => ' *')),
    );
    
    $userName = new Zend_Form_Element_Text('userName');
    $userName->setDecorators($elementDecorators);
    $userName->setLabel('User Name');
    

    或者,您也可以在现有装饰器上显式设置后缀/前缀:

    $userName->getDecorator('Label')->setReqSuffix(' *');
    $userName->getDecorator('Label')->setOptSuffix('(Optional) ');
    

    【讨论】:

      【解决方案2】:

      由于 Label 装饰器将 CSS 类 required 添加到附加到根据需要指定的表单输入元素的 <label> 元素中,我已经能够使用 CSS :after 添加符号(如星号)带有content() 声明的选择器:

      label.required:after {
          content: "*";
      }
      

      但是,我发现设置正确的间距、让星号以粗体或我想要的颜色呈现等可能很棘手。因此,我经常回退到使用 CSS 来呈现标签本身以粗体或其他颜色显示,然后在表单的顶部或底部添加一个图例(“需要粗体/红色字段”或类似的)(通常通过创建我自己的自定义图例装饰器,但有时在视图中-脚本本身)。

      【讨论】:

        【解决方案3】:
        class FormDecorators {
            public static $simpleElementDecorators = array(
                array('ViewHelper'),
                array('Label', array('tag' => 'span', 'escape' => false, 'requiredPrefix' => '<span class="required">* </span>')),
                array('Description', array('tag' => 'div', 'class' => 'desc-item')),
                array('Errors', array('class' => 'errors')),
                array('HtmlTag', array('tag' => 'div', 'class' => 'form-item'))
            );
            }
        

        对于你使用的元素

         $elem->setDecorators(FormDecorators::$simpleElementDecorators)
        

        我在标签数组中添加了带有“requiredPrefix”参数的必需前缀。

        array('Label', array('tag' => 'span', 'escape' => false, 'requiredPrefix' => '<span class="required">* </span>')),
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-08
          • 1970-01-01
          • 2015-08-08
          • 2021-05-31
          • 1970-01-01
          • 2014-09-10
          相关资源
          最近更新 更多