Menus

Sunday, 22 October 2017

Yii2 Validating Input


Given a model populated with user inputs, you can validate the inputs by calling the yii\base\Model::validate() method. The method will return a boolean value indicating whether the validation succeeded or not. If not, you may get the error messages from the yii\base\Model::$errors property. 


Yii2 Custom Rules 



Open your model, add this code

public function rules()
    {
        return [
       .....
       ....
       ['enquiry_reference_no', 'uniqueReference_no'],  //Custom Validation In Yii2.0
     ],



public function uniqueReference_no($attribute, $params)
    {      
        if ($this->isNewRecord ==1)
        {
        $Stud = Enquiry::find()->where(['enquiry_reference_no' => $this->enquiry_reference_no])->one();  
        }
        else {      
            $Stud = Enquiry::find()->where('enquiry_reference_no = :en and enquiry_number != :an', ['en' => $this->enquiry_reference_no,'an' => $this->enquiry_number])->one();
        }
         
        if($Stud)
          $this->addError($attribute, 'Reference Number must be unique');
     
    }

}  


Code add in Controller

public function actionCreate()
    {
     
             
             $model = new Enquiry();
     
            //ajax validation..
            if(yii::$app->request->isAjax && $model->load($_POST))
            {
                yii::$app->response->format = 'json';
                return \yii\widgets\ActiveForm::validate($model);
            }

public function actionCreate()
    {
     
     
        $model = new Enquiry();
     
            //ajax validation..  for reference number unique
            if(yii::$app->request->isAjax && $model->load($_POST))
            {
                yii::$app->response->format = 'json';
                return \yii\widgets\ActiveForm::validate($model);
            }
         

           if ($model->load(Yii::$app->request->post())) {
           .........
           }
    .........
  }


Enable ajax validation in form

<?php $form = ActiveForm::begin(['enableAjaxValidation' => TRUE]); ?>



More Details
http://www.yiiframework.com/doc-2.0/guide-input-validation.html



Data Type Validation In Yii2.0

[['boolean_var'],'boolean'],
Other Types - number,integer,'double','string'

Required Validation In Yii2.0

[['username'],'required'],

Assigning Default Value In Yii2.0

// set "email" as null if they are empty [['email'],'default'], // set "level" to be 111 if it is empty [['level'],'default','value'=>'111'],

Minimum, Maximum Number Validation In Yii2.0

[['slno'],'number','max'=>100], [['roll_no'],'number','min'=>10,'max'=>100],

Minimum, Maximum String Validation In Yii2.0

[['max_string'],'string','max'=>10], [['min_max_string'],'string','min'=>5,'max'=>10], ['min_max_string2', 'string', 'length' => [4, 10]]

File Type/ Image Validation In Yii2.0

[['file_image'],'image'], [['file_var'],'file','types'=>['gif','jpg']], ['file_image', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024], ['file_image', 'image', 'extensions' => 'png, jpg, gif', 'minWidth' => 100, 'maxWidth' => 500, 'minHeight' => 100, 'maxHeight' =>500,],

Date Format Validation In Yii2.0

[['date_var'],'date', 'format'=>'d-m-yy'],

Email, URL Format Validation In Yii2.0

['email_var','email'], ['url_var','url'], //prepend the 'http' with url if it is not available ['website', 'url', 'defaultScheme' => 'http'],

Unique Validation In Yii2.0

[['unique_var'],'unique'],
//email is validated in secondary_email column ['email', 'unique', 'targetAttribute' => 'secondary_email'],

exist Validation In Yii2.0

['user_name', 'exist'], //email should not be exist in secondary_email ['email', 'exist', 'targetAttribute' => 'secondary_email'],

Filter Validation In Yii2.0

[['filter_trim'],'filter','filter'=>'trim'],
['filter_custom_function', 'filter', 'filter' => function ($value) { // your concept if($value=='') return ''; return 'Value Changed'; }],

Range In Validation In Yii2.0

['range_in_min_max', 'in','range'=>range(5,20)], ['range_in','in','range'=>['en','fr','zn']], ,'strict'=>false], ['range_in_string','in','range'=>['EN','FR','ZN'],'strict'=>true],

Compare Validation In Yii2.0

[['passwordConfirm'], 'compare', 'compareAttribute' => 'password'],// validates if the value of "password" attribute equals to that of "password_repeat" ['password', 'compare'],//password_repeat ['age', 'compare', 'compareValue' => 18, 'operator' => '>='], [['password','date_var'],'safe'],
 we have to check They are '==','===','>','>=','<','<=', '!=','!=='

Custom Validation In Yii2.0

public function rules(){ return [ ['custom_validation','custom_function_validation', 'values'=>['One', 'Two']], ]; } public function custom_function_validation($attribute, $params){ // add custom validation if (!in_array($this->$attribute, $params['values'])) $this->addError($attribute,'Custom Validation Error'); }
Inline Custom Validation In Yii2.0
public function rules(){ return [ ['token', function ($attribute, $params) { if (!ctype_alnum($this->$attribute)) { $this->addError($attribute, 'The token must contain letters or digits.'); } }], ]; }

captcha Validation In Yii2.0
['verificationCode', 'captcha'],

match Validation In Yii2.0
['user_name', 'match', 'pattern' => '/^[a-z]\w*$/i']



Related Links

DropDownList

Yii2 Dependent Drop Down Lists

CheckboxList Advanced Operations

Yii2 ListBox Field



Tuesday, 26 September 2017

Yii2 DatePicker



How to add a date range picker to filter for dates on a GridView for Yii2




The ModelSearch class
Your model Students has a date_of_join attribute and we want to add a date range filtering on that value.

declare variable
    public $date_from;
    public $date_to;
add in search function

if($this->date_from && $this->date_to) {
$query->andFilterWhere(['between', 'date_of_join', date('Y-m-d',strtotime($this->date_from)),  date('Y-m-d',strtotime($this->date_to))]);
}


Configuring GridView column

use widget
use dosamigos\datepicker\DateRangePicker;

filtering column

         
                'format'=>'raw',                
                'filter'=>  DateRangePicker::widget([
                                                        'model' => $searchModel,
                                                        'attribute' => 'date_from',
                                                        'attributeTo' => 'date_to',
                                                       'clientOptions' => [
                                                            'autoclose' => true,
                                                            'format' => 'd-m-yyyy',  
                                                            'todayBtn' => true,
                                                        ]
                                                    ]),                                              
                'attribute' => 'date_of_join',           
       'format' =>  ['date', 'php:d-m-Y'],
       'options' => ['width' => '1000'],                
   ],   

Related site - http://www.2amigos.us/blog/how-to-add-a-date-range-picker-to-filter-for-dates-on-a-gridview-for-yii2

Yii2 date range filter

'columns' => [     [          'attribute' => 'date',          'filter' => DateRangePicker::widget(...),     ] ] 



Related Links

Yii2 gridview widget filter

Tuesday, 19 September 2017

Yii2 Text Input Field



Yii Framework 2.0 ActiveForm Input Fields

'yii\widgets\ActiveForm' class is used to create a form and 'yii\helpers\Html' class is used to display the different type of HTML input fields like buttons, textbox, select box etc.
ActiveForm::begin() - creates a form instance and  beginning of the form.
ActiveForm::begin() and ActiveForm::end() - All of the content placed between this.

Use the namespace For ActiveForm


<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
'ActiveForm' namespace is very important to create the a active form and 'Html' namespace is very useful to display the different html input fields.

Active Form Begin And End



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

//$form = ActiveForm::begin(); //Default Active Form begin
$form = ActiveForm::begin([
    'id' => 'active-form',
    'options' => [
    'class' => 'form-horizontal',
    'enctype' => 'multipart/form-data'
    ],
])
/* ADD FORM FIELDS */
ActiveForm::end();
?>

Yii2 Text Input Field



//Format 1
<?= $form->field($model,'name'); ?>
//Format 2
<?= $form->field($model, 'name')->textInput()->hint('Please enter your name')->label('Name') ?>


yii2 ActiveForm numeric textfield

yii2 textinput to accept only numeric input.


You can use ->textInput(['type' => 'number']

HTML example
<input type="number" min="0" max="10"></input>

<?= $form->field($modelSalesitem, "qty")->textInput(['type' => 'number', 'maxlength' => true, 'onChange' => 'checkStock(this.id);',])->label(false)->error(FALSE) ?>                                   


Yii2 Textinput set as min value

<?= $form->field($modelSalesitem, "qty")->textInput(['type' => 'number', 'min'=>1, 'maxlength' => true])->label(false)->error(FALSE) ?>