本文整理汇总了PHP中User::getErrors方法的典型用法代码示例。如果您正苦于以下问题:PHP User::getErrors方法的具体用法?PHP User::getErrors怎么用?PHP User::getErrors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类User
的用法示例。
在下文中一共展示了User::getErrors方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testBasic
public function testBasic()
{
$user = new \User(array('name' => ' Alex', 'email' => 'invalid-email'));
$this->assertFalse($user->save(), 'Save result is false for invalid email');
$this->assertArrayHasKey('email', $user->getErrors(), 'Has an email error');
$this->assertArrayHasKey('name', $user->getErrors(), 'Has error on name');
$this->assertEquals(array('invalid name'), $user->getErrors('name'), 'Custom error description works');
$user->name = 'Alexandr Viniychuk ';
$user->email = 'a@viniychuk.com';
$this->assertTrue($user->save(), 'Saving correct values');
$this->assertEquals('Alexandr Viniychuk', $user->name, 'Trim process rule worked');
}
示例2: createUser
private function createUser($login)
{
$model = new User();
$tmpname = array();
preg_match('/^([^\\s]+)\\s*(.*)?$/', $this->service->getAttribute('name'), $tmpname);
//разделение имени по запчастям
//$newUser->firstname = $tmpname[1];
//$newUser->lastname = $tmpname[2];
$model->login = $login;
$model->username = $this->service->getAttribute('username');
$model->avatar = $this->service->getAttribute('photo_small');
$model->timezone = $this->service->getAttribute('timezone');
$model->gender = $this->service->getAttribute('gender');
$model->service = $this->service->serviceName;
$model->subscribe = 0;
$model->active = true;
$model->last_login = date('Y-m-d H:i:s');
$model->date_registration = date('Y-m-d H:i:s');
if ($model->validate()) {
$model->save(false, false);
} else {
print_r($model->getErrors());
die;
}
return $model;
}
示例3: testEmailUniquenessValidation
public function testEmailUniquenessValidation()
{
$user = User::getByUsername('super');
Yii::app()->user->userModel = $user;
$user = new User();
$user->username = 'usera';
$user->lastName = 'UserA';
$user->setPassword('myuser');
$emailAddress = 'userA@example.com';
$user->primaryEmail->emailAddress = $emailAddress;
$saved = $user->save();
$this->assertTrue($saved);
$user2 = new User();
$user2->username = 'userb';
$user2->lastName = 'UserB';
$user2->setPassword('myuser');
$emailAddress = 'userA@example.com';
$user2->primaryEmail->emailAddress = $emailAddress;
$saved = $user2->save();
$this->assertFalse($saved);
$validationErrors = $user2->getErrors();
$this->assertTrue(count($validationErrors) > 0);
// Todo: fix array keys below
$this->assertTrue(isset($validationErrors['primaryEmail']));
$this->assertTrue(isset($validationErrors['primaryEmail']['emailAddress']));
$this->assertEquals('Email address already exists in system.', $validationErrors['primaryEmail']['emailAddress'][0]);
// Try to save user without email address
$user3 = new User();
$user3->username = 'userc';
$user3->lastName = 'UserC';
$user3->setPassword('myuser');
$saved = $user3->save();
$this->assertTrue($saved);
}
示例4: actionCreate
/**
* 创建卡牌库
* @author gentle
*/
public function actionCreate()
{
$model = new User();
if (isset($_POST['User'])) {
//admin管理员不能手动添加
if ($_POST['User']['username'] == 'admin') {
$this->redirect_back();
exit;
}
//添加默认密码
if ($_POST['User']['password'] == '') {
$_POST['User']['password'] = Yii::app()->params['def_password'];
}
//接收范围权限并预处理
$_POST['User']['scope'] = User::model()->makeScope();
$_POST['User']['password'] = md5($_POST['User']['password']);
$model->attributes = $_POST['User'];
if ($model->save()) {
$this->addLog('user', $model->id, '添加了名为“' . $model->username . '”的“' . Yii::app()->params["role"][$model->role]["name"] . '”');
Yii::app()->user->setFlash("success", "新建 <b>{$model->username}</b> 用户成功!");
} else {
$errorMsg = '';
$errorErr = $model->getErrors();
foreach ($errorErr as $value) {
$errorMsg .= "\t" . $value[0];
}
$errorMsg = trim($errorMsg, ',');
Yii::app()->user->setFlash("error", $errorMsg);
}
$this->redirect(array('user/index'));
}
$yxlist = User::model()->getScope();
$this->renderPartial('_form', array('model' => $model, 'yxlist' => $yxlist));
}
示例5: run
public function run()
{
$form = new RegistrationForm();
if (Yii::app()->request->isPostRequest && !empty($_POST['RegistrationForm'])) {
$module = Yii::app()->getModule('user');
$form->setAttributes($_POST['RegistrationForm']);
// проверка по "черным спискам"
// проверить на email
if (!$module->isAllowedEmail($form->email)) {
// перенаправить на экшн для фиксации невалидных email-адресов
$this->controller->redirect(array(Yii::app()->getModule('user')->invalidEmailAction));
}
if (!$module->isAllowedIp(Yii::app()->request->userHostAddress)) {
// перенаправить на экшн для фиксации невалидных ip-адресов
$this->controller->redirect(array(Yii::app()->getModule('user')->invalidIpAction));
}
if ($form->validate()) {
// если требуется активация по email
if ($module->emailAccountVerification) {
$registration = new Registration();
// скопируем данные формы
$registration->setAttributes($form->getAttributes());
if ($registration->save()) {
// отправка email с просьбой активировать аккаунт
$mailBody = $this->controller->renderPartial('application.modules.user.views.email.needAccountActivationEmail', array('model' => $registration), true);
Yii::app()->mail->send($module->notifyEmailFrom, $registration->email, Yii::t('user', 'Регистрация на сайте {site} !', array('{site}' => Yii::app()->name)), $mailBody);
// запись в лог о создании учетной записи
Yii::log(Yii::t('user', "Создана учетная запись {nick_name}!", array('{nick_name}' => $registration->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory);
Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Учетная запись создана! Инструкции по активации аккаунта отправлены Вам на email!'));
$this->controller->refresh();
} else {
$form->addErrors($registration->getErrors());
Yii::log(Yii::t('user', "Ошибка при создании учетной записи!"), CLogger::LEVEL_ERROR, UserModule::$logCategory);
}
} else {
// если активации не требуется - сразу создаем аккаунт
$user = new User();
$user->createAccount($form->nick_name, $form->email, $form->password);
if ($user && !$user->hasErrors()) {
Yii::log(Yii::t('user', "Создана учетная запись {nick_name} без активации!", array('{nick_name}' => $user->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory);
// отправить email с сообщением о успешной регистрации
$emailBody = $this->controller->renderPartial('application.modules.user.views.email.accountCreatedEmail', array('model' => $user), true);
Yii::app()->mail->send($module->notifyEmailFrom, $user->email, Yii::t('user', 'Регистрация на сайте {site} !', array('{site}' => Yii::app()->name)), $emailBody);
Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Учетная запись создана! Пожалуйста, авторизуйтесь!'));
$this->controller->redirect(array('/user/account/login/'));
} else {
$form->addErrors($user->getErrors());
Yii::log(Yii::t('user', "Ошибка при создании учетной записи без активации!"), CLogger::LEVEL_ERROR, UserModule::$logCategory);
}
}
}
}
$this->controller->render('registration', array('model' => $form));
}
示例6: save
public function save()
{
$app = Yii::app();
$transaction = $app->db->beginTransaction();
try {
if ($this->validate() == false) {
throw new CDbException('参数出错', 0, []);
}
preg_match('/^(.*)@/', $this->username, $match);
$password = CPasswordHelper::hashPassword($this->password);
$result = Fraudmetrix::register($this->username, $this->username, $password);
if ($result['success'] == true && $result['final_decision'] == 'Reject') {
throw new CDbException('注册用户失败', 100, []);
}
$user = new User();
$user->attributes = ['username' => $this->username, 'realname' => isset($match[1]) ? $match[1] : '无', 'nickname' => isset($match[1]) ? $match[1] : '无', 'email' => $this->username, 'password' => $password, 'sign_up_time' => time(), 'sign_up_ip' => Yii::app()->request->getUserHostAddress(), 'approved' => 5, 'state' => 0];
if ($user->save() === false) {
throw new CDbException('注册用户失败', 10, $user->getErrors());
}
$user->uuid = $app->getSecurityManager()->generateUUID($user->id . $user->password);
if ($user->save() === false) {
throw new CDbException('注册用户失败', 10, $user->getErrors());
}
//写入service
$service = new Service();
$service->attributes = ['uid' => $user->id, 'email' => $user->username, 'status' => 1, 'traffic' => 100 * 100];
if ($service->save()) {
Queue::apiCreate($user->id);
}
$transaction->commit();
} catch (CDbException $e) {
$transaction->rollback();
$this->addErrors($e->errorInfo);
return false;
}
$email = $app->getComponent('email');
if (!empty($email)) {
$email->quickSend($this->username, '欢迎您注册夸父', "请妥善保管好您的登录密码:" . $this->password);
}
return true;
}
示例7: actionForm
public function actionForm()
{
$model = new User();
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
if ($model->save()) {
$this->redirect('./index.php?r=user');
} else {
$model->getErrors();
}
}
$this->render('form', array('model' => $model));
}
示例8: returnOrRenderView
protected function returnOrRenderView(User $model, $view)
{
if ($this->isAjax()) {
// Flatten errors
$errors = array();
foreach ($model->getErrors() as $attribute => $att_errors) {
$errors = array_merge($errors, $att_errors);
}
echo CJSON::encode(array('result' => -1, 'message' => $model->hasErrors() ? $errors[0] : "No data"));
Yii::app()->end();
} else {
$this->getController()->render($view, array('model' => $model));
}
}
示例9: actionIndex
public function actionIndex()
{
$user = new User();
if (!empty($_POST['User'])) {
$user->attributes = $_POST['User'];
if ($user->save()) {
Yii::app()->user->login(UserIdentity::createAuthenticatedIdentity($user->username, $user->id), 0);
echo json_encode(array('errors' => ''));
} else {
$errors = $user->getErrors();
echo json_encode(array('errors' => $errors));
}
exit;
}
$this->render('index', array('model' => $user));
}
示例10: register
public function register()
{
$this->username = htmlspecialchars(strip_tags($this->username));
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->password = $this->password;
if ($user->save()) {
return true;
} else {
// print_r($user->getErrors());
$this->_errors += $user->getErrors();
return false;
}
}
return false;
}
示例11: register
public function register($params = array())
{
extract($params);
if (isset($nickname) && isset($password) && isset($mobile)) {
$cache = Yii::app()->cache;
$save_code = strtolower($cache->hget($mobile, 'register'));
if (isset($code) && $save_code == strtolower($code)) {
//查询手机是否注册过
$user = User::model()->exists(array('condition' => 'mobile=:mobile', 'params' => array(':mobile' => isset($mobile) ? $mobile : 0)));
if (!$user) {
Yii::import("application.extensions.Emchat.*");
$h = new Easemob();
if (isset($mobile) && $mobile) {
$ur_name = 'ur_' . $mobile;
$pwd = isset($password) ? $password : '123456';
$res = $h->createUser($ur_name, $pwd);
}
$result = array('nickname' => $nickname, 'sex' => isset($sex) ? $sex : 0, 'mobile' => isset($mobile) ? $mobile : 0, 'image' => isset($image) ? $image : '', 'password' => md5($mobile . md5($password)));
if ($uuid = $res['entities'][0]['uuid']) {
$result['uuid'] = $uuid;
}
$model = new User();
$model->attributes = $result;
if ($model->validate() && $model->save()) {
$id = $model->getPrimaryKey();
$res = array('id' => $id, 'nickname' => $nickname, 'uuid' => $uuid);
$ret = $this->notice('OK', 0, '成功', $res);
} else {
$ret = $this->notice('ERR', 307, '', $model->getErrors());
}
} else {
$ret = $this->notice('ERR', 306, '该号码已经注册过了', []);
}
} else {
$ret = $this->notice('ERR', 305, '验证码错误', ['code' => $code, 'save_code' => $save_code]);
}
} else {
$ret = $this->notice('ERR', 307, '', []);
}
$result = array('password' => $params['password']);
$ret = $this->notice('ERR', 307, '', $result);
return $ret;
}
示例12: actionCreate
public function actionCreate()
{
$data = CJSON::decode(file_get_contents('php://input'));
$model = new User();
$model->fname = $data['fname'];
$model->lname = $data['lname'];
$model->email = $data['email'];
$model->username = $data['username'];
$model->password = $data['password'];
$model->role = $data['role'];
if (!$model->save()) {
$errors = array();
foreach ($model->getErrors() as $e) {
$errors = array_merge($errors, $e);
}
$this->sendResponse(500, implode("<br />", $errors));
}
$model = User::model()->noPassword()->findByPk($model->id);
$this->sendResponse(200, CJSON::encode($model));
}
示例13: store
public function store()
{
$user = new User();
// populate the model with the form data
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
if (!$user->save()) {
$errors = $user->getErrors();
return Redirect::action('UsersController@create')->with('errors', $errors)->withInput();
}
// success!
// Mail::send('emailTemplate', array('firstname'=>Input::get('first_name')), function($message){
// $message->to(Input::get('email'), Input::get('firstname').' '.Input::get('lastname'))->subject('Welcome to Airtalk!');
// });
$email = Input::get('email');
$password = Input::get('password');
Auth::attempt(array('email' => $email, 'password' => $password));
return Redirect::action('UsersController@index', Auth::id())->with('message', 'Account with email of ' . $user->email . ' has been created!');
}
示例14: actionAdd
/**
* Lists all models.
*/
public function actionAdd()
{
$model = new User();
$model->setScenario('add');
$errores = array();
// If form is submitted and data is correct...
// collect user input data
if (isset($_POST['User'])) {
$_POST['User']['role'] = Yii::app()->params['subAdminRole'];
$model->attributes = $_POST['User'];
// validate user input and redirect to the previous page if valid
if ($model->validate()) {
$model->save();
$this->redirect(array('post/index'));
} else {
$errores = $model->getErrors();
}
}
// else, show the form again
$this->render('add', ['model' => $model]);
}
示例15: process
public function process()
{
$this->validate();
if (!$this->hasErrors()) {
$user = new User();
$user->username = $this->username;
$user->password = $this->password;
if (!$user->save()) {
foreach ($user->getErrors() as $errors) {
foreach ($errors as $field => $message) {
if (in_array($field, $this->attributes)) {
$this->addError($field, $message);
}
}
}
return false;
}
return true;
}
return false;
}