Tag Archives: cakephp

Send Form data with ajax to cakephp controller

23666The following example shows how to submit a form with AJAX to a Cakephp controller;

Jquery Javascript Funtion;

	/*
	sends the form to the controller, ensure form fields names match up 
	with escpected values.
	*/
	function testajaxaddv3(){		
		jQuery.ajax({
			type:'POST',
			async: true,
			cache: false,
			url: 'http://localhost/mycakeapp/messages/ajaxadd',
			success: function(response) {					
				//success
				console.log(response);                
			},
			error: function(response) {					
				console.log(response);
			},
			data:jQuery('form').serialize()
		});
	}

CakePHP 3 Form:

<?= $this->Form->create(null) ?>
<fieldset>
<legend><?= __('Add Quizzes Answer') ?></legend>
<?php
echo $this->Form->input('message');
?>
</fieldset>

<?= $this->Form->end() ?>
</div>

<?php
echo $this->Form->button('save',['onclick'=>'testajaxaddv3()']);
?>

 

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 

Cakephp Tips – Sort Data With the Pagnator Component

If you wanted to sort a Model by a certain field in this case take the field “created” which is a date. We can simply tell cakePHP to pagnate entries by the order they were created by the following example.

	public function index() {
		
		// we prepare our query, the cakephp way!
		$this->paginate = array(
			'limit' => 20,
			'order' => array('created' => 'desc')
		);
		
		
		$this->Link->recursive = 0;		
		$this->set('links', $this->Paginator->paginate());
	}

More Examples can be found here;
https://www.codeofaninja.com/2013/07/pagination-in-cakephp.html

Cakephp 2.0 Tip# 14 File Uploads

cake-logo

Firstly you need to install the Plugin;
https://github.com/josegonzalez/cakephp-upload

In the Model of the object you want to allow uploads to(eg User,Product) add;

Model

public $actsAs = array(
        'Upload.Upload' => array(
            'picture'
        )
);

View:

In the View Form of this action add;

Form->create('User', array('type' => 'file')); ?>
Form->input('picture',array('type' => 'file','accept'=>'image/*')); ?>
Form->end(__('Submit')); ?>

CakePhp 2 Tip #11- Force SSL Connection

cake-logo

In your app Controller add;

class AppController extends AppController {

    public $components = array('Security');

    public function beforeFilter() {
        if (isset($this->params['admin'])) {
            $this->Security->blackHoleCallback = 'forceSSL';
            $this->Security->requireSecure();
        }
    }

    public function forceSSL() {
        return $this->redirect('https://' . env('SERVER_NAME') . $this->here);
    }
}

More info:
http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html

CakePhp 2 Tip#8-Checking User Ownership

cake-logo

Another common task in Cakephp Applications or any Web Application is making sure that a user can only delete items they own otherwise anyone could erase your entire database.

An example you have created a users table and users can create posts, but we need to ensure that User A can only edit and delete posts belonging to them.

Solution: The isAuthorized() function.
This function will check that the user isAuthorized to do what ever action they are about to under take.

Assuming every posts has a user_id as a foreign key, we can check the current logged in user’s Id against the id stored in the post their about to modify and if they match allow and if not deny.

// app/Controller/PostsController.php

public function isAuthorized($user) {
    // All registered users can add posts
    if ($this->action === 'add') {
        return true;
    }

    // The owner of a post can edit and delete it
    if (in_array($this->action, array('edit', 'delete'))) {
        $postId = (int) $this->request->params['pass'][0];
        if ($this->Post->isOwnedBy($postId, $user['id'])) {
            return true;
        }
    }

    return parent::isAuthorized($user);
}
// app/Model/Post.php
public function isOwnedBy($post, $user) {
    return $this->field('id', array('id' => $post, 'user_id' => $user)) !== false;
}

Entire User Auth Solution and Guide:
https://github.com/cakephp/docs/blob/master/en/tutorials-and-examples/blog-auth-example/auth.rst