Friday 6 January 2017

YII Frame work Forms

Creating Form

We'll create a form to get the data from users.
In our form, we'll create four input fields for name, contact, course and email. Page will display the entered values back.
Step 1 Create Model file UserForm.php
Here we'll create a model file to request data from the user in models/UserForm.php.
  1. <?php   
  2.   
  3.     namespace frontend\models;   
  4.   
  5.     use Yii;   
  6.     use yii\base\Model;   
  7.   
  8.     class UserForm extends Model   
  9.     {   
  10.         public $name;   
  11.         public $contact;   
  12.         public $course;   
  13.         public $email;   
  14.   
  15.         public function rules()   
  16.         {   
  17.             return [   
  18.                 [['name''contact''course''email'], 'required'],   
  19.                 ['email''email'],   
  20.         ];   
  21.         }   
  22.     }   
Look at the above code, the function rules() is set to validate data from users.
Step 2 Create Action
In the controllers/SiteController.php, we'll create an action user.
  1. <?php   
  2.     namespace frontend\controllers;   
  3.   
  4.     use Yii;   
  5.     use yii\base\InvalidParamException;   
  6.     use yii\web\BadRequestHttpException;   
  7.     use yii\web\Controller;   
  8.     use yii\filters\VerbFilter;   
  9.     use yii\filters\AccessControl;   
  10.     use common\models\LoginForm;   
  11.     use frontend\models\PasswordResetRequestForm;   
  12.     use frontend\models\ResetPasswordForm;   
  13.     use frontend\models\SignupForm;   
  14.     use frontend\models\ContactForm;   
  15.     use frontend\models\UserForm;   
  16.     /**  
  17.     * Site controller  
  18.     */   
  19.     class SiteController extends Controller   
  20.     {   
  21.         /**  
  22.         * @inheritdoc  
  23.         */   
  24.     public function actionUser()   
  25.         {   
  26.             $model = new UserForm();   
  27.   
  28.             if ($model->load(Yii::$app->request->post()) && $model->validate()) {   
  29.                 // valid data received in $model   
  30.   
  31.                 // do something meaningful here about $model ...   
  32.   
  33.                 return $this->render('user-confirm', ['model' => $model]);   
  34.             } else {   
  35.                 // either the page is initially displayed or there is some validation error   
  36.                 return $this->render('user', ['model' => $model]);   
  37.             }   
  38.         }   
Look at the above code, action receives the data from the $_POST method provided by the users. The action validate() will make sure that entered data is valid.
If data is valid, then action will render to the view page user-confirm to confirm the submission. Otherwise, it will go to else part, stating error in the validation.
Step 3 Create views
Two files in the view directory will be created.
One is user-confirm.php file in views/site/user-confirm.php.
  1. <?php   
  2.     use yii\helpers\Html;   
  3.     ?>   
  4.     <p>You have entered the following information:</p>   
  5.     <ul>   
  6.         <li><label>Name</label>: <?= Html::encode($model->name) ?></li>   
  7.         <li><label>Contact</label>: <?= Html::encode($model->contact) ?></li>   
  8.         <li><label>Course</label>: <?= Html::encode($model->course) ?></li>   
  9.      <li><label>Email</label>: <?= Html::encode($model->email) ?></li>   
  10.     </ul>  
Other is user.php file in views/site/user.php.
  1. <?php   
  2.     use yii\helpers\Html;   
  3.     use yii\widgets\ActiveForm;   
  4.     ?>   
  5.     <?php $form = ActiveForm::begin(); ?>   
  6.   
  7.         <?= $form->field($model'name') ?>   
  8.   
  9.         <?= $form->field($model'contact') ?>   
  10.   
  11.         <?= $form->field($model'course') ?>   
  12.   
  13.         <?= $form->field($model'email') ?>   
  14.   
  15.         <div class="form-group">   
  16.             <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>   
  17.         </div>   
  18.   
  19.     <?php ActiveForm::end(); ?>  
Look at the above code, the ActiveForm widget is used to create the HTML form. The begin() and end() widgets represents the opening and closing tags of HTML form respectively.
Step 4 Running on Browser
Type the following URL in your browser to run the form,
http://localhost/form/frontend/web/index.php?r=site%2Fuser
YII Creating form 1
Now we'll fill the details in the above form.
YII Creating form 2
On clicking the Submit button, we'll see the validated information.


Ad hoc Validation

To validate values that are not bound to any model, we need to use ad hoc validation. Or if you want to validate values without models then use ad hoc validation.
To perform one type of validation, you may call yii\validators\validator() method of the desired validator.
Not all the valdiators support this type of validation.
For example, we are calling yii\validators\DateValidator()
  1. $date = '24th November 2016, Thursday';  
  2.     $validator = new yii\validators\DateValidator();  
  3.   
  4.     if ($validator->validate($date$error)) {  
  5.         echo 'Date is valid.';  
  6.     } else {  
  7.         echo $error;  
  8.     }  
But to perform multiple validations, against several values you can use yii\base\DynamicModel which defines both attributes and rules.
For example, here we are calling DynamicModel to validate date and email.
  1. public function actionAdHocValidation() {   
  2.     $model = DynamicModel::validateData([   
  3.         'date' => '24th November 2016, Thursday',   
  4.          'email' => 'abc@gmail.com'   
  5.     ], [   
  6.         [['date''email'], 'string''max' => 40],   
  7.      ]);   
  8.       
  9.     if ($model->hasErrors()) {   
  10.         var_dump($model->errors);   
  11.     } else {   
  12.         echo "success";   
  13.     }   
  14.     }  
On the browser, pass the URL
http://localhost/ad_hoc/frontend/web/index.php?r=site/ad-hoc-validation
YII Ad hoc validation 1
Look at the above output, both date and email have been validated at the same time.

No comments:

Post a Comment