Tag Archives: cakephp3

Cakephp3: sending json response message to view

23666Method1:

$this->response->body(json_encode($msg));
return $this->response;

Method2:

$this->set('msg', $msg);
$this->set('_serialize', ['msg']);

//controller action

public function test(){		
		
		$msg="this is a call";
		
                //method 1 (chose a method)
		$this->response->body(json_encode($msg));
		return $this->response;	
		
		//method 2
		$this->set('msg', $msg);
		$this->set('_serialize', ['msg']);		
		
}

//javascript function call in view
function delete_all(){
	jQuery.ajax({
			type:'POST',
			async: true,
			cache: false,
			url:'mycontroller/test.json',
			success: function(response){					
				//success
				console.log(response);  				
			},
			error: function(response){					
				console.log(response);
			}
		});
}

 

Cakephp3 Ajax data submission example

23666How to create a javascript function to send a AJAX request to your cakePHP controller action;

 

 

function testajaxadd(question_id,answerindex){ 

var mydata=new Object();
mydata.question_id=question_id;
mydata.answerindex=answerindex;

jQuery.ajax({
type:'POST',
async: true,
cache: false,
data: mydata,
url: 'http://localhost/myquiz/questions-answers/ajaxadd',
success: function(response) { 
//success
console.log(response); 
},
error: function(response) { 
console.log(response);
}
});
}

Cakephp controller action;

public function ajaxadd(){

$questionsAnswer = $this->QuestionsAnswers->newEntity(); 
if ($this->request->is('ajax')) {

$questionsAnswer = $this->QuestionsAnswers->patchEntity($questionsAnswer, $this->request->data);

// Added this line which makes the record belong to the logged in user
$questionsAnswer->user_id = $this->Auth->user('id');

if ($this->QuestionsAnswers->save($questionsAnswer)) {

$status['msg']="Saved Record"; 

} else {
$status['msg']="Error Saving Record"; 
}

//return the message to js function
$this->response->body(json_encode($status));
return $this->response; 
}
}

 

Fixing the Add action in your controller to save the user_id

23666One of the key things youll do with cakephp is to ensure that when your saving data that the user logged in owns thats you save their user_id as well.

the simpliest way to do this is with one line of code added to your add action;

Sample Code from a Controller called Joke;

public function add()
{
$joke = $this->Jokes->newEntity();
if ($this->request->is('post')) {

$joke = $this->Jokes->patchEntity($joke, $this->request->data); 

// Added this line, set the userid to the logged in user  $joke->user_id = $this->Auth->user('id');

if ($this->Jokes->save($joke)) {
$this->Flash->success(__('The joke has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The joke could not be saved. Please, try again.'));
}
}
$users = $this->Jokes->Users->find('list', ['limit' => 200]);
$jokescategories = $this->Jokes->Jokescategories->find('list', ['limit' => 200]);
$this->set(compact('joke', 'users', 'jokescategories'));
$this->set('_serialize', ['joke']);
}

 

Creating Plugins

23666Open up your command prompt in your app/bin folder;

enter the command;

//non vendor specified
cake bake plugin ContactManager 

//vendor specified 
cake bake plugin Gmcd/ContactManager

Baking the  controller for your plugin;

//no vendor

cake bake controller --plugin ContactManager Contacts

cake bake controller --plugin Gmcd/ContactManager Contacts

Baking the Model View and Controller:

cake bake all --plugin Gerrymcdonnell/jokes jokes

Read more here:
http://book.cakephp.org/3.0/en/plugins.html#creating-your-own-plugins

Cakephp3 make a field unique

23666To do this, simple open your table model file and add the following;

public function validationDefault(Validator $validator)
{

//the below code makes the field "title" validate as unique
$validator
->requirePresence('title', 'create')
->add('title', 'unique', ['rule' => 'validateUnique', 'provider' => 'table','message'=>'Error: Title already exists.'])
->notEmpty('title');

return $validator;
}

 Manual:
http://book.cakephp.org/3.0/en/core-libraries/validation.html

Cakephp3 How to pass a variable to an element

cake-logoSometimes its very handy to pass a variable to an Element in Cakephp3.

This allows you to customize the element if needed;
To do so simply;

in your view file;

echo $this->element('helpbox', [
    "helptext" => "Oh, this text is very helpful."
]);

What does it do?
This will load the element called “helpbox” and pass the value “Oh, this text is very helpful.” to the variable called “helptext” in the element.

CakePHP3 Book:
http://book.cakephp.org/3.0/en/views.html#passing-variables-into-an-element 

How to add REST features to your Cakephp 3 App

23666To add REST features to your CakePHP 3 you simply need to add two lines of code to your controller;

This will allow any action in the controller to be viewed as JSON or XML .

To view your action index as JSON simply;

http://localhost/mycakeapp/mycontroller/index.json

Rest Examples:
http://localhost/mycakeapp/mycontroller/view/1.json

http://localhost/mycakeapp/mycontroller/view/1.xml

 

public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}

 

Then in routes.php file /config/routes.php add;

Router::extensions(['json', 'xml']); //ensure this is before the below line.
Router::scope('/', function (RouteBuilder $routes) {

More info from the manual:
http://book.cakephp.org/3.0/en/development/routing.html#resource-routes