PHP Professional এবং Zend Certified PHP Engineer (ZCPE ) Course এ সীমিত সংখ্যক আসন বাকি আছে। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করার জন্য অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল নম্বর : ০১৭২২ ৮১ ৭৫ ৯১

Client Side Form Validation with Yii Framework

Yii logo

Validating form is the process of inserting proper data into the database. It is a serious security issue. Yii framework makes it easy for us. In this tutorial, I will show you how to create a form and validate the input data. I assume, you have little knowledge about GiiModule and CRUD operation.

Introduction:
There are two kinds of form validation process, Yii support. First one is server side form validation and second one is client side validation process. In this tutorial I will show you how to do client side validation in the form.

Preparation:
Let’s imagine there is a company called xyz and has number of employees. They want to create a database with all employees’ information.

So, to provide this solution we need a database and our mighty Yii framework.

Step 1: Creating Database
Use the following code to create our table.

--
-- Database: xyz
--

CREATE DATABASE xyz;

--
-- Select: xyz
--

USE xyz;

--
-- Table structure for table employees
--

CREATE TABLE IF NOT EXISTS employees (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(150) NOT NULL,
  age int(11) NOT NULL,
  email varchar(100) NOT NULL,
  address text NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

This code will create one database called xyz and five fields for our employees table.

id – Id no of the employee
name – Name of the employee
age – Employee age
email – Email address of the employee
address – Address of the employee

We are done with our database. Now we will start working with our framework.

Step 2: Framework Preparation

Create a project with yiic application named yiiform in your htdocs folder. Now go to

http://localhost:8080/yiiform/

If everything is ok you will see the welcome screen of Yii.

Now, enable GiiModule from by uncommenting the following code segment from htdocs>yiiform>protected>config>main.php. And, I am setting my GiiModle password to Password.

'gii'=>array(
    'class'=>'system.gii.GiiModule',
    'password'=>'Password',
    // If removed, Gii defaults to localhost only. Edit carefully to taste.
    'ipFilters'=>array('127.0.0.1','::1'),
),

Uncomment the following code segment to get nicer URL from main.php

'urlManager'=>array(
    'urlFormat'=>'path',
    'rules'=>array(
    '<controller:\w+>/<id:\d+>'=>'<controller>/view',
	'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
	'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
        ),
),

Comment in the SQLite database setting from main.php. Because, we will use MySQL database for our application.

/*
'db'=>array(
	'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
	),
*/

Uncomment and change the MySQL database connection string from main.php by

'db'=>array(
    'connectionString' => 'mysql:host=localhost;dbname=xyz',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
),

Note: Make sure you set your own username and password for your MySQL server.

Go to – http://localhost:8080/yiiform/index.php/gii. If everything is OK you will see the Yii Code Generator screen. Write the password and click Enter.

Now, we will create model for our application, then we will use Form Generator to create our form and lastly we will create our controller.

Let’s start now. To work with me follow the sequences.

  1. Click on the Model Generator link in Yii Code Generator page. It will take us to the Model Generator page. Fill the Table Name by our database table name and Model Class. Model Class would be the same as table name. Then click Preview and then Generate button. It will create an Employees.php file in htdocs>yiiform>protected>models folder.

Model Generator screen

  • Click on the Form Generator link from the same page. It will Form Generator page. Write –

Model Class: Employees
View Name: employees/index

Click Preview and Generate. This will create index.php in views/employees folder, which will have necessary codes for form.

Form Generator screen

It will give you a sample code segment for your controller class. For, this tutorial no needs to copy this code. If you work for your personal project, you may need to store this code.

  • Now, click on the Controller Generator link. Fill the fields’ with-

Controller ID: Employees

Click Preview button. It will show an error. This is because we have already created our views, when we worked with Form Generator. Keep it uncheck and click Generate button.

Controller Generator screen

It will create EmployeesController.php in our controllers folder.

  • By this time, we have our Model, View and Controller (MVC). But these are not interlinked with each other. We have to do it by writing code. Open EmployeesController.php file with your editor and replace with the following code segment.
    <?php
    
    class EmployeesController extends Controller
    {
    
    	public function actionIndex()
    	{
        	$model=new Employees;
    
        	if(isset($_POST['ajax']) && $_POST['ajax']==='employees-index-form')
        	{
            	echo CActiveForm::validate($model);
            	Yii::app()->end();
        	}
    
        	if(isset($_POST['Employees']))
        	{
            	$model->attributes=$_POST['Employees'];
            	if($model->validate())
            	{
                	// form inputs are valid, do something here
                	if($model->save())
    		$this->redirect(array('index'));
                	return;
            	}
        	}
        	$this->render('index',array('model'=>$model));
    	}
    }
    

    Code Explanation:

    In line 6 we have created a actionIndex() method which is initiated when we call Employees controller.

    In line 8 we have created an instance of Employees model.

    From line 10 – 14, this code is responsible for checking the validation of our input data. Here, we have used CActiveForm form validation class of Yii framework.

    Line from 17 – 27 we have saved our validated input data to our database. And after saving we have redirected to our input form page.

  • We need to change our views as well. So, open index.php from views/employees folder with your editor and replace with the following code.
<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'employees-index-form',
	'enableAjaxValidation'=>true,
	'enableClientValidation'=>true,
	'focus'=>array($model,'name'),
)); ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'name'); ?>
		<?php echo $form->textField($model,'name'); ?>
		<?php echo $form->error($model,'name'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'age'); ?>
		<?php echo $form->textField($model,'age'); ?>
		<?php echo $form->error($model,'age'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'email'); ?>
		<?php echo $form->textField($model,'email'); ?>
		<?php echo $form->error($model,'email'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'address'); ?>
		<?php echo $form->textField($model,'address'); ?>
		<?php echo $form->error($model,'address'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton('Submit'); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->

Code Explanation:

From line 3 – 8, we have initialized CActiveForm class with a widget.

From line 10 – 41, we have used different methods from CActiveForm class to create our form fields and labels.

  • A small change needs to do in your model file as well. So, open Employees.php from models folder with your editor. Find out the following code segment and replace it.
public function rules()
{
	return array(
		array('name, age, email, address', 'required'),
		array('age', 'numerical', 'integerOnly'=>true),
		array('name', 'length', 'max'=>150),
		array('email', 'email'),
		array('id, name, age, email, address', 'safe', 'on'=>'search'),
	);
}

Code Explanation:

In line one, we have created rules() method to validate our input data. And, it returns a multidimensional array.

From line 4 – 8, we have set the validating criteria for our input fields.

You are done by now. Go to http://localhost:8080/yiiform/index.php/Employees from your browser. You will see a page with our form –
Form Validation final screen

Yes.. We have done. Now, start populating xyz database with your data.

I tried to submit some invalid data in the fields. But, it did not work. Try for yourself. Incase..

All error messages

Yahoo.. we have completed our application.

Conclusion
Yii greatly simplifies the workflow of MVC architecture as well as validate user input and display appropriate error messages for invalid input. Yii ensures to save the input to persistent storage.

Happy Coding 🙂

Client Side Form Validation with Yii Framework

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.

6 comments on “Client Side Form Validation with Yii Framework
  1. I think this is still server validation of the form unless I missed something. If you watch in firebug at every exit of a field you will see a post with the form data going back to the model for validation. I think this is called AJAX validation and I think their is a way for Yii to do client side validation with Javascript if not mistaken.

    Good example and very clear, wish all that I have come across on the web were as well done.

    Thanks

    SAndy

    • Correct. This is server-side validation. Javascript needs to be written for client-side validation. Not very clear from the documentation though.

      • You don’t need to write javascript to have client-side validation.
        The only thing this tutorial is missing, is that you need to disable ajaxValidation on the fields where you don’t need It.

        To achieve that, you need to define the 4th parameter of the error field to false.

        error($model,’name’, array(), false); ?>

        It will disable ajaxValidation for that field.
        If you need to disable client-side validator, set the 5th parameter as false.

        http://www.yiiframework.com/doc/api/1.1/CActiveForm/#error-detail

Leave a Reply

Your email address will not be published. Required fields are marked *