0

I'm using CakePHP _serialize function to API response output.

In case of some validation error on model is returned message which describes error in JSON output.

Code is like this:

$status = 'NOK';
            $errors = $this->User->validationErrors;
            // SET RESPONSE TO OUTPUT
            $this->set(array(
                'status' => $status,
                'message' => $errors,
                '_serialize' => array('status','message')
            ));

It produces this JSON:

{
"status": "NOK",
"message": {
    "email": [
        "Email already exists"
    ],
    "username": [
        "Username already exists"
    ]
}

}

Problem is, that messages should be simple array with error strings (because user cannot access to errors via key names), it means, something like this:

   {
    "status": "NOK",
    "message": [
            "Email already exists",
            "Username already exists"
        ]
    }

Question is:

How can i simple solve that in CakePHP or pure PHP?

Thanks for any help or advice.

redrom
  • 11,502
  • 31
  • 157
  • 264

2 Answers2

1

Use array_values:

$this->set(array(
    'status' => $status,
    'message' => array_values($errors),
    '_serialize' => array('status','message')
));
Holt
  • 36,600
  • 7
  • 92
  • 139
0

Try using Hash::extract

$errors = Hash::extract($this->User->validationErrors, '{s}.{n}');

Gives the following JSON:

["Email already exists", "Username already exists"]