【问题标题】:How to add custom CSS class to required input label?如何将自定义 CSS 类添加到所需的输入标签?
【发布时间】:2015-08-17 12:43:08
【问题描述】:

我想在我的 required 输入字段之前的标签中添加一个 CSS 类。我可以通过 JavaScript 完成,但我想在 CakePHP 中完成。

是否有一些选项可以告诉 CakePHP 自动执行?

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:

    对于一个input,您可以这样做:

    $this->Form->input('myfield', [
        'label' => [
            'text' => 'My Field', 
            'class' => 'my-label-class'
        ]
    ]);
    

    如果您需要将其添加到所有必需输入,您可以改为创建自己的FormHelper

    App::import('Helper', 'Form') ;
    
    class MyFormHelper extends FormHelper {
    
        protected function _inputLabel($fieldName, $label, $options) {
            // Extract the required option from the $options array.
            $required = $this->_extractOption('required', $options, false)
              || $this->_introspectModel($this->model(), 'validates', $fieldName);
    
            // If the input is required, first force the array version for $label,
            // then add the custom class.
            if ($required) {
                if (!is_array($label)) {
                    $label = array('text' => $label) ;
                }
                $label = $this->addClass($label, 'my-label-class') ;
            }
    
            // Then simply call the parent function.
            return parent::_inputLabel($fieldName, $label, $options) ;
        }
    
    }
    

    然后在你的控制器中:

    public $helpers = array(
        'Form' => array('className' => 'MyForm')
    );
    

    请参阅FormHelper.php 了解有关_introspectModel 的信息,基本上:

    $this->_introspectModel ($model, 'validates', $fieldName)
    

    ...如果$fieldNameModel::validates 数组中的必填字段,则将返回true

    【讨论】:

    • @user1315357 您想将类添加到FormHelper生成的每个标签?
    • @user1315357 您使用的是 CakePHP 2 还是 CakePHP 3?
    • 我仍然使用 CakePHP 2.7.3
    • @user1315357 查看我的编辑,我认为在 CakePHP 2 中没有更短的方法来做你想做的事。
    • @user1315357 抱歉,我看错了你的问题。请参阅我的更新答案。
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    相关资源
    最近更新 更多