The widget I am going to create is fairly simple; It will output a twitter profile link.

Firstly we need to describe our widget.

We do this using widget.xml located inside our app/code/[codePool]/[Vendor]/[ModuleName]/etc directory.

Before we do we should note that to output the link will require a twitter handle. We should provide a way of giving that information to the widget.

In app/code/[codePool]/[Vendor]/[ModuleName]/etc/widget.xml

<?xml version="1.0"?>
    <[unique_name] type="[namespace]/twitter" translate="name description" module="[namespace]">
        <name>Twitter Profile Link</name>
                <description>The Twitter handle you want to display (@smartiewoo)</description>

Parameters get set on our widget block (defined in the type attribute) as data like any other block. We can therefore access the values in the normal way by calling ->getData('<key>'); from within the class itself or get<Key>() from outside. In this case ->getData('handle').

<handle> (Line 6) is just a unique parameter name.

The properties of the specific parameter are fairly self explanatory in this case but there are quite a few others you can use dependant on the node.

For example, a select type might have a source model (adminhtml/system_config_source_yesno)

You can specify a default value by using the <value> node.

Next, we need to create our widget block.

In app/code/[codePool]/[Vendor]/[ModuleName]/Block/Twitter.php


class [Vendor]_[ModuleName]_Block_Twitter
    extends Mage_Core_Block_Abstract
    implements Mage_Widget_Block_Interface
    public function toHtml()
        $handle = $this->getData('handle');
        // only show if the handle is specified
        if ($handle) {
            if (substr($handle, 0, 1) === '@') {
                $handle = substr($handle, 1);
            return sprintf('<a href="">@%s</a>', $handle, $handle);
        return '';

It is a requirement that all widgets implement Mage_Widget_Block_Interface.

This specifies that our widget must implement the methods toHtml, addData and setData;

Fortunately, because we are extending Mage_Core_Block_Abstract the later two are already taken care of because that itself extends Varien_Object.

We could choose to extend Mage_Core_Block_Template instead and that would take care of toHtml. We would need to set a template for it to work but that is quite trivial (Hint: Use the _construct method).

For this purpose though I have implemented toHtml myself.


How does this look in the admin though?

Assuming you have set it up correctly, go to a cms block, click “insert widget” on the content area and you should see your new widget type in the list.

Once selected you will be asked to enter the “Handle” (e.g. @smartiewoo)

Once saved this will insert a widget into the content area that looks like { {widget type="[namespace]/twitter" handle="smartiewoo"}}

  • magento
  • widgets

Like this post? Share it :)

Related Posts