javascript + tabular input

Enhance tabular input managing. ΒΆ

If you tried this extension with success, maybe you thought how to do it without page submission or ajax calls.

This wiki is meant to be a prosecution of the wiki, so read the extension page and do some test before going forward this example.

The code of the controller and models is the same of the example in the wiki, we will do just some changes in the views.

First of all, a main view with the table of students:

<table id="students">
				<?php echo CHtml::link('add', '', array('onClick'=>'addStudent($(this))', 'class'=>'add'/* 'submit'=>'', 'params'=>array('Student[command]'=>'add', 'noValidate'=>true)/**/));?>
	<?php foreach($students->items as $id=>$model): ?> 
		<?php $this->renderPartial('form/studentRow', array('id'=>$id, 'model'=>$model, 'form'=>$form));?>
	<?php endforeach;?>

<?php $this->renderPartial('form/studentJs', array('students'=>$students, 'form'=>$form));?>

This drows the header of the table, there is a first renderPartial in the foreach for drow the rows of the table, and a second renderPartial that add the needed javascript code.

As you can see, the button add now calls a javascript function instead submit the page, that is the only difference with the previous version.

The view form/studentRow should be like that:

		<?php echo $form->textField($model,"[$id]name"); ?> 
		<?php echo $form->textField($model,"[$id]surname");?>

		<?php echo CHtml::link(
					'onClick'=>'deleteStudent($(this))', /*

In this view too the button has been changed in order to call a js function instead of submit.

Let's now pass to the js file:

<script type="text/javascript">
// initializiation of counters for new elements
var lastStudent=<?php echo $students->lastNew?>;

// the subviews rendered with placeholders
var trStudent=new String(<?php echo CJSON::encode($this->renderPartial('form/studentRow', array('id'=>'idRep', 'model'=>new Student, 'form'=>$form), true));?>);

function addStudent(button)

function deleteStudent(button)


This do the trick.

At the beginning we initialize the variable lastStudent, it will count the student added with javascript in order to have all id different.

In the variable trStudent we save as string the view studentRow. We use the special place holder idRep, that js will replace with the proper id.

This method will replace in name, id and also in evenutally needed javascript functions in the view studentRow, so any javascript in the view will work correcly even in the js added views.