Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display CakePHP input validation errors in a different spot the default?

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?

like image 957
Nick Messick Avatar asked Jun 07 '10 19:06

Nick Messick


3 Answers

Just updating an old post.

The validations errors are automatically passed on to view (as pointed out by @Angel S. Moreno)

$this->validationErrors 
like image 100
Kishor Kundan Avatar answered Oct 24 '22 08:10

Kishor Kundan


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

like image 42
bancer Avatar answered Oct 24 '22 07:10

bancer


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.

like image 4
shaw kwok Avatar answered Oct 24 '22 07:10

shaw kwok