In a previous article (How to make a dynamic Sub-menu I discussed a technique to allow you to build a dropdown sub-menu system where each sub-menu is populated by the controller.
I have updated my menu system as I wanted to apply styling to some of the list items, so have changed the way that parameters are passed to the submenu Portlet.
Without further waffle, here is the code..
components/submenu.php
| PHP | | copy code | | ? |
| 01 | Yii::import('zii.widgets.CPortlet'); |
| 02 | |
| 03 | class SubMenu extends CPortlet |
| 04 | { |
| 05 | |
| 06 | public $title; |
| 07 | public $menu; |
| 08 | |
| 09 | public function init() |
| 10 | { |
| 11 | $this->hideOnEmpty=false; |
| 12 | |
| 13 | $controllerId = Yii::app()->controller; |
| 14 | //fb($controllerId); |
| 15 | |
| 16 | if (method_exists($controllerId, 'getSubMenu')) { |
| 17 | $this->menu= $controllerId->getSubMenu(); |
| 18 | } |
| 19 | parent::init(); |
| 20 | } |
| 21 | |
| 22 | protected function renderContent() |
| 23 | { |
| 24 | if (isset ($this->menu)) { |
| 25 | $this->render('subMenu', array('menu'=>$this->menu)); |
| 26 | } |
| 27 | } |
| 28 | } |
components/views/submenu.php
| PHP | | copy code | | ? |
| 01 | |
| 02 | <ul> |
| 03 | <?php |
| 04 | $count = count($menu); |
| 05 | for ($i = 0; $i < $count; $i++) { |
| 06 | $mItem=$menu[$i]; |
| 07 | if (isset($mItem[2])) { |
| 08 | echo "<li ".$mItem[2]." >"; |
| 09 | } else { |
| 10 | echo "<li>"; |
| 11 | } |
| 12 | $mName=$mItem[0]; |
| 13 | $mLink=$mItem[1]; |
| 14 | echo CHtml::link($mName,$mLink)."</li>"; |
| 15 | } |
| 16 | ?> |
| 17 | </ul> |
| 18 |
Somewhere in your code
| PHP | | copy code | | ? |
| 01 | public function setUserMenu() { |
| 02 | |
| 03 | $subMenuItems=array(); |
| 04 | |
| 05 | if(Yii::app()->user->id) { |
| 06 | $user=Yii::app()->controller->module->user(); |
| 07 | $profile=$user->profile; |
| 08 | } |
| 09 | if(UserModule::isAdmin()) { |
| 10 | $subMenuItems[]=array(UserModule::t('Manage User'),'/user/admin'); |
| 11 | $subMenuItems[]=array(UserModule::t('List User'),'/user'); |
| 12 | } |
| 13 | |
| 14 | if(Yii::app()->user->isGuest) { |
| 15 | $subMenuItems[UserModule::t('Register')]='/user/registration'; |
| 16 | |
| 17 | } else { |
| 18 | |
| 19 | $subMenuItems[]=array(UserModule::t('Profile'),'/user/profile'); |
| 20 | $subMenuItems[]=array(UserModule::t('Edit'),'/user/profile/edit'); |
| 21 | $subMenuItems[]=array(UserModule::t('Change password'),'/user/profile/changepassword'); |
| 22 | |
| 23 | } |
| 24 | $subMenuItems[]=array(UserModule::t('Logout').' ('.$user->email.')','/user/logout','class="right"'); |
| 25 | |
| 26 | } |
| 27 | |
| 28 | return $subMenuItems; |
| 29 | |
| 30 | } |
See also:
How to make a dynamic sub-menu
Example of Creating a submenu widget
Blog
Photography
Portfolio
Yii Part 1