[cakephp]Link in post method – en

The problem :

CakePhp helpers does link only with GET method. Well It’s not the better way to delete a resource and it should be POST method.

How to

… make a hypertext link with POST method :

Then we should use javascript in order to create a form :
Delete

When the user confirm the action, this will create a form which will be sent to the application.

In CakePhp

The helper

The way I use, I create a custom helper which use the original html->link helper :
//file: app/views/helpers/html2.php
class Html2Helper extends Helper {
//this allow my helper to use the original one
var $helpers = array(‘Html’);

function link($title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true, $return = false) {
//add form with post method thanks to javascript only if confirmMessage present

if ($confirmMessage) {
$confirmMessage = str_replace("’", "\’", $confirmMessage);
$confirmMessage = str_replace(‘"’, ‘\"’, $confirmMessage);
//here we set our POST method
$htmlAttributes['onclick']="if (confirm(‘$confirmMessage’)) { var f = document.createElement(‘form’); f.style.display = ‘none’; this.parentNode.appendChild(f); f.method = ‘post’; f.action = this.href;f.submit(); };return false;";
}
//we use the link helper to finalized it
$output = $this->Html->link($title, $url, $htmlAttributes, null, $escapeTitle, $return);
return $this->output($output, $return);
}
}
?>

Use it : the view

You can insert into any view. Don’t forget to specified it in your controller. Confirm Message is required :

link(‘post link’, ‘/pages/index’, null, ‘Are you sure?’); ?>

The Controller

Specify the helper and check this:
//file: app/controller/pages_controller.php

class PagesController extends AppController {

var $name = ‘Posts’;
//hell yeah! the helper :
var $helpers = array(‘Html2′);
//check the request type :
var $components = array(‘RequestHandler’);

function index(){
//if the request use post method : return true
if($this->RequestHandler->isPost())
debug(‘request is post’);
else
debug(‘request is not post T_T’);
}
}
?>

Then …

Now you can modify those scripts to fit with RESTful app using PUT, DELETE …

This entry was posted in Cakephp. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>