如何将自定义CSS类添加到所需的输入标签?

问题描述 投票:1回答:1

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

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

cakephp cakephp-2.0
1个回答
6
投票

对于一个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')
);

有关qazxsw poi的信息,请参阅qazxsw poi,基本上:

FormHelper.php

...如果_introspectModel$this->_introspectModel ($model, 'validates', $fieldName) 数组中的必填字段,将返回true

© www.soinside.com 2019 - 2024. All rights reserved.