Menus

Monday 18 September 2017

Yii2 change current user password


Yii2 user change own password


Yii2 framework generate password hashed format.


The following will hash the password. Do what you need with it:
  1. Yii::$app->security->generatePasswordHash($password);

This was taken from the setPassword() function in the advanced app. Source: yii2-app-advanced/User.php at master · yiisoft/yii2-app-advanced · GitHub



Steps

/backend/models/ChangePasswordForm.php

<?php
namespace backend\models;

use Yii;
use yii\base\InvalidParamException;
use yii\base\Model;
use common\models\User;

/**
 * Change password form for current user only
 */
class ChangePasswordForm extends Model
{
    public $id;
    public $password;
    public $confirm_password;

    /**
     * @var \common\models\User
     */
    private $_user;

    /**
     * Creates a form model given a token.
     *
     * @param  string                          $token
     * @param  array                           $config name-value pairs that will be used to initialize the object properties
     * @throws \yii\base\InvalidParamException if token is empty or not valid
     */
    public function __construct($id, $config = [])
    {
        $this->_user = User::findIdentity($id);
     
        if (!$this->_user) {
            throw new InvalidParamException('Unable to find user!');
        }
     
        $this->id = $this->_user->id;
        parent::__construct($config);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['password','confirm_password'], 'required'],
            [['password','confirm_password'], 'string', 'min' => 6],
            ['confirm_password', 'compare', 'compareAttribute' => 'password'],
        ];
    }

    /**
     * Changes password.
     *
     * @return boolean if password was changed.
     */
    public function changePassword()
    {
        $user = $this->_user;
        $user->setPassword($this->password);
        $user->password_encrypt= base64_encode($this->password);

        return $user->save(false);
    }
}



/backend/controllers/SiteController.php 


add this code


public function actionChangepassword()
    {
   
        $id = \Yii::$app->user->id;

       //user details..
        $user = $this->findModeluser($id);
     
        try {          
            $model = new \backend\models\ChangePasswordForm($id);
        } catch (InvalidParamException $e) {
            throw new \yii\web\BadRequestHttpException($e->getMessage());
        }

        if ($model->load(\Yii::$app->request->post()) && $model->validate() && $model->changePassword()) {
            \Yii::$app->session->setFlash('success', 'Password Changed!');
        }

        return $this->render('changePassword', [
            'model' => $model,
            'user' => $user,
        ]);
    }


/backend/views/site/changePassword.php

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

use yii\widgets\DetailView;

use backend\modules\tools\models\Center;
$user->subcenter=Center::getCenter($user->ccid);


$this->title = 'View or Change User Password';

$this->params['breadcrumbs'][] = $this->title;

?>
<div class="user-changePassword  box box-body table-responsive">

     <?= DetailView::widget([
        'model' => $user,
        'attributes' => [
            'id',
            'first_name',
            'subcenter',                                                                      
            'username',
            'email'
        ],
    ]) ?>
 
 
<div class="lb-box-header lb-with-border">
    <h4 class="lb-box-title"><span class="glyphicon glyphicon-user"></span> Change your password</h4>
</div>
<div class="box-body lb-bgcolor" style="padding: 20px 0px 0px 20px;">  
    <?php $form = ActiveForm::begin(); ?>

        <div class="row">
            <div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
                <?= Html::activeLabel($model, 'password') ?>          
            </div>
            <div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
                <?= $form->field($model, 'password')->passwordInput()->label(FALSE) ?>
            </div>        
        </div>
     
        <div class="row">
            <div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
                <?= Html::activeLabel($model, 'confirm_password') ?>          
            </div>
            <div class="col-xs-12 col-sm-6 col-lg-6 lb-div-width1">
                <?= $form->field($model, 'confirm_password')->passwordInput()->label(FALSE) ?>
            </div>        
        </div>

        <div class="form-group" align="center">
            <?= Html::submitButton('Change', ['class' => 'btn btn-primary']) ?>
        </div>
 
    <?php ActiveForm::end(); ?>  
</div>  
 

</div>

* Code used in frontend or backend.


Another method for use old password


ChangePasswordForm model like this include old password.

