Yii ajax form

Yii ajax form submission

In this post I will show you how to insert values into database using Yii ajax form.First of all download the frame work from the yii site http://www.yiiframework.com/download/ . I am using the version Yii 1.1. After downloading the file you can create a basic application using command prompt.

 

First you have to set the environment variable for php. For that right click on the computer icon on the desktop and select properties. Then click on the ‘Advanced system settings’ menu on the left side. Then select the advanced tab and click on the ‘Environment Variables’ button.In the dialog that appears select path in the system variable section and and click edit, then enter the path to the php.exe file. For me it is located in ‘E:\wamp\bin\php\php5.5.12’. Then open the command prompt and enter the path to the frame work followed by command to create the application, for me it is ‘E:\wamp\www\yii\framework\yiic webapp E:\wamp\www\myapp’. So now the application is created successfully.

 

Yii ajax form

 

Yii ajax form
Now we will connect the application to a mysql database. Open ‘myapp\protected\config\main.php’, this is the configuration file for yii. Here I will use the database ‘report’ that I created for another tutorial as explained here.

Yii ajax form

Create a file ‘myapp\protected\components\ButtonColumn.php’ and copy the below code, which is a class used in the grid view.

<?php
/**
* ButtonColumn class file.
* Extends {@link CButtonColumn}
*
* Allows additional evaluation of ID in options.
*
* @version $Id$
*
*/
class ButtonColumn extends CButtonColumn
{
/**
* @var boolean whether the ID in the button options should be evaluated.
*/
public $evaluateID = false;

/**
* Renders the button cell content.
* This method renders the view, update and delete buttons in the data cell.
* Overrides the method 'renderDataCellContent()' of the class CButtonColumn
* @param integer $row the row number (zero-based)
* @param mixed $data the data associated with the row
*/
public function renderDataCellContent($row, $data)
{
$tr=array();
ob_start();
foreach($this->buttons as $id=>$button)
{
if($this->evaluateID and isset($button['options']['id']))
{
$button['options']['id'] = $this->evaluateExpression($button['options']['id'], array('row'=>$row,'data'=>$data));
}

$this->renderButton($id,$button,$row,$data);
$tr['{'.$id.'}']=ob_get_contents();
ob_clean();
}
ob_end_clean();
echo strtr($this->template,$tr);
}
}
?>

Now we will create a new page in the website. Create a new file under ‘myapp\protected\views\site\students.php’. This is the view file for the page. Now we will add the form to insert values into the database table ‘student.

<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'student-form',
'action' => Yii::app()->createUrl('//site/studentsapply'),
'enableAjaxValidation' => true,
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate'=>'js:function(form,data,hasError){
if(!hasError){
$.ajax({
"type":"POST",
"url":"'.CHtml::normalizeUrl(array("//site/studentsapply")).'",
"data":form.serialize(),
"success":function(data){$.fn.yiiGridView.update("students-grid");$("#student-form")[0].reset();$("#Students_editmode").val(0);return false;},
"error":function(xhr, status, error){alert(xhr.responseText);},
});
}
}'
),
'htmlOptions' => array(
"class"=>"form-horizontal"
),
));

echo $form->hiddenField($model,'editmode',array('value'=>0));
echo $form->hiddenField($model,'student_id');
?>
<?php echo $form->labelEx($model,'student_name',array('class'=>'control-label')); ?>
<?php echo $form->textField($model,'student_name',array('class'=>'form-control','title'=>'Name')); ?>
<?php echo $form->error($model,'student_name',array('class'=>'help-block','style'=>'color:#b94a48;')); ?>

<?php echo CHtml::submitButton('Save',array('class'=>'btn btn-primary top-buffer')); ?>
<?php $this->endWidget(); ?>

Here we are using CActive form.The form id is ‘student-form’. This should be used in the site controller for ajax validation. If there is no error then we are submiting the form using $.ajax function. Next we will create the model file for writing the queries.This file is located at ‘myapp\protected\models\Students.php’.

<?php
class Students extends CActiveRecord
{
public $editmode;
public $student_name;
public $student_id;

/**
* Declares the validation rules.
*/
public function rules()
{
return array(
array('student_name', 'required'),
array('student_id,editmode', 'safe'),
);
}

public function tableName()
{
return 'student';
}

public function attributeLabels() {
parent::attributeLabels();
return array(
'student_name'=>'Name : ',
);
}

public function search()
{

if(empty($this->student_name))
$this->student_name=null;

$command =Yii::app()->db->createCommand("SELECT COUNT(*) FROM student where :student_name is null or name like '%:student_name%'");
$command->bindParam(":student_name", $this->student_name,PDO::PARAM_STR);
$count=$command->queryScalar();

$sql="SELECT id,name FROM student where :student_name is null or name like '%:student_name%'";

$dataProvider=new CSqlDataProvider($sql, array(
'params' => array(':student_name'=>$this->student_name),
'totalItemCount'=>$count,
'db'=>Yii::app()->db,
'sort'=>array(
'attributes'=>array(
'student_name'
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
return $dataProvider;
}

public function transaction()
{

if($this->editmode==0)
{
$command = Yii::app()->db->createCommand("insert into student(id,name) values(null,:student_name);");
$command->bindParam(":student_name",$this->student_name,PDO::PARAM_STR);
$command->execute();

}
else if($this->editmode==1)
{

$command = Yii::app()->db->createCommand("update student set name= :student_name where id=:id;");
$command->bindParam(":id",$this->student_id,PDO::PARAM_STR);
$command->bindParam(":student_name",$this->student_name,PDO::PARAM_STR);
$command->execute();

}
}

public function selectRow()
{

$command = Yii::app()->db->createCommand("select id,name from student where id=:id;");
$command->bindParam(":id",$this->student_id,PDO::PARAM_INT);
$result=$command->queryAll();
return $result;
}

public function delete()
{

$command = Yii::app()->db->createCommand("delete from student where id=:id;");
$command->bindParam(":id",$this->student_id,PDO::PARAM_INT);
$command->execute();

}

}

Below is the actions written in the site controller file located at ‘myapp\protected\controllers\SiteController .php’.

public function actionStudents()
{
$model=new Students;
if(isset($_GET['Students']))
{
$model->unsetAttributes();
$model->attributes = $_GET['Students'];
}
$this->render('students',array('model'=>$model));
}

public function actionStudentsApply()
{
$model=new Students;

if(isset($_POST['ajax']) && $_POST['ajax']==='student-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}

if(isset($_POST['Students']))
{

$model->attributes=$_POST['Students'];
$valid=$model->validate();
if($valid){
$model->transaction();
}

else
{
$error = CActiveForm::validate($model);
if($error!='[]')
echo $error;
Yii::app()->end();
}

}

}

public function actionStudentSelectRow()
{
$model=new Students;
if(isset($_GET['Students']))
{
$model->attributes=$_GET['Students'];
$result=$model->selectRow();
echo CJavaScript::jsonEncode($result[0]);
}
}

public function actionStudentDelete()
{
$model=new Students;
if(isset($_POST['Students']))
{
$model->attributes=$_POST['Students'];
$model->delete();
}

}

Now open the layout file located at’myapp\protected\views\layouts\main.php’ and add ‘array(‘label’=>’Students’, ‘url’=>array(‘/site/students’)),’ to the menu. Click the menu ‘Students’ to view the page. Now you can insert the values using Yii ajax form. The values will get displayed in the grid using ajax. You can also edit and delete the values using ajax.

 

Yii ajax form

 

Yii ajax form