Widget - Development
How to create a Widget?
In order to create a widget please follow these steps:
- 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:
- Create a template in "clancms/views/themes/YOUR_THEME/widgets" folder named "example.php"
- To use the widget you need to load it wherever you want it to be used. Here is how to load the widget:
- Your widget should now be loaded and ready to use!
<?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 */
?>
<?php
$this->load->widget('example');
?>
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; ?>
?>

