passwordFieldRow1 - 当前密码
passwordFieldRow2 - 新密码
passwordFieldRow3 - 重复新密码
尽可能使用模型进行验证。
如:
密码错误,不匹配新密码并重复新密码
**My model**
<?php
class User extends CActiveRecord
{
public $totalVolunteer;
public $totalAlumni;
public $currentPass;
public $newPass;
public $repNewPass;
public function behaviors()
{
return array(
'LoggableBehavior'=>
'application.modules.auditTrail.behaviors.LoggableBehavior',
);
}
public $uploadedFile;
public function getRoles()
{
return array('encoder'=>'Encoder','admin'=>'Admin','alumni'=>'Alumni','volunteer'=>'volunteer');
}
public function getVolunteerName()
{
return $this->user_fname.' '.$this->user_mname.'. '.$this->user_lname;
}
public function getAlumniName()
{
return $this->user_fname.' '.$this->user_mname.'. '.$this->user_lname;
}
public function getFullName()
{
return $this->user_fname . ' ' . $this->user_mname.'. '.$this->user_lname;
}
public function getName()
{
return $this->user_lname . ', ' . $this->user_fname.' '.$this->user_mname.'.';
}
public function getGenderOptions(){
return array('male'=>'Male','female'=>'Female');
}
public function getMaritalStatus(){
return array('single'=>'Single','married'=>'Married','widowed'=>'Widowed','separated'=>'Separated','annuled'=>'Annuled');
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'user';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('username, password, roles, user_fname, user_lname, user_mname, user_gender, user_birthdate, user_marital_status, user_address1, user_mobile, user_email', 'required'),
array('username, password, user_fname, user_lname', 'length', 'max'=>45),
array('user_photo','file','types'=>'jpg, gif, png, bmp, jpeg,JPG',
'maxSize'=>1024 * 1024 * 10, // 10MB
'tooLarge'=>'The file was larger than 10MB. Please upload a smaller file.',
'allowEmpty' => true),
array('roles', 'length', 'max'=>11),
array('user_mname', 'length', 'max'=>4),
array('user_gender', 'length', 'max'=>7),
array('currentPass,newPass,repNewPass','required'),
//validator
array('username', 'unique','message'=>"{attribute} already exists"),
array('password','ext.SPasswordValidator'),
//array('user_fname','ext.alpha',),
//array('user_lname','ext.alpha',),
//array('user_mname','ext.alpha',),
array('user_mname,user_lname,user_fname','match' ,'pattern'=>'/^[A-Za-z_]+$/u','message'=>"{attribute} contains not allowed characters"),
array('user_email','email',),
/*array('user_mobile','numerical','integerOnly'=>true,'min'=>12,'max'=>12,'tooSmall'=>'mobile should contain 12 numbers','tooBig'=>'mobile cannot contain more than 12 numbers'),*/
/*array('user_email', 'email','message'=>"Please enter a valid email"),
array('user_email', 'unique','message'=>'Email already exists!'), */
/*array('username', 'unique','message'=>'username already exists!'),*/
array('user_marital_status, user_landline', 'length', 'max'=>10),
array('user_address1, user_address2', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, user_fname, user_lname, user_mname', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'alumnis' => array(self::HAS_MANY, 'Alumni', 'user_id'),
'batchHistories' => array(self::HAS_MANY, 'BatchHistory', 'user_id'),
'donations' => array(self::HAS_MANY, 'Donation', 'user_id'),
'volunteers' => array(self::HAS_MANY, 'Volunteer', 'user_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'username' => 'Username',
'password' => 'Password',
'roles' => 'Roles',
'user_fname' => 'Firstname',
'user_lname' => 'Lastname',
'user_mname' => 'Middlename',
'user_gender' => 'Sex',
'user_birthdate' => 'Birthdate',
'user_marital_status' => 'Marital Status',
'user_address1' => 'Address1',
'user_address2' => 'Address2',
'user_mobile' => 'Mobile',
'user_landline' => 'Landline',
'currentPass' => 'Current Password',
'newPass' => 'New Password',
'repNewPass' => 'Repeat New Password',
'user_email' => 'Email',
'user_photo' => 'Photo',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('username',$this->username,true);
$criteria->compare('password',$this->password,true);
$criteria->compare('user_fname',$this->user_fname,true);
$criteria->compare('user_lname',$this->user_lname,true);
$criteria->compare('user_mname',$this->user_mname,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public function Total(){
return VolunteerCount()+AlumniCount();
}
public function VolunteerCount(){
$criteria = new CDbCriteria;
$criteria->select='COUNT(*) as totalVolunteer';
$criteria->condition='roles = :searchTxt';
$criteria->params=array(':searchTxt'=>'volunteer');
$user = User::model()->find($criteria);
return $user->totalVolunteer;
}
public function AlumniCount(){
$criteria = new CDbCriteria;
$criteria->select='COUNT(*) as totalAlumni';
$criteria->condition='roles = :searchTxt';
$criteria->params=array(':searchTxt'=>'alumni');
$user = User::model()->find($criteria);
return $user->totalAlumni;
}
}
我的表单
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id' => 'user-form',
'type' => 'horizontal',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
//'htmlOptions' => array('enableClientValidation'=>true),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->passwordFieldRow($model,'currentPass',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->passwordFieldRow($model,'newPass',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->passwordFieldRow($model,'repNewPass',array('size'=>45,'maxlength'=>45)); ?>
<div class="row">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit','type'=>'info','label'=>'create','icon'=>'ok-circle white')); ?>
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'reset', 'label'=>'cancel','icon'=>'remove-circle')); ?>
</div>
<?php $this->endWidget(); ?>
UserController中:
public function actionUpdate($ id) { $模型= $这 - &GT; loadModel($ ID); $用户= $这 - &GT; loadUser($模型 - &GT; ID);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
$user->attributes=$_POST['User'];
$uploadedFile = CUploadedFile::getInstance($model, 'user_photo');
$rnd = rand(0123456789, 9876543210);
$fileName = "{$rnd}-{$uploadedFile}";
$user->user_photo = $fileName;
/*--password hashing--*/
if($user->validate()){
$salt = openssl_random_pseudo_bytes(22);
$salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
$password_hash = crypt($model->password, $salt);
$model->password = $password_hash;
}
$fileName = "{$rnd}-{$uploadedFile}";
if (!empty($uploadedFile)) $model->user_photo = $fileName;
if($model->save()){
if (!empty($uploadedFile))
{
$uploadedFile->saveAs(Yii::app()->basePath.'/../files/images/'.$fileName); // save images in given destination folder
}
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
**Codes for Update Password in UserController:**
public function actionUpdatePassword($id){
$model=$this->loadModel($id);
$user=$this->loadUser($model->id);
//echo $user->password;
if(isset($_POST['currentPass']) && isset($_POST['newPass']) && isset($_POST['repNewPass'])){
$user = User::model()->findByPk(Yii::app()->user->id);
$salt = openssl_random_pseudo_bytes(22);
$salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
$password_hash = crypt($_POST['currentPass'], $salt);
if($password_hash === $user->password){
if($_POST['newPass'] == $_POST['repNewPass']){
$user->password =crypt($_POST['newPass'], $salt);
$user->save();
$this->redirect(array('view','id'=>$model->id));
}
}
}
$this->render('updatePassword',array(
'model'=>$model,));
}
答案 0 :(得分:0)
我有办法做到这一点
<强>表格强>
/** Form **/
class PasswordForm extends CModel
{
public $password;
public $repeat_password;
public function rules()
{
return array(
array('repeat_password', 'compare', 'compareAttribute' => 'password', 'message' => Y::t('Passwods not matching')),
array('password', 'required'),
array('repeat_password', 'required', 'message' => Y::t('Repeat password')),
);
}
.....
<强>控制器强>
$model = new PasswordForm;
$model->attributes = $_POST['PasswordForm'];
$model->save();
在Model中为此操作添加单独的场景,并在beforeSave中检查场景并保存新密码。
答案 1 :(得分:0)
使用Yii Framework中的TbActiveForm更改密码 -
在您的模型中(用户模型)
//Define public variable
public $old_password;
public $new_password;
public $repeat_password;
//Define the rules for old_password, new_password and repeat_password with changePwd Scenario.
public function rules()
{
return array(
array('old_password, new_password, repeat_password', 'required', 'on' => 'changePwd'),
array('old_password', 'findPasswords', 'on' => 'changePwd'),
array('repeat_password', 'compare', 'compareAttribute'=>'new_password', 'on'=>'changePwd'),
);
}
//matching the old password with your existing password.
public function findPasswords($attribute, $params)
{
$user = User::model()->findByPk(Yii::app()->user->id);
if ($user->password != md5($this->old_password))
$this->addError($attribute, 'Old password is incorrect.');
}
在你的控制器/行动中
public function actionChangepassword($id)
{
$model = new User;
$model = User::model()->findByAttributes(array('id'=>$id));
$model->setScenario('changePwd');
if(isset($_POST['User'])){
$model->attributes = $_POST['User'];
$valid = $model->validate();
if($valid){
$model->password = md5($model->new_password);
if($model->save())
$this->redirect(array('changepassword','msg'=>'successfully changed password'));
else
$this->redirect(array('changepassword','msg'=>'password not changed'));
}
}
$this->render('changepassword',array('model'=>$model));
}
在您的视图文件(changepassword.php)
<div class="form">
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id' => 'chnage-password-form',
'enableClientValidation' => true,
'htmlOptions' => array('class' => 'well'),
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<div class="row"> <?php echo $form->labelEx($model,'old_password'); ?> <?php echo $form->passwordField($model,'old_password'); ?> <?php echo $form->error($model,'old_password'); ?> </div>
<div class="row"> <?php echo $form->labelEx($model,'new_password'); ?> <?php echo $form->passwordField($model,'new_password'); ?> <?php echo $form->error($model,'new_password'); ?> </div>
<div class="row"> <?php echo $form->labelEx($model,'repeat_password'); ?> <?php echo $form->passwordField($model,'repeat_password'); ?> <?php echo $form->error($model,'repeat_password'); ?> </div>
<div class="row submit">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType' => 'submit', 'type' => 'primary', 'label' => 'Change password')); ?>
</div>
<?php $this->endWidget(); ?>
</div>
为了获得最佳帮助,您可以在yii框架上关注我的wiki文章 - Change password in Yii