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?
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
)); ?>
Creating a widget is very simple in Yii. It couldn't be better explained than in the following short official documentation section, Here.
I little emphasis as lots of people found this answer useful. The following words are at my own taste, how I prefer designing my Yii application building blocks: when building your widget class always bear in mind that a widget is a kind of a view in Yii (v1.x). Its not supposed to process stuff, to perform important business logic decisions. Rather, as a view it merely supposed to render stuff. The decision making code in it should be focused in finding out what to render. I used to design in the past widgets that included some AJAX processing. Today I think this is bad design. A widget should render stuff. Need an accompanying processing unit? I would pack it all in a module, with controllers, possibly model classes, and the widget as an extension in that module. Cest tout :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With