Let's say I have field that looks like this in the view:
<li class="bigfield">
<?php echo $form->input('phone', array(
'placeholder' => 'Phone',
'label' => false,
'between' => '<br />'
)); ?>
</li>
If I have a validation rule on this field and validation fails, I see the following HTML:
<li class="bigfield">
<div class="input text required error">
<br>
<input name="data[Appointment][email]" type="text" placeholder="Email"
maxlength="45" value="" id="AppointmentEmail" class="form-error">
<div class="error-message">Please enter a valid email address</div>
</div>
</li>
I'm like to do something like move the error message div to an entire different part of the page rather then have it inside with the same <li> as the field itself. What would be the most straight forward way of doing this?
Just updating an old post.
The validations errors are automatically passed on to view (as pointed out by @Angel S. Moreno)
$this->validationErrors
In you controller:
$this->set('validationErrorsArray', $this->ModelName->invalidFields());
You will have $validationErrorsArray
in your views.
UPDATE (Sept. 2014):
From the view
From CakePHP 2.3 you can access validation errors array from the view:
$this->validationErrors;
From the controller
If you tried to save data in the controller you can access validation errors this way:
$this->ModelName->validationErrors;
If you want to validate data before saving do it this way:
$this->ModelName->set($this->request->data);
if ($this->ModelName->validates()) {
$this->ModelName->save();
} else {
$errors = $this->ModelName->validationErrors;
// handle errors
}
Validating Data from the Controller
From controller you can use:
$this->Modelname->validationErrors['TheFieldYouWantToDisplay'] = 'This is not correct'
In your case it would be like this in your controller:
$this->Appointment->validationErrors['email'] = 'Error message'
This code is just to make a custom error message on the fly. But you can also define $validate in the model and do it like how brancer has described it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With