8

I'd like to create 'widgets' in certain areas on my site, that can have certain parameters configurable by a non-technical Magento store admin. Widgets, by all descriptions sound like a nice way of doing this. All the adminhtml elements are in place to allow them to fill in the parameters without too much hassle.

What I can't work out though, is how to load and render a specific widget instance at a particular point in a template (as created via CMS > Widget > Add New Widget Instance and stored in widget_instance). I used the layout update feature to insert it into a block, which works reasonably well, but it's not quite flexible enough for what I wish to achieve.

Is it possible in a template file to load and render a widget instance?

2 Answers 2

9

Yes, you can do something like this:

$widget = Mage::getModel('widget/widget_instance')->load($widgetId);
$widgetBlock = $this
                   ->getLayout()
                   ->createBlock($widget->getType(),
                                 $widget->getTitle(),
                                 $widget->getWidgetParameters());
echo $widgetBlock->toHtml();
0
0

If you don't know your widget ID, you can use this, and its not limited to templates.

$collection = Mage::getModel('widget/widget_instance')->getCollection();
        $collection->addStoreFilter(Mage::app()->getStore()->getId(), false)
            ->addFieldToFilter('title', $filter)->load();

        $widget = $collection->getFirstItem(); 

        if($widget && is_numeric($widget->getId())) {
            $widgetBlock = Mage::app()->getLayout()
                ->createBlock(
                    $widget->getType(),
                    $widget->getTitle(),
                    $widget->getWidgetParameters()
                );
            return $widgetBlock;
        }
        return false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.