YII Creating Form

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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.   
  2.     namespace frontendmodels;   
  3.   
  4.     use Yii;   
  5.     use yiiaseModel;   
  6.   
  7.     class UserForm extends Model   
  8.     {   
  9.         public $name;   
  10.         public $contact;   
  11.         public $course;   
  12.         public $email;   
  13.   
  14.         public function rules()   
  15.         {   
  16.             return [   
  17.                 [['name''contact''course''email'], 'required'],   
  18.                 ['email''email'],   
  19.         ];   
  20.         }   
  21.     }   

Look at the above code, the function rules() is set to validate data from users.

Step 2 Create ActionIn the

In the controllers/SiteController.php, we'll create an action user.

  1.     namespace frontendcontrollers;   
  2.   
  3.     use Yii;   
  4.     use yiiaseInvalidParamException;   
  5.     use yiiwebBadRequestHttpException;   
  6.     use yiiwebController;   
  7.     use yiifiltersVerbFilter;   
  8.     use yiifiltersAccessControl;   
  9.     use commonmodelsLoginForm;   
  10.     use frontendmodelsPasswordResetRequestForm;   
  11.     use frontendmodelsResetPasswordForm;   
  12.     use frontendmodelsSignupForm;   
  13.     use frontendmodelsContactForm;   
  14.     use frontendmodelsUserForm;   
  15.     /**  
  16.     * Site controller  
  17.     */   
  18.     class SiteController extends Controller   
  19.     {   
  20.         /**  
  21.         * @inheritdoc  
  22.         */   
  23.     public function actionUser()   
  24.         {   
  25.             $model = new UserForm();   
  26.   
  27.             if ($model->load(Yii::$app->request->post()) && $model->validate()) {   
  28.                 // valid data received in $model   
  29.   
  30.                 // do something meaningful here about $model ...   
  31.   
  32.                 return $this->render('user-confirm', ['model' => $model]);   
  33.             } else {   
  34.                 // either the page is initially displayed or there is some validation error   
  35.                 return $this->render('user', ['model' => $model]);   
  36.             }   
  37.         }   

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.     use yiihelpersHtml;   
  2.     ?>   
  3.     

    You have entered the following information:

       
  4.     
    •    
      •         
      • Name: $model->name) ?>
      •    
        •         
        • Contact: $model->contact) ?>
        •    
          •         
          • Course: $model->course) ?>
          •    
            •      
            • Email: $model->email) ?>
            •    
              •     
                

Other is user.php file in views/site/user.php.

  1.     use yiihelpersHtml;   
  2.     use yiiwidgetsActiveForm;   
  3.     ?>   
  4.     $form = ActiveForm::begin(); ?>   
  5.   
  6.         $form->field($model'name') ?>   
  7.   
  8.         $form->field($model'contact') ?>   
  9.   
  10.         $form->field($model'course') ?>   
  11.   
  12.         $form->field($model'email') ?>   
  13.   
  14.         
    class="form-group">   
  15.             'Submit', ['class' => 'btn btn-primary']) ?>   
  16.            
  17.   
  18.     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.

models/UserForm.php.


    <?php   

      

        namespace frontendmodels;   

      

        use Yii;   

        use yiiaseModel;   

      

        class UserForm extends Model   

        {   

            public $name;   

            public $contact;   

            public $course;   

            public $email;   

      

            public function rules()   

            {   

                return [   

                    [[name, contact, course, email], required],   

                    [email, email],   

            ];   

            }   

        }   

 

controllers/SiteController.php, well create an action user.


    <?php   

        namespace frontendcontrollers;   

      

        use Yii;   

        use yiiaseInvalidParamException;   

        use yiiwebBadRequestHttpException;   

        use yiiwebController;   

        use yiifiltersVerbFilter;   

        use yiifiltersAccessControl;   

        use commonmodelsLoginForm;   

        use frontendmodelsPasswordResetRequestForm;   

        use frontendmodelsResetPasswordForm;   

        use frontendmodelsSignupForm;   

        use frontendmodelsContactForm;   

        use frontendmodelsUserForm;   

        /**  

        * Site controller  

        */   

        class SiteController extends Controller   

        {   

            /**  

            * @inheritdoc  

            */   

        public function actionUser()   

            {   

                $model = new UserForm();   

      

                if ($model->load(Yii::$app->request->post()) && $model->validate()) {   

                    // valid data received in $model   

      

                    // do something meaningful here about $model ...   

      

                    return $this->render(user-confirm, [model => $model]);   

                } else {   

                    // either the page is initially displayed or there is some validation error   

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

                }   

            }   

 

views/site/user-confirm.php.


    <?php   

        use yiihelpersHtml;   

        ?>   

        <p>You have entered the following information:</p>   

        <ul>   

            <li><label>Name</label>: <?= Html::encode($model->name) ?></li>   

            <li><label>Contact</label>: <?= Html::encode($model->contact) ?></li>   

            <li><label>Course</label>: <?= Html::encode($model->course) ?></li>   

         <li><label>Email</label>: <?= Html::encode($model->email) ?></li>   

        </ul> 

views/site/user.php.


    <?php   

        use yiihelpersHtml;   

        use yiiwidgetsActiveForm;   

        ?>   

        <?php $form = ActiveForm::begin(); ?>   

      

            <?= $form->field($model, name) ?>   

      

            <?= $form->field($model, contact) ?>   

      

            <?= $form->field($model, course) ?>   

      

            <?= $form->field($model, email) ?>   

      

            <div class="form-group">   

                <?= Html::submitButton(Submit, [class => btn btn-primary]) ?>   

            </div>   

      

        <?php ActiveForm::end(); ?> 

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.

YII Creating form 3