-1

i'm try to add a new row to a table of my database by using CakePhp framework, but something it's not work properly. This is my add.ctp

echo $this->Form->create(array('type' => 'get'));
echo $this->Form->input('username');
echo $this->Form->input('password');

echo $this->Form->end('Save');

This is controller add function:

public function add() {
    if ($this->request->is('get')) {
        $this->Admin->create();
        if ($this->Admin->save($this->request->data)) {
            debug("done");
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
    }
}

and this is my Admin Model class:

class Admin extends AppModel {
    public $validate = array(
        'username' => array(
        'rule' => 'notEmpty'
    ),
    'password' => array(
        'rule' => 'notEmpty'
    )
);

but new row is never added to my Admins table. Database works fine (i can retrieve all rows inside table). I'm working on localhost with xampp

giozh
  • 9,868
  • 30
  • 102
  • 183
  • 1
    I think your form should be of type `post` – Yerko Palma Feb 20 '15 at 15:16
  • Ok, it works, but why? Framework admit only POST method for save something on database? – giozh Feb 20 '15 at 15:19
  • I must admite that I've never used a from of type `get` before, some I am not sure. Have you debugged your values? I mean `$this->request->data` because in post type forms I use `$this->data`. I don't know what else could be. – Yerko Palma Feb 20 '15 at 15:23
  • Why a _post_? Because your form _posts_ the data. Did you examine the HTML generated by that view? FYI: Cakephp can handle _posts_ and _gets_. – AgRizzo Feb 20 '15 at 15:33
  • @giozh its because cake handles data with post and get requests diffrently check my answer below – scx Feb 20 '15 at 15:55
  • If you would like use GET Method, it should be $this->request->query instead $this->request->data. – Mumtaz Ahmad Feb 20 '15 at 20:58

1 Answers1

1

Its not working because your $this->request->data is not populated with information you sent with your request. Simply CakePHP handles post and get differently.

All POST data can be accessed using CakeRequest::$data.

If for some unknown reason you want to send your password with form using 'get' you can access it like this

$data['username'] = $this->params['url']['username'];
$data['password'] = $this->params['url']['password'];

Also please take a look at this 'when do you use post, when do you use get'

Community
  • 1
  • 1
scx
  • 2,749
  • 2
  • 25
  • 39
  • i know when to use post and when to use get. In this case i've try to use GET intentionally for test purpose (i've try to pass params directly like /admin/add?username=myusername&password=mypassword) – giozh Feb 20 '15 at 16:09