[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 ...
Ruby on rail c'est marrant, ça c'est dit. Un des concepts de ce framework est de ne pas réinventer la roue (peut être est-ce une évidence?! Captain Obvious). Ce qui m'a ammené à tester
Après un retour aux sources de quelques jours, c'est à dire avec pour seule connexion un bon vieux modem bas-débit facturé au coût d'une communication locale, je me lance dans le langage Java.
Ouais verticale, verticale pas éxagerer non-plus, on se contente de ce qu'on a et c'est déjà pas mal, n'est-ce pas?!