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

How to add custom CSS class to required input label?

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

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

对于一个 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 for informtion about _introspectModel,基本上:

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

...将 return true 如果 $fieldName 是您的 Model::validates 数组中的必填字段。