<?php 
    namespace app\models;
    
    use Yii;
    use yii\base\Model;
    use app\models\Login;
    
    class ChangePasswordForm extends Model{
        public $oldpass;
        public $newpass;
        public $repeatnewpass;
        
        public function rules(){
            return [
                [['oldpass','newpass','repeatnewpass'],'required'],
                ['oldpass','findPasswords'],
                ['repeatnewpass','compare','compareAttribute'=>'newpass'],
            ];
        }
        
        public function findPasswords($attribute, $params){
            $user = Login::find()->where([
                'username'=>Yii::$app->user->identity->username
            ])->one();
            $password = $user->password;
            if($password!=$this->oldpass)
                $this->addError($attribute,'Old password is incorrect');
        }
        
        public function attributeLabels(){
            return [
                'oldpass'=>'Old Password',
                'newpass'=>'New Password',
                'repeatnewpass'=>'Repeat New Password',
            ];
        }
    }


in add siteController

 public function actionChangepassword(){
        $model = new ChangePasswordForm;
        $modeluser = Login::find()->where([
            'username'=>Yii::$app->user->identity->username
        ])->one();
      
        if($model->load(Yii::$app->request->post())){
            if($model->validate()){
                try{
                    $modeluser->password = $_POST['PasswordForm']['newpass'];
                    if($modeluser->save()){
                        Yii::$app->getSession()->setFlash(
                            'success','Password changed'
                        );
                        return $this->redirect(['index']);
                    }else{
                        Yii::$app->getSession()->setFlash(
                            'error','Password not changed'
                        );
                        return $this->redirect(['index']);
                    }
                }catch(Exception $e){
                    Yii::$app->getSession()->setFlash(
                        'error',"{$e->getMessage()}"
                    );
                    return $this->render('changepassword',[
                        'model'=>$model
                    ]);
                }
            }else{
                return $this->render('changepassword',[
                    'model'=>$model
                ]);
            }
        }else{
            return $this->render('changepassword',[
                'model'=>$model
            ]);
        }
    }




Wednesday 6 September 2017

Yii2 Masked Input


Class yii\widgets\MaskedInput



MaskedInput generates a masked text input.
MaskedInput is similar to yii\helpers\Html::textInput() except that an input mask will be used to force users to enter properly formatted data, such as phone numbers, social security numbers.

Yii2 MaskedInput to collect phone numbers:

echo MaskedInput::widget([
    'name' => 'phone',
    'mask' => '999-999-9999',
]);
You can also use this widget in an yii\widgets\ActiveForm using the widget() method, for example like this:
<?= $form->field($model, 'from_date')->widget(\yii\widgets\MaskedInput::className(), [
    'mask' => '999-999-9999',
]) ?>

Demonstration and usage examples for the Yii 2.0 Masked Input widget


Masked input to collect date from users


More Masked Inputs

Code paste to your view
use yii\widgets\MaskedInput;


  1. echo MaskedInput::widget([
  2. 'name' => 'input-31',
  3. 'clientOptions' => ['alias' => 'date']
  4. ]);




Example

Masked date input use in active form.


<?= $form->field($model, 'date_of_birth')->widget(\yii\widgets\MaskedInput::className(), [
        'name' => 'input-31',
        'clientOptions' => ['alias' =>  'dd-mm-yyyy'],
        
]) ?>



Retype your date format in  'clientOptions' => ['alias' =>  'dd-mm-yyyy']


Masked  Amount input 

  1. echo MaskedInput::widget([
  2. 'name' => 'input-33',
  3. 'clientOptions' => [
  4. 'alias' => 'decimal',
  5. 'groupSeparator' => ',',
  6. 'autoGroup' => true
  7. ],
  8. ]);


Masked  URL input 

  1. echo MaskedInput::widget([
  2. 'name' => 'input-35',
  3. 'clientOptions' => [
  4. 'alias' => 'url',
  5. ],
  6. ]);


Masked  Email input 

  1. echo MaskedInput::widget([
  2. 'name' => 'input-36',
  3. 'clientOptions' => [
  4. 'alias' => 'email'
  5. ],
  6. ]);

Masked  Other Phone | US Phone input 


  1. echo MaskedInput::widget([
  2. 'name' => 'input-5',
  3. 'mask' => ['99-999-9999', '999-999-9999']
  4. ]);

More



Yii2 Bootstrap DatePicker Widget for Yii2

/yii2-date-picker-widget



Related Links

Yii Tabular Input



Monday 14 August 2017

PHP more useful functions




PHP strlen() Function

