lets start from zero:
[list=1][]Create a table named: player with 3 columns: idplayer, firstname, lastname, and add some players to it:[list=1][][indent]
idplayer firstname lastname[/indent][indent]
----------------------------------------------------------------[/indent][indent]
1, ‘name player 1’, ‘last name player 1’[/indent][indent]
2, ‘name player 2’, ‘last name player 2’
[i]
[/i][/indent][/list][*]using Gii, create a model named [b]Player.php
[/b][]again using Gii, create a controller for that model, name: ‘player’, with an action: ‘list’[]Creates the actionList on player controller:
public function actionList()
{
// for demo propouses, list all players
$dataProvider = Player::model()->search();
$this->render('list',array('dataProvider'=>$dataProvider));
}
[*]In your view: views/player/list.php (this file was created by Gii when you creates your controller, step 3) put the following:[/list]
[indent]
<h1>My Players</h1>
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'idplayer',
'firstname',
'lastname',
),
));
?>
[/indent][indent]
[/indent][indent]6. Test your view: http://localhost/tes...p?r=player/list (use your own URL) it will display a CGridView with your players created in step 1.
[/indent][indent]7. Create a new action in your player controller, named: ‘actionAjaxCreate’[/indent]
[indent]
public function actionAjaxCreate() {
$p = new Player();
$p->firstname = 'new Player firstname';
$p->lastname = 'new Player lastname';
if($p->save()){
echo "OK"; // echo or not, if an exception dont occur then is OK.
}
else{
throw new Exception("Sorry, cant create a player",500);
}
}
[/indent]
[indent]
- create a "New Player" Button with auto refresh of your grid:[/indent]
[indent]
<h1>My Players</h1>
<!-- CODE TO INSERT NEW PLAYER BEGINS -->
<div id='results'>...</div>
<script>
function allFine(data) {
// display data returned from action
$("#results").html(data);
// refresh your grid
$.fn.yiiGridView.update('player-grid');
}
</script>
<?php echo CHtml::ajaxButton("Insert New Player", array('player/ajaxcreate'), array('success'=>'allFine')); ?>
<!-- CODE TO INSERT NEW PLAYER ENDS -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'player-grid',
'dataProvider'=>$dataProvider,
'columns'=>array(
'idplayer',
'firstname',
'lastname',
),
));
?>
[/indent]
[indent]
- test it. It works fine, and will insert a new player refreshing your grid inmediatly.[/indent]