Fully ajax website with Yii – Part 2

In previous post I described how to create simple full ajax web application without changing basically logic of the application. All changes was made to the layout, view and to the base classes.
But as you maybe already noticed not everything works well. For example if you tried to sign-in -menu won’t be updated. In this short article I will show how to fix such kind of problems.

All data which ouputs for ajax request collecting with help of flash messages (built-in Yii functionality);

So basically if you wand update something on your page you have to set flash message with name updatedata wich contains an array with key value elements

Example   protected/controllers/SiteController.php ;  actionLoginMethod

                ...
                // collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
                        if($model->validate() && $model->login()) {
                               Yii::app()->user->setFlash('updatedata', array(
 						'#mainmenu'=>$this->renderPartial('/includes/menu',array(),true),));                   
                               $this->redirect(Yii::app()->homeUrl);
                        }
                ...

As you can see I put all mainmenu to separate file. Here is it’s content

protected/views/includes/menu.php

	<?php $this->widget('zii.widgets.CMenu',array(
			'items'=>array(
				array('label'=>'Home', 'url'=>array('/site/index')),
				array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
				array('label'=>'Contact', 'url'=>array('/site/contact')),
				array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
				array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
			),
		)); ?>

For avoiding dublicating data I cut this code from main layout and put there renderPartial instead.

protected/views/layout/main.php

...
<div id="mainmenu" >
		<?php $this->renderPartial('/includes/menu');?>
</div><!-- mainmenu -->
...

So all blocks that might be updated via ajax better to move to includes folder. Now after sign -in main menu is changing.

Now we have to add the same code to sign-out method

protected/controllers/SiteController.php

...
public function actionLogout()
	{
		Yii::app()->user->logout();
		Yii::app()->user->setFlash('updatedata', array(
 						'#mainmenu'=>$this->renderPartial('/includes/menu',array(),true),));
 
		$this->redirect(Yii::app()->homeUrl);
	}
...

In that way you can update everyrhing you want on the webpage. Good luck!
P.S. Suggestions are welcome!

Full ajax Yii webapp demo