Issue
I am trying to pass JSON into an Add() action of my controller but the response I get is either a response from the Index() action or "null" depending on entries in my routes.php (shown below).
I'm using Firefox plugin RESTClient to test/pass json to my actions:
Method: POST
URL: http://MyApp/notes.json (my understanding is this should call Add action based on cakephp docs )
JSON:
{
"post_id":"123",
"note":"hello world"
}
When I have the following in my routes.php, the response is "null"
Router::scope('/', function ($routes) {
$routes->extensions(['json']);
$routes->resources('Notes');
Removing $routes->resources('Notes');
from this scope returns a response from the index action and all items in the Notes model are returned in the response.
Furthermore, when I implement this through Crud.Add in an api prefix, I get valid results. That being said trying to understand what I have incorrect in my routes.php or add action that could be causing the null or routing to index action.
Add Action:
public function add()
{
$note = $this->Notes->newEntity();
if ($this->request->is('post')) {
$note = $this->Notes->patchEntity($note, $this->request->data);
if ($this->Notes->save($note)) {
$message = 'Saved';
} else {
$message = 'Error';
}
}
$this->set('_serialize', ['note', 'message']);
}
Routes.php:
<?php
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::defaultRouteClass('DashedRoute');
Router::extensions(['json'], ['xml']);
Router::prefix('api',function($routes) {
$routes->extensions(['json','xml']);
$routes->resources('Notes');
});
Router::scope('/', function ($routes) {
$routes->extensions(['json']);
$routes->resources('Notes');
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
$routes->fallbacks('DashedRoute');
});
Plugin::routes();
Thanks in advance.
Solution
You didn't set any variables for the view, other than serialization options, so you get null
because there's nothing to serialize, ie you are missing something like
$this->set(compact('note', 'message'));
in your action.
And without the resource routes a request to /notes
maps to the index action of the Notes
controller, because that's how fallback routes are connected, no action = index action.
See also
- Cookbook > Views > JSON And XML Views > Using Data Views with the Serialize Key
- Cookbook > Routing > Fallbacks Method
Answered By - ndm
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.