CakePHP - 如何将自己的CSS类添加到所需的输入标签?

Art*_*gon 1 cakephp cakephp-2.0

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

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

Hol*_*olt 6

首先input,你可以这样做:

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

如果您需要将其添加到所有必需的输入,您可以创建自己的输入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) ;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

public $helpers = array(
    'Form' => array('className' => 'MyForm')
);
Run Code Online (Sandbox Code Playgroud)

有关信息,请参阅FormHelper.php,如果是数组中的必填字段_introspectModel,则基本上true将返回.$fieldNameModel::validatesinput