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!
Related
I am using cakephp 2.0.4 (Doing Changes in existing project)
My controller function is..
class PagesController extends AppController {
public function getlocations($string = ''){
$this->autoRender = false;
$aResult = array(0=>'Florida', 1=>'London');
echo json_encode($aResult);
}
}
And also I have try $this->autoLayout = $this->autoRender = false;
When I am calling this action directly in browser mysite/app/pages/getlocations it will give following error
View file "/home/mysite/public_html/testing/app/View/Pages/g.ctp" is missing.
Create a /View/Ajax/json.ctp view:
<?php
if(!empty($data)) echo json_encode($data);
Then in the action:
$this->set('data', array(0=>'Florida', 1=>'London'));
$this->layout = false;
$this->render('/Ajax/json');
You could also make it work following the Cake way.
First you have to add the following code to your routes file:
Router::parseExtensions('json');
Next, in the controller add the 'RequestHandler' to your components array and serialize your result in your getlocations function:
public $components = array('RequestHandler');
public function getlocations($string = ''){
$this->set('aResult', array(0=>'Florida', 1=>'London'));
$this->set('_serialize', 'aResult');
}
Finally, you can see the results in your browser mysite/app/pages/getlocations.json
Doing this way CakePHP will add the application/json headers automatically.
More info: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
So I started to play around with cakePHP after i did the blog tutorial (yes im new), and i would like to do something complicated. Like, theres a comment form, which is simple it contains Name and the Comment. And I would like to send the data to another application in the same host, which is save this comment in the DB. Currently the Comments/add.ctp saves it.
Thanks for any advice!
So theres the CommentsControll.php
<?php
class CommentsController extends AppController{
public $components = 'Session'
public function add(){
if($this->request->is('POST')){
$this->Comment->create();
if($this->Comment->save($this->request->data)){
$this->Session->setFlash('Your comment is saved!')
}
}
}
}
?>
And theres the Comments/add.ctp file
<?php
echo $this->Form->create('Comment');
echo $this->Form->input('name', array(
'label' => 'Your Name'
));
echo $this->Form->input('commenttext',array(
'label' => 'Your Comment'
));
echo $this->Form->end('Submit');
?>
Solution HttpSocket
CakePHP includes an HttpSocket class which can be used easily for making requests. It is a great way to communicate with external webservices, or remote apis.
// in your controller
App::uses('HttpSocket', 'Network/Http'); // This should be at the top of your Controller
class CommentsController extends AppController{
public $components = 'Session'
public function add(){
if($this->request->is('POST')){
$this->Comment->create();
$HttpSocket = new HttpSocket();
$response = $HttpSocket->post('http://example.com/add', $this->request->data));
// Get the status code for the response.
$code = $results->code;
if($code == 200) {
$this->Session->setFlash('Your comment is saved!');
} else {
$this->Session->setFlash('Opps! Somthing is wrong!');
}
}
}
}
Also see here CakePHP HttpSocket
EDIT:
I am getting the JSON results from the dropbox chooser, but they are not being parsed properly to be put into the database. I can't figure out what I am doing wrong, if I should be doing a JSON decoder in my controller or if it is something else.
Controller Code:
<?php class DropboxfilesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->File->create();
if ($this->File->save($this->request->data)) {
$this->Session->setFlash(__('Your file is now available :)'));
$this->redirect($this->referer());
} else {
$this->Session->setFlash(__('Something went wrong!'));
}
}
}}?>
View Code:
<?php echo $this->Form->create('File'); ?>
<input type="Dropboxfilechooser" name="selected-file" style="visibility: hidden;"/>
<?php echo $this->Form->end('Finish'); ?>
Model Code:
<?php class File extends AppModel {}?>
The actual problem is looking at the source code, the form action is not going to the proper controller, it is just going to the cake/homes. Just change that and the problem is solved.
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
I am new in cakephp. I wrote a validation ctpfile in cakephp 2.6.7 for viewing login and logout word but the validation doesn't work.
My code is:-
<?php
if (!$authUser) {
echo $this->element('logout-header');
} else {
echo $this->element('login-header');
}
?>
How can I write validation in ctp file for viewing login and logout word in my page header?
Why you wrote a validation ctp? put your validation rules in model
http://book.cakephp.org/2.0/en/models/data-validation.html
In your AppController's beforeRender() callback set the authUser view variable by retrieving the logged in user:-
public function beforeRender() {
parent::beforeRender();
$this->set('authUser', $this->Auth->user());
}
Then the view code in your question should work as expected.
I have a solution, which I regularly use when I worked in cakephp.
in AppController.php
class AppController extends Controller{
public function beforeFilter() {
parent::beforeFilter();
$userInfo = array();
if($this->Auth->user('_id')){
$userInfo['User'] = $this->Auth->user();
Configure::write($userInfo);
}
}
}
And after this in view .ctp file
<?php
$authUser = Configure::read('User');
if (!$authUser) {
echo $this->element('logout-header');
} else {
echo $this->element('login-header');
}
?>