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.

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.

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.

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

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.

YII Creating form 3



Latest Courses