Search code examples
phpcakephpform-helpers

Insert additional data beyond that is from the helper


If I have this form:

form--- username email password

And I also need to insert an unique ID that is generated.

This code will save the username, email and password in the DB. My question is about the codeLink.

$user_arr = $this->request->data;
$this->User->save($user_arr)

There is another (easy) way, or I should do something like this?

$username = $user_arr['User']['username'];
$email = $user_arr['User']['email'];
$password = $user_arr['User']['password'];
$codeLink = uniqid();

$user_arr = array('User'=>array('username'=>$username, 'email'=>$email, 'password'=>$password, '$code'=>$codeLink));

Solution

  • You can inject the values into the post data before you pass it to the model like so:

    $this->request->data['User']['codeLink'] = unqueid(); // <-- this line
    $this->User->create($this->request->data);
    if ($this->User->save()) {
    } else {
    }
    

    Things of this sort should be moved to the model, though.

    class User extends AppModel {
    
        public function register($data) {
            $data[$this->alias]['codeLink'] = uniqueid();
            $this->create($data);
            return $this->save();
        }
    
    }
    
    // your controller
    
    if ($this->User->register($this->request->data) {}...