Php 如何使用我的控制器、型号和_表单创建更改密码

Php 如何使用我的控制器、型号和_表单创建更改密码,php,yii,Php,Yii,passwordFieldRow1-当前密码 passwordFieldRow2-新密码 passwordFieldRow3-重复新密码 如果可能,使用模型进行验证 例如: 密码不正确,与新密码不匹配,请重复新密码 **My model** <?php class User extends CActiveRecord { public $totalVolunteer; public $totalAlumni; p

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(); ?>
/** 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();

在模型中为此操作添加单独的方案,并在保存和保存新密码之前检查方案。

在Yii Framework中使用TbActiveForm更改密码-

在您的模型中(用户模型)


在控制器/操作中

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)





要获得最佳帮助,请阅读我在yii framework上的wiki文章-

控制器代码在哪里?你试过什么?你现在得到了什么?如果我提交当前通行证、新通行证和重新键入新通行证的数据,什么都不会发生。没有指向$this->redirect(数组('view','id'=>$model->id))。。密码没有改变。
//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)); 
 }
<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>