Reputation: 3608
I would like to add a CSS class to labels which are before my required inputs field. I can do it via JavaScript but I would like to do it in CakePHP.
Is there some options to tell CakePHP to do it automatically?
Upvotes: 1
Views: 5307
Reputation: 37606
For one input
, you can simply do this:
$this->Form->input('myfield', [
'label' => [
'text' => 'My Field',
'class' => 'my-label-class'
]
]);
If you need to add it to all required inputs, you could instead create your own 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) ;
}
}
And then in your controller:
public $helpers = array(
'Form' => array('className' => 'MyForm')
);
See FormHelper.php for informtion about _introspectModel
, basically:
$this->_introspectModel ($model, 'validates', $fieldName)
...will return true
if $fieldName
is a required field in your Model::validates
array.
Upvotes: 6