Steps to create a widget on Yii?

MEM picture MEM · Dec 9, 2011 · Viewed 36.2k times · Source

I have the following code on a given view:

<?php
    $form = $this->beginWidget('CActiveForm', array(
        'id' => 'home-newsletter-form',
        'enableAjaxValidation' => false,
        'enableClientValidation' => true,
            ));

    echo $form->textField($newsletterSubscribeForm, 'email');
    echo $form->error($newsletterSubscribeForm, 'email');
    echo CHtml::link("subscribe", "#", array('class'=>'btSubscribe'));
    $this->endWidget(); 
?>

It happens that I will need this on MORE then one view, so I find a widget a better option. I wish however to place this on a separate file (on app/widgets/ folder), and called on each view.

Can anyone please be kind enough to tell me what steps should we follow in order to achieve that?

Answer

emix picture emix · Jan 24, 2013

Widget is the best solution here, it will keep your code DRY (Don't Repeat Yourself - focus on re-usability) as well.

<?php

// protected/components/SubscriberFormWidget.php

class SubscriberFormWidget extends CWidget
{
    /**
     * @var CFormModel
     */
    public $form;

    public function run()
    {
        if (! $this->form instanceof CFormModel) {
            throw new RuntimeException('No valid form available.');
        }
        $this->render('subscriberFormWidget', array('form'=>$this->form));
    }
}

And the view:

<?php
// protected/components/views/subscriberFormWidget.php

$form = $this->beginWidget('CActiveForm', array(
    'id' => 'home-newsletter-form',
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
));

echo $form->textField($newsletterSubscribeForm, 'email');
echo $form->error($newsletterSubscribeForm, 'email');
echo CHtml::link("subscribe", "#", array('class'=>'btSubscribe'));
$this->endWidget();

sample usage inside any view

<?php $this->widget('SubscriberFormWidget', array(
        'form' => $newsletterSubscribeForm
)); ?>