2

I am using cakephp. I have a form with an element array. For ex:-

<textarea name="data[User][0][description]>
<textarea name="data[User][1][description]>

From the controller, I need to invalidate (manually) the array field if it is empty and need to show errors to the respective field. What is the correct syntax for invalidating the field if it an element array ? I know, the following will work for single element . How it will be for an element array ?

$this->User->invalidate("description");
user470077
  • 23
  • 1
  • 4

4 Answers4

4

You can type in view:

<?php 
    echo $this->Form->error("User.1.description");
?>
Julia
  • 41
  • 1
4

Unfortunately you cannot invalidate the field with that function.

But what invalidate() does?

function invalidate($field, $value = true) {
        if (!is_array($this->validationErrors)) {
            $this->validationErrors = array();
        }
        $this->validationErrors[$field] = $value;
    }

It just set validationErrors of the model.

So, you can do following in your Controller (but I also appeal you to move that validation in the Model):

$this->User->validationErrors[1]['description'] = 'Your error message';

The following code will invalidate the second description in the list.

HTH

Nik Chankov
  • 6,049
  • 1
  • 20
  • 30
0

Thanks Nik,

your answer helped me, but halfway, because my problem was with a compound field by other subfields.

account_number {
    bank_code, 
    bank_office,
    check_digit,
    account
}

In this case if we need put in validation error in one subfield, this is the solution:

$this->Model->validationErrors['account_number']['bank_code'][0] = 'Your message error';

I hope this help someone.

Regards.

Adexe Rivera
  • 414
  • 7
  • 12
0

I had similar problem, since it was for admin panel I showed error message on the first level of field i.e. for this portion only.

If you are validation on controller, just create an array of error with field name and error message, set it in controller and display message if in_array($field, $withErrorArray) in view.

ritesh khadka
  • 152
  • 2
  • 13