widget又称动态block,首先widget有Block的特点,是用来获取数据然后在前台输出的,其次它不像block输出时需要在布局配置文件中配置,那么widget又如何配置和使用呢,
下面我们通过一个例子来说明widget创建配置和使用的全过程
1、创建widget
从根本上说创建widget只需要一个配置文件widget.xml己可以了,
在你module的etc/ 目录下创建widget.xml文件,文件内容如下
<?xml version="1.0"?>
<widgets>
<blog_list type="blog/last" translate="name description" module="blog"><!--blog_list是你创建的widget的唯一标志符,保证全局唯一就可以了;module="blog"设置widget所在的模块;type="blog/last"设置widget所对应的block类,这里设置了blog_list widget对应的block是blog模块下的last block类 -->
<name>Blog: Latest Posts</name>
<description>Adds a list of latest post from Blog</description>
<parameters><!-- 设置widget的参数,用于在后台设置-->
<blocks_count>
<label>How much blocks to show</label>
<type>text</type>
<visible>1</visible>
<required>1</required>
</blocks_count>
<categories>
<label>Categories to show</label>
<type>multiselect</type><!--多选框类型参数-->
<source_model>blog/system_config_source_categories</source_model><!--多选框参数的数据模型-->
<visible>1</visible>
<required>1</required>
</categories>
</parameters>
</blog_list>
</widgets>
上面就是看一个widget的全部配置,刷新后台就能在后台看到这个widget了,但是单单就这个配置文件还不能使widget正常工作,从上面的配置我们至少还需要两个文件,一个是blog/last配置说明需要一个block类(AW_Blog_Block_Last),另一个<source_model>blog/system_config_source_categories</source_model>配置说明需要一个数据model文件(AW_Blog_Model_System_Config_Source_Categories)
AW_Blog_Block_Last
class AW_Blog_Block_Last implements Mage_Widget_Block_Interface
{
protected function _toHtml()
{
$this->setTemplate('aw_blog/widget_post.phtml');//设置模版文件
echo $this->getBlocksCount();//获取blocks_count参数
echo $this->getCategories();//获取categories参数
}
public function getRecent()
{
// widget declaration
if ($this->getBlogWidgetRecentCount()) {
$size = $this->getBlogWidgetRecentCount();
} else {
// standard output
$size = self::$_helper->getRecentPage();
}
if ($size) {
$collection = clone self::$_collection;
$collection->setPageSize($size);
foreach ($collection as $item) {
$item->setAddress($this->getBlogUrl($item->getIdentifier()));
}
return $collection;
}
return false;
}
}
AW_Blog_Model_System_Config_Source_Categories
class AW_Blog_Model_System_Config_Source_Categories {
public function toOptionArray() {
$categories = array();
$collection = Mage::getModel('blog/cat')->getCollection()->setOrder('sort_order', 'asc');
foreach ($collection as $cat) {
$categories[] = ( array(
'label' => (string) $cat->getTitle(),
'value' => $cat->getCatId()
));
}
return $categories;
}
}
2、使用widget
widget又叫动态Block,使用的时候非常方便,只需要在后台编辑产品或这CMS页面时候插入widget就行了
这里以插入新产品为例描述下Widget的使用方式,打开一个cms页面,这里我用首页,点击编辑器上的第二个图标Insert Widget,打开Widget选择页面
选择Catalog New Products List,下面会弹出这个Widget的配置参数
配置完之后点击Insert Widget,新产品这个block已经插入到首页中,而且样子很形象