Update a Record in CakePHP

Mister R2 picture Mister R2 · Mar 19, 2013 · Viewed 12.1k times · Source

So I'm learning CakePHP, and I'm trying to just build a bunch of basic applications I can build in straight PHP to learn how CakePHP works. Right now I'm working on a basic Order Management System -- Users can have multiple Orders and Orders belong to a User.

I have the database set up and CakePHP is configured correctly (the starting page shows all green for each topic such as default timezone and database connection, with the exception of the DebugKit which I have not installed). I also have a "List of Users" page:

enter image description here

The problem I'm running into, as you can actually see in the above screenshot, is when I'm trying to edit an existing User on /users/edit_user:

enter image description here

I'm trying to save the edits for the user, and I (1) use $this->Form->hidden(...) for the ID and (2) set the primary key to the table's primary key in the Model with public $primaryKey = 'ID';

Every time I try to do this, it simply inserts a new record instead of updating the existing record, and I thought the problem would be fixed by identifying my PK and by adding the ID to be submitted, but I must be missing something.

Here's the code for the involved pages:

Model

<?php
/**
 * app/Model/User.php
 *
 */
class User extends AppModel
{
    public $name = 'User';
    public $primaryKey = 'ID';

    // <hasMany>
    public $hasMany = array(
                            'Order' => array('dependent' => true)
                        );
}

?>

Controller

<?php
/**
 * app/Controller/UsersController.php
 *
 */
class UsersController extends AppController
{
    //public $scaffold;

    /* Validation */
    public $validate = array(
            'username' => array(
                    'required' => true,
                    'allowEmpty' => false,
                    'loginRule1' => array(
                        'rule' => 'alphaNumeric',
                        'message' => "Usernames must be alphanumeric!"
                                        ),
                    'loginRule2' => array(
                        'rule' => array('minLength', 4),
                        'message' => 'Usernames must be at least 4 characters.'
                                        ),
                                ),
            'password' => array(
                    'required' => true,
                    'allowEmpty' => false,
                    'passwordRule1' => array(
                        'rule' => array('minLength', 4),
                        'message' => 'Passwords must be between 4 and 8 characters.'
                                            ),
                    'passwordRule2' => array(
                        'rule' => array('maxLength', 8),
                        'message' => 'Passwords must be between 4 and 8 characters.'
                                            )
                                )
            );


    /* Actions */

    public function index()
    {
        // Grab all users
        $users = $this->User->find('all');

        // Set/Send users to View
        $this->set('users', $users);
    }

    public function new_user()
    {
        /* Has any Form data been POST'd? */
        if ($this->request->is('post'))
        {
            // Save User data to the DB
            $this->User->save($this->request->data);

            $this->redirect('/users');
        }
    }

    /*
        Accessing Args:
            (1) Direct URL Routing Method
                --> ...
            (2) Named Params Method
                --> CakeRequest['named']['[name]']
    */
    public function edit_user($id = null)
    {
        $id = $this->request['named']['currentID'];

        // Display the current data of the user
        if (!empty($id))
        {
            $userInfo = $this->User->find('all', 
                    array('conditions' => array('User.ID' => $id)));

            $this->set('userData', $userInfo);
        }
        else
            $this->set('error', '$id is empty!');

        /* Has any Form data been POST'd? */
        if ($this->request->is('post'))
        {
            // Save User data to the DB
            $this->User->save($this->request->data);

            $this->redirect('/users');
        }
    }
}

?>

View/Users/edit_user.ctp

<div class="row-fluid">

    <div class-"span12"></div>
    <div class="span12"></div>

    <div class="span8 offset2">

        <?php
            echo "Hidden ID Field Value: " . $userData[0]['User']['ID'];
            echo "<hr>";



            echo $this->Form->create('User');
            echo $this->Form->input('username');
                echo "  Current Name: " . 
                    $userData[0]['User']['username'];
            echo $this->Form->input('password');
                echo "  Current password: " . 
                    $userData[0]['User']['password'];

            // Hidden ID field to make save ~ an UDATE
            echo $this->Form->hidden('User', 
                    array('ID' => $userData[0]['User']['ID'],
                            'type' => 'hidden'));

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

        ?>
    </div>

</div>

Does anyone see what I'm not doing that will allow me to edit / UPDATE an existing record instead of INSERT a brand new one? Thanks for your time!

Answer

summea picture summea · Mar 19, 2013

The problem probably has to do with the type of Form element being used here; I would suggest trying something like this in your /View/Users/edit_user.ctp file:

// Hidden ID field to make save an UPDATE
echo $this->Form->input('id', array('type' => 'hidden'));

More information about saving edits can be found in the CakePHP blog tutorial.