The strlen() function returns the length of a string.

Syntax

strlen(string)

Example

<?php
echo strlen("Hello world!");
?>

PHP substr() Function


Return part of a string


The substr() function returns a part of a string.

Syntax

substr(string,start,length)



ParameterDescription
stringRequired. Specifies the string to return a part of
startRequired. Specifies where to start in the string
  • A positive number - Start at a specified position in the string
  • A negative number - Start at a specified position from the end of the string
  • 0 - Start at the first character in string
lengthOptional. Specifies the length of the returned string. Default is to the end of the string.
  • A positive number - The length to be returned from the start parameter
  • Negative number - The length to be returned from the end of the string

Get first n characters of a string

Examples

echo substr("Hello world",0,4);
Output is print  "Hello"


$category_name=substr($cat['description'],3,  strlen($cat['description'])-1);


PHP fmod() Function


The fmod() function returns the remainder (modulo) of x/y.

Syntax

fmod(x,y);

             if(fmod($i, 2)==0){                  

                  //  Reminder is zero.
             
            }
            else{

                //  Reminder is one.

            }



Converting separate month, day and year values into a timestamp



using setDate funtion

<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>




Tuesday 8 August 2017

YII2 Useful Tips


Filter to force lowercase on all operations


Yii change case each word in a string and save model.


Yii2 change model case

['student_name', 'filter', 'filter'=>'strtolower'],

['student_name', 'filter', 'filter'=>'strtoupper'],

To convert to Lowercase or Uppercase 





Thursday 3 August 2017

Yii2 Transaction


Yii2 save related records in single save call in single transaction


Database Transaction in Yii


A transaction is used to run a group of operations in single process. When you we run multiple query in single process, It will be used. If you get any problem, It will not complete successfully and also rollback the executed query.


Transaction represents a DB transaction.
It is usually created by calling yii\db\Connection::beginTransaction().
The following code is a typical example of using transactions (note that some DBMS may not support transactions):
$transaction = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    //.... other SQL executions
    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
} catch (\Throwable $e) {
    $transaction->rollBack();
    throw $e;
}

Example

$transaction = Yii::$app->db->beginTransaction(); 

 try { 

 $user = new User(); 
 $user->name = 'Name'; 
 $user->save(); 

 $ua = new UserAddress(); 
 $ua->city = 'City'; 
 $user->link('userAddress', $ua); // <-- it creates new record in UserAddress table with ua.user_id = user.id 

 $transaction->commit(); 

 } catch (Exception $e) { 
 $transaction->rollBack(); 
 }


Example


if ($model->load(Yii::$app->request->post()))
        {
         
           $transaction = \Yii::$app->db->beginTransaction();
           try {  
         
         
            $stockitem=Stockitem::find()->where(['id'=>$model->stockitem_id])->one();
            $stockitem->stock=$stockitem->stock-$model->stock;
         
            $stockitem->save();
         
            //Stock add to center
            $st=  Stockcenter::find()->where(['stockitem_id'=>$model->stockitem_id,'center_ccid'=>$model->center_ccid])->one();
            if($st)
            {
              $st->stock=$st->stock+$model->stock;
              $st->amount=$model->amount;
              $st->save();
            }
            else
            {
                $st= new Stockcenter();
                $st->stockitem_id=$model->stockitem_id;
                $st->center_ccid=$model->center_ccid;
                $st->stock=$model->stock;
                $st->amount=$model->amount;
                $st->save();              
            }
         
         
            $model->date=date('Y-m-d',strtotime($model->date));
            $model->save();
         
            $transaction->commit();

            } catch (Exception $e) {
                        $transaction->rollBack();
            }
         
            //Redirect...
         
         
        }


Example

$transaction = Yii::$app->db->beginTransaction(); 
              
                try {
                    
                                     
                    $command=Yii::$app->db->createCommand('UPDATE receipt SET type="STUDENTS" , students_admission_number = '. $std->admission_number . ', students_ccid = '. $std->ccid .' WHERE type = "ENQUIRY" AND students_admission_number = '. $model->enquiry_number . ' and students_ccid = ' . $model->ccid);
                    
                    if($std->save() && $model->save() && $command->execute())                    
                        $transaction->commit();
                    
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    throw $e;
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    throw $e;
                }


http://www.yiiframework.com/doc-2.0/yii-db-transaction.html