开发者

How can I save an automatically generated password in CakePHP?

I am trying to automatically register users. You enter an email address and it sends the user a password. Sounds simple enough, right? Here are a bunch of things that I've tried in my add action, but none of them work (as indicated).

if (!empty($this->data)) {
    $this->User->create();

    $random_pass = $this->Auth->password($this->generatePassword());

    // Doesn't work:
    $user_data['User'] = $this->data['User'];
    $user_data['User']['password'] = $random_pass;
    if ($this->User->save($user_data)) { /* ... */ }

    // Doesn't work:
    $this->User->set('password', $random_pass);
    if ($this->User->save($this->data)) { /* ... */ }

    // Doesn't work:
    $this->data['User']['password'] = $random_pass;
    if ($this->User->save($this->data)) { /* ...开发者_Go百科 */ }

    // Doesn't work:
    $this->data['User'][0]['password'] = $random_pass; 
    if ($this->User->saveAll($this->data)) { /* ... */ }

}

According to Why is the CakePHP password field is empty when trying to access it using $this->data? it's because the Auth component is removing the password. Seems common enough, no? So how do I get around it?

More information

I'm using this function to generate the password. The add view only has three fields, first_name, last_name, and email (which is assigned to the username field in the Auth component).


first of all.. you can do

$random_pass = $this->Auth->password($this->generatePassword());
pr($random_pass);

to make sure there is actually data in that variable...

then you can save that data with...

$this->data['User']['password'] = $random_pass;
$this->User->save($this->data);

Also keep in mind that... during your testing you have if (!empty($this->data)) so make sure you are actually testing by entering some form of default data somewhere in your form.


Maybe you've got some validation rules defined in your User model that are not satisfied? You can try to check this by printing $this->validationErrors (or just check your User model to see if there are any rules).


JohnP answered this question in the comments. I had some junk in the beforeSave action. Removed and now it's working perfectly. Thanks again JohnP!


I am using Cake PHP 2.3.3 and following code works for me

public function recover()
{
  if ($this->request->is('post') )
  {
    $this->loadModel('AclManagement.User');
    $passwords = AuthComponent::password($this->data['User']['password']);
    $this->User->query("UPDATE users SET password = '".$passwords."' WHERE password_change = '".$this->request->data['User']['id']."' ");
    $this->Session->setFlash(__('Password Saved Sucessfully'), 'success');
    $this->redirect(array('action' => 'login'));
  } else {
    $this->set('resettoken', $_REQUEST['id']);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