cakephp form validation success class/message
-
02-07-2021 - |
문제
I'm using cakePHP with its default model validation. On error cake add the class "error" to my container div. Great! But what about if everything is entered correctly but one form element? I would like the inputs that are correct to receive the class "success" (and maybe a message or icon telling my user how awesome they are).
Here is my form create code:
echo $this->Form->create('User',
array(
'class' => 'form-horizontal',
'inputDefaults' =>
array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'control-group'),
'label' => array('class' => 'control-label'),
'between' => 'div class="controls">',
'after' => '/div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
)
)
);
해결책
What I ended up doing was copy /lib/Cake/View/HelperFormHelper.php
to /app/View/Helper/FormHelper.php
. I then modified /app/View/Helper/FormHelper.php around line 1028 (on my copy, it's the end of the 'input' function) so that it looks like this:
1028:
if ($this->_introspectModel($modelKey, 'validates', $fieldKey)) {
$divOptions = $this->addClass($divOptions, 'required');
}
if($this->request->is('post')) {
if(!$this->isFieldError($modelKey.'.'.$fieldKey)) {
// This is the important line.
$divOptions = $this->addClass($divOptions, 'success');
}
}
if (!isset($divOptions['tag'])) {
$divOptions['tag'] = 'div';
}
}//end input function
다른 팁
Don't know if it's the cleanest way, but it would work.
I would add the following lines to my View, checking if the request is a POST. All the fields with the class 'control-group' would adopt the new style.
if($this->request->is('post')){
echo '<style type="text/css">div.control-group { background-color:#000; }</style>';
}
As you don't wan't to show the new style in the fields that use class 'error', just put !important after the style rules at the CSS file revoking the change.
Example 'style.css':
error {
background-color: none !important;
}