php - cakephp edit action and requests?
So can someone explain this to me? I'm trying to write an edit action and am a bit unsure of why the following does not work:
public function edit($id = null) {
if (!$id) {
throw new NotFoundException('NO ID HAS BEEN SUPPLIED');
}
$data = $this->User->findById($id);
if(!$this->request->is('post')) { $this->request->data = $data; }
if($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id;
$this->User->save($this->request->data);
$this->redirect(array('action'=>'index'));
}
}
And by not working, I mean, that while it does pre-populate the form with data gathered from findById($id).. it doesn't update the database with the new inputs after the form has been sent.
I have replaced this:
if(!$this->request->is('post'))
With the following:
if($this->request->is('get'))
And suddenly, it works fine. It updates the row with the new values gathered from the post. However, I do not understand what's happening here. Why is it that !$this->request->is('post), does NOT work, while $this->request->is('get') DOES work? Surely, when the action is first called it is called using a GET request? Doesn't that request qualify as !$this->request->is('post')?
EDIT:
below is the ctp: app/View/Users/edit.ctp
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('edit User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role');
// echo $this->Form->input('role', array(
// 'options' => array('admin' => 'Admin', 'regular' => 'Regular')
//));//
?>
</fieldset> <?php echo $this->Form->end(__('Submit')); ?>
Answer
Solution:
By default Cake uses 'PUT' method for 'edit' action and 'POST' for 'add'. so you need to check
$this->request->isPut()
(or$this->request->is('put')
). Look for a hiiden field *_method* that automatically generated by$this->Form->create()
method in your view.If 'id' property is set in data passed to view Cake creates 'edit' form and 'add' if no 'id'.
Answer
Solution:
Do it this way
passing id to edit from url is not safe way...
$this->params['id']
will have your post id so with it$this->request->is('put')
will work.