cakephp output data as json - cakephp

I am new to cakephp and i am trying to create a simple rest api that deals with vehicles. I want to out my data that i get from mysql database in json format.
This is my controller
class VehiclesController extends AppController {
var $name = 'Vehicles';
var $layout = 'default';
function index() {
$this->set('vehicles', $this->Vehicle->find('all'));
$this->set('title_for_layout','Home');
}
}
How would i out the content as json in a view?

Create a view here Views/Vehicles/json/index.ctp.
In your view you should be able to use:
<?php echo json_encode($vehicles); ?>
To output the JSON
You can then access it on this url : /vehicles/index.json

Related

Passing JSON from controller to view in codeigniter

I made an API call and received the response in JSON format.
JSON:
{
"Specialities": [
{
"SpecialityID": 1,
"SpecialityName": "Eye Doctor"
},
{
"SpecialityID": 2,
"SpecialityName": "Chiropractor"
},
{
"SpecialityID": 3,
"SpecialityName": "Primary Care Doctor"
}
]
}
Controller File:
public function index(){
$data= json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
}
Above code doesn't work because in view I can't access the nested object properties. However I am able to echo the JSON properties in controller file just like this:
Controller File:
public function index(){
$data=json_decode(file_get_contents('some_url'));
foreach ($data as $key=>$prop_name){
for($i=0;$i < count($prop_name);$i++){
echo $prop_name[$i]->SpecialityID;
echo $prop_name[$i]->SpecialityName;
}
}
}
My question is how do I pass this JSON to view and how can I access those properties in view file?
In controller changes like
public function index(){
$data['json_data']= json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
}
and in the view
echo "<pre>";print_r($json_data);
As per Docs
Data is passed from the controller to the view by way of an array or
an object in the second parameter of the view loading method.
Here is an example using an array:
So you need to change your code in controller
Controller.php
$data = array();
$data['myJson'] = json_decode(file_get_contents('some_url'));
$this->load->view('my_view',$data);
my_view.php
<html>
....
<?php
//Access them like so
print_r($myJson);
// Rest of your code here to play with json
?>
....
</html>

retrieve single record with kohana 3.3 with request->param() is NULL

i try to use kohana framework but i have a little issue wen i try to retrieve a single record from table of my database.
my table:
ads
id_ads
title_ads
description_ads
my controller:
public function action_single()
{
$ads_id = $this->request->param('id_ads');
$ads = ORM::factory('ads', $ads_id);
$view = new View('ads/single'); // load the view/ads/single.php
$view->set('ads', $ads); // set 'ads' object to view
$this->template->set('content', $view);
}
my view
<h2><?php echo $ads->title_ads; ?></h2>
<pre><?php echo $ads->description_ads; ?></pre>
when i go to to localhost/kohana/index.php/ads/single/1 the browser display nothing, where is the problem?
try this:
$ads_id = $this->request->param('id_ads');
$ads =ORM::factory('ads'->find($ads_id);
or
$ads_id = $this->request->param('id_ads');
$ads =ORM::factory('ads')->where("id","=",$ads_id)->find();
to pass parameters, i think, is better (easier) to extend Controller_Template
in this way:
class Controller_News extends Controller_Template{
...
public function action_single()
{
...
$view->ads=$ads;
$this->template->content = $view;
}
}

Json does not popup as download file in cakephp 2.3

I am using cakephp 2.3 and want to generate list of users in json format.
controller name: users
method: list
Earlier, I have done it in cake 1.3.x and when user tries access method via url in browser then output comes as download file but when i am doing it in cakephp 2.3 then it is showing me json output on browser page itself instead of download file.
here is my code:
Controller:
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $helpers = array('Form', 'Html', 'Js', 'Time');
public $components = array('RequestHandler');
var $layout = 'js/default';
public function list() {
$this->log("i got data in user add:");
$this->log($this->request->data);
$posts['id']['name']='kapil';
$this->set(compact('posts'));
}
}
list.ctp file
<?php echo json_encode(compact('posts')); ?>
view/js/default.ctp
<?php echo $scripts_for_layout; ?>
<?php echo $this->fetch('content'); ?>
when i try to access my function in browser then i get this output
url: http://localhost/project/users/list
{"posts":{"id":{"name":"aditya"}}}
This output is correct but should come in download file format. I don't know what is wrong here.
If you are trying to force download, your code must make use of Response object.
Here is an example taken from CsvExport Behavior:
public function export() {
$this->autoRender = false;
$modelClass = $this->modelClass;
$this->response->type('Content-Type: text/csv');
$this->response->download( strtolower( Inflector::pluralize( $modelClass ) ) . '.csv' );
$this->response->body( $this->$modelClass->exportCSV() );
}
So your code would look like this :
public function list() {
$this->autoRender = false;
$this->log("i got data in user add:");
$this->log($this->request->data);
$posts['id']['name']='kapil';
$this->set(compact('posts'));
$modelClass = $this->modelClass;
$this->response->type('Content-Type: application/json');
$this->response->download('list.json');
}
Hope this helps!

One model to many controllers - CakePHP

Im trying to load one appmodel to many controllers. For example i have appmodel called Item and i want to get some items in HomeController and ContactController. When i execute this code:
class HomeController extends AppController {
public function index() {
$items = $this->Item->find('all');
$this->set('items', $items);
}
}
I got this error:
Call to a member function find() on a non-object
How can i get thing from database in many views in CakePHP?
you need to declare which model you want to use in your controller.
class HomesController extends AppController {
var $uses = array('Item', 'AnotherModel');
...
}
var $uses=array('Item');
If using this model in multiple controllers, put this in app controller.

How to name a controller file for uppercase table in cakephp

Hye. I want to make a controller and model for a table which is named in uppercase and abbreviation.
For example, the table name is PS_DEPT_TBL
1) What would be the controller file name? Is it PSDEPTTBL_controller.php? The code below seems to be not working for the controller.
class PSDEPTTBLController extends AppController {
var $uses = 'PS_DEPT_TBL';
var $scaffold ;
}
2) I name the model file as PSDEPTTBL.php and code it as below.
class PSDEPTTBL extends AppModel {
var $useTable = 'PS_DEPT_TBL';
}
But the error shows that there isn't any controller of the table. I'm new to cakephp. Help me.
There is no need for your controller to be called the same as your table. The same goes for your model.
How about something this:
// ThingsController.php
class ThingsController extends AppController
{
var $uses = array('Thing');
}
// Thing.php
class Thing extends AppModel
{
var $useTable = 'PS_DEPT_TBL';
}
// Config/routes.php
Router::connect(
'/PSDEPTTBL/:action/*', array('controller' => 'things')
);
The key idea here is to make your code readable. If you have a legacy database, the best thing you can do for yourself is to hide it all in all the models.

Resources