how can I return the validation errors for a REST call?

2.1k Views Asked by At

I am making a REST api for my application. It almost works, but I want it to return the validation errors when they occurs.

With CakePHP 2.x I see there was an invalidFields method, but it's not there anymore with Cake3. I see, instead, that there is an errors method in the Form class, but I don't know how can I use it.

This is what I have in my Users/json/add.ctp file:

<?php
$echo = [
    'errors' => $this->Form->errors(),
    'user' => $user
];

echo json_encode($echo);

As I said it doesn't work (I know that probably Form is used out of its scope here, but I don't even know if I am on the right path)...

This is the result:

{
    "message": "Missing field name for FormHelper::errors",
    "url": "\/fatturazione\/api\/users.json",
    "code": 500
}

What is the correct way to display all the form errors when they occour?

1

There are 1 best solutions below

0
On BEST ANSWER

This is what I would do, check for validation-errors in your controller and send them to the view serialized

public function add() {
    $this->request->allowMethod('post');
    $data = $this->Model->newEntity($this->request->data);

    if($data->errors()) {
        $this->set([
            'errors' => $data->errors(), 
            '_serialize' => ['errors']]);
        return;
    }

     //if no validation errors then save here
}