我正在开发一个基于 Zend 框架的项目。在用户注册中,我必须检查唯一的电子邮件。当我第一次注册用户时,我的代码工作正常,但是当我尝试更新用户信息并按下更新按钮时,它会给出错误消息:
Email already taken
请帮我解决这个问题。我的代码附在下面:
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
array('Db_NoRecordExists', true, array(
'table' => 'users',
'field' => 'email',
'messages' => array(
'recordFound' => 'Email already taken'
)
)
)
)
));
我已将控制器更改为:
public function addAction()
{
$modelUsers = new Model_Users();
$userId = $this->_getParam('userId');
$form = $this->_getAddForm();
if ($userId) {
$populateData = array();
$user = $modelUsers->fetch($userId);
if ($user instanceof Model_User) {
$populateData = $user->toArray();
}
$form->populate($populateData);
}
$request = $this->getRequest();
if ($request->isPost()) {
$email = $this->getRequest()->getParam('email');
if (strtolower(trim($email)) == $modelUsers->fetchByEmail($email)) {
// change $this->_user->getAccount()->getEmail() to retrieve the user's current email address
// remove validator from form
$form->getElement('email')->removeValidator('Db_NoRecordExists');
}
$post = $request->getPost();
if ($form->isValid($post)) {
$values = $form->getValidValues($post);
$data = array(
'firstName' => $values['firstName'],
'userTypeId' => 2,
'lastName' => $values['lastName'],
'email' => $values['email'],
'userName' => $values['userName'],
'password' => $values['password'],
'role' => $values['role']
);
if ($userId) {
$user = $modelUsers->fetch($userId);
if ($user instanceof Model_User) {
$user->setFromArray($data);
$success = $user->save();
if ($success) {
echo Zend_Json::encode(array('status' => self::STATUS_SUCCESS, 'message' => 'Successfully updated the user!'));
exit;
}
}
} else {
$user = $modelUsers->createRow($data);
$success = $user->save();
if ($success) {
echo Zend_Json::encode(array('status' => self::STATUS_SUCCESS, 'message' => 'Successfully added the user!'));
exit;
}
}
echo Zend_Json::encode(array('status' => self::STATUS_FAILED, 'message' => 'user not added'));
exit;
} else {
$errors = array();
$errors = $form->errors();
echo Zend_Json::encode(array('status' => self::STATUS_ERROR, 'data' => $errors));
exit;
}
}
$this->view->form = $form;
$this->_helper->layout->disableLayout();
}
模型:
public function fetchByEmail($email)
{
$email=fetchOne('SELECT email FROM users WHERE email = $email');
//$select->where('email=?',$email) ;
//$student = $this->fetchRow($select);
return $email;
}
但这仍然行不通