Admin area and module activation – Part 2


In the last article I showed you how we solved the problem of activating modules in admin area of our Zend web application. In Part 1 I presented the logic behind the activation, now let’s list our modules in admin area and change their states.

For modules listing I’ve made a new model called Application_Models_Module and I’ve situated it inside application/models/ folder in Module.php file. This model will have functions for activating my module and listing all modules. I wanted to make the process as automatic as possible, so here is how my function look like:

//this goes into application/models/Module.php file
class Application_Model_Module {

     protected $_mod;
     protected $_name;
     protected $_active;

     // basic constructor, setters and getters go here
     // ...

     public function getModules($path){                                // function to get all modules, it takes modules path as it's variable
          $directories = glob($path. '/*' , GLOB_ONLYDIR);                  //get directory listing 
          $directories = str_replace($path.'/','', $directories);           //get only directory names

          $config = new Zend_Config_Ini(APPLICATION_PATH.'/modules/config/modules.ini');  //get my modules.ini file with basic module info

          $mods = array();
          foreach($directories as $mod):
               $conf = $config->$mod;                  //get configuration from modules.ini file for single module

               $this->setMod($mod);                    //setting data inside model's variables

               $mods[$mod] = $this;                             //add modules setting to mods array


          return $mods;                                         //return all modules' data

Ok, we have function that gets our modules. Now we’ll create the function to activate our modules. This function has to read the contents of modules.ini file and then edit them accordingly:

//appending application/models/Module.php file
class Application_Model_Module {

     //right below the getModules() function
     public function changeState($mod, $state){                                    //takes as parameters module and the future state (0 or 1)
         $config = new Zend_Config_Ini(APPLICATION_PATH.'/modules/config/modules.ini', null,          //read the contents of modules.ini and allow modifications
                    array('skipExtends'  => true,
                    'allowModifications' => true));
         $config->$mod->module->active = $state;                       //set module's state
         $writer = new Zend_Config_Writer_Ini(array('config'   => $config,               
				'filename' => APPLICATION_PATH.'/modules/config/modules.ini'));

         try{                  //try to write the state in the file if not successful return error
             return $state;
         }catch (Exception $e){
             return $e;

All of needed function are now complete and we’re going to edit our view. In my admin area module controllers folder I’m going to make a controller Settings and inside it I’m going to add action modulesAction(). In it we’re going to list all of our modules.

// Settings controller inside admin module

class Admin_SettingsController extends Zend_Controller_Action {

     public function modulesAction(){
          $mods = new Application_Models_Module();

          $mods = $mods->getModules(LOCAL_PATH); //LOCAL_PATH is path to my modules/local folder, you can define it as a global in index.php

          $this->view->mods = $mods;     // put the list of mods in the view variable

We’re going to use our view variable to show the modules and edit their states with a little bit of ajax magic inside the view file. Here’s my view file:

 <!-- contents of application/modules/admin/views/scripts/settings/modules.phtml file -->
$mods = $this->mods;
<div class="title">
	<h1>Installed Modules</h1>

<table class="mods">                        //simple table to show our modules list with enabled/disabled information

<?php foreach($mods as $mod):?>

	<a href="/admin/settings/module?mod=<?php echo $mod->getMod();?>" class="<?php echo $mod->getMod()?>"><?php  echo $mod->getName()?></a>

	    <?php $state = $mod->getActive()?>
	    <select class="sel-mod">                                               //select if the module is enable or disabled
		<option value="0" <?php if(!$state) echo 'selected = "selected"' ?>>Disabled</option>
		<option value="1" <?php if($state) echo 'selected = "selected"' ?>>Enabled</option>
	<small class="message"></small>                                            //message area for "Module disabled/enabled." message
	<img style="display: none;" src="<?php echo $this->baseUrl('path_to_small.gif');?>"/> //small gif for loading
<?php endforeach;?>

As you can see we have made a simple table that shows us some basic data. Now let’s make the script needed for changing the state using ajax.

//add this to the bottom of view file or make a new script file and add it at the bottom
	$('.sel-mod').on('change',function(){                                         //when select state changes
		var mess = $(this).parent().find('.message');
		var img = $(this).parent().find('img');

			url:'/admin/settings/modulestate?format=json',                //where to send the data
			beforeSend: function(e){
				img.attr('style','display:block');                    //before sending show the loading gif
			data: {                                                       //data we need to send
				mod: $(this).parent().prev().find('a').attr('class'),
				name: jQuery.trim($(this).parent().prev().text()),
				state: $(this).val()},
			success: function(e){                                          //what to do on success
				var res = e.result;
				var text;
				if(res==1) text = 'Module enabled.';                  
				else text = 'Module disabled.'

				mess.text(text);                                      //inject message into message div
				setTimeout(function(){img.attr('style','display:none')},500);  //disable gif when not needed
			error: function(e){                                           //what to do on error
				mess.text('Something went wrong, please try again later');
			dataType: 'json'                                             //type of data to use

We need to make another action in our settings controller, the one that saves data into the modules.ini file. It’s the action that ajax uses as url to which to send data. Since we’ve already completed our model all we need is to instantiate the right object and call changeState() function.

 //this goes inside our Settings controller

   public function modulestateAction(){
        $mods = new Application_Model_Module();            //our object
        $params = $this->getRequest()->getParams();        //get the request params
        $mod = $params['mod'];                             
        $state = $params['state'];
        $this->view->result=$mods->changeState($mod, $state);    //change the state and return result into new view variable

Don’t forget to make the view file of your new action. And you’re all set. All that needs to be done is to style your table to your liking and add gif file of your choice.

Cheers! 🙂

Published by Iva Korlevic

I'm a web programmer that started working with web pages in 2008 by programming simple HTML/CSS webpages. I finished Faculty of electrical engineering in April 2010 and started working in Inchoo in May 2010. During the time in Inchoo I worked on Zend applications, Magento stores and a few Wordpress projects. I left Inchoo in January 2012 and worked for a couple of months in Gauss Informatika as Zend teacher and team leader. In May 2012 I left Gauss Informatika and joined the team at NTH Media. For next 6 months I worked on various mobile and Wordpress projects. In the February 2013 together with MArin Blazevic I opened Proodos. I'm still continuing my work as Zend and Magento programmer. In summer 2015 I also started to work for Webbite Media GMBH and on 19th August 2015 I passed Magento Certification Exam and am now Magento Certified Developer.

Leave a comment

Your email address will not be published. Required fields are marked *