我正在尝试使用load
记录edit
,save
和CakePHP 2.0
,但是在generic error
方法期间我收到了save
,但没有帮助我了解问题出在哪里。
如果我尝试使用debug($this->User->invalidFields());
,我会得到一个empty array
,但是我会从false
条件中得到$this->User->save()
。
这是我收到错误的 Controller 操作:
public function activate ($code = false) {
if (!empty ($code)) {
// if I printr $user I get the right user
$user = $this->User->find('first', array('activation_key' => $code));
if (!empty($user)) {
$this->User->set(array (
'activation_key' => null,
'active' => 1
));
if ($this->User->save()) {
$this->render('activation_successful');
} else {
// I get this error
$this->set('status', 'Save error message');
$this->set('user_data', $user);
$this->render('activation_fail');
}
debug($this->User->invalidFields());
} else {
$this->set('status', 'Account not found for this key');
$this->render('activation_fail');
}
} else {
$this->set('status', 'Empty key');
$this->render('activation_fail');
}
}
当我尝试操作
test.com/users/activate/hashedkey
时,我得到带有activation_fail
消息的Save error message
模板页面。如果我对
printr
进行$user
编码,则可以从cake的find
方法中找到合适的用户。我哪里错了?
最佳答案
我认为问题可能出在您查询用户记录的方式上。执行此操作时:
$user = $this->User->find('first', array('activation_key' => $code));
变量
$user
填充有用户记录作为数组。您检查以确保它不为空,然后继续;但是问题是没有填充$this->User
。我认为如果您尝试debug($this->User->id)
,它将为空。 read() method按照您的思维方式工作。您可以尝试使用
$user
数组中的ID来首先设置Model ID,如下所示:if (!empty($user)) {
$this->User->id = $user['User']['id']; // ensure the Model has the ID to use
$this->User->set(array (
'activation_key' => null,
'active' => 1
));
if ($this->User->save()) {
...
编辑:另外一种可能的方法是使用
$user
数组而不是修改当前模型。您说如果您使用debug($user)
可以找回一个有效的用户,所以如果是这样,您可以执行以下操作:if (!empty($user)) {
$user['User']['activation_key'] = null;
$user['User']['active'] = 1;
if ($this->User->save($user)) {
...
此方法的工作方式与从
$this->request->data
接收表单数据的方式相同,并在本书的Saving Your Data部分中进行了介绍。我很好奇,但是是否还有其他设置妨碍了您的设置。应用程序的其他部分能否正确写入数据库?您还应该检查以确保没有验证错误,例如其示例:
<?php
if ($this->Recipe->save($this->request->data)) {
// handle the success.
}
debug($this->Recipe->validationErrors);
关于error-handling - 用cakephp保存数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100803/