Hello guest, Please login or register.

Widget - Development

How to create a Widget?

In order to create a widget please follow these steps:

  1. Create a new file named "example_widget.php" in "clancms/widgets/" where "example" is the name of the widget. Here is the basic framework for the widget:
  2. <?php
    
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');  
    
    class Example_widget extends Widget { 
    
        /** 
         * Constructor 
         * 
         */ 
        function Example_widget() 
        { 
            // Call the Widget constructor 
            parent::Widget(); 
             
            // Create a instance to CI 
            $CI =& get_instance(); 
        } 
         
        function index() 
        { 
            // Load the example view 
            $this->CI->load->view(THEME . 'widgets/example'); 
        } 
         
    } 
         
    /* End of file example_widget.php */ 
    /* Location: ./clancms/widgets/example_widget.php */
    				
    ?>
  3. Create a template in "clancms/views/themes/YOUR_THEME/widgets" folder named "example.php"
  4. To use the widget you need to load it wherever you want it to be used. Here is how to load the widget:
  5. <?php
    
    $this->load->widget('example');
    				
    ?>
  6. Your widget should now be loaded and ready to use!

How to pass data from the widget to the template?

The whole point of a widget is to pass data easily from our database to the template. Let's say we wanted to grab the latest 3 news articles from the database and pass them to the template. To do this we would have to do the following:

<?php

// Load the Articles model
$this->CI->load->model('Articles_model', 'articles');
		
// Retrieve the articles
$articles = $this->CI->articles->get_articles(3);
		
// Create a reference to articles
$this->data->articles =& $articles;
		
// Load the articles widget view
$this->CI->load->view(THEME . 'widgets/articles', $this->data);
		
?>

Now the array articles will be available in the articles widget template and can be easily displayed via a foreach loop:

<?php

<?php if($articles): ?>
	<ul id="ticker">
	<?php foreach($articles as $article): ?>
		<li><?php echo $article->article_title; ?> - <?php echo anchor('articles/view/' . $article->article_slug, 'View Article', array('class' => 'yellow')); ?></li>
	<?php endforeach; ?>
	</ul>
<?php else: ?>
	There are currently no articles
<?php endif; ?>

?>