【发布时间】:2015-08-17 12:43:08
【问题描述】:
我想在我的 required 输入字段之前的标签中添加一个 CSS 类。我可以通过 JavaScript 完成,但我想在 CakePHP 中完成。
是否有一些选项可以告诉 CakePHP 自动执行?
【问题讨论】:
标签: cakephp cakephp-2.0
我想在我的 required 输入字段之前的标签中添加一个 CSS 类。我可以通过 JavaScript 完成,但我想在 CakePHP 中完成。
是否有一些选项可以告诉 CakePHP 自动执行?
【问题讨论】:
标签: cakephp cakephp-2.0
对于一个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)
...如果$fieldName 是Model::validates 数组中的必填字段,则将返回true。
【讨论】:
FormHelper生成的每个标签?