Before introducing Yii's built-in UI components, let's explain how to customize the components, which will also help you understand the use of cwidget, which is the Init () and run () methods of overloaded CWidget.
Class Mywidget extends CWidget
{public
function init ()
{
//This method will be called by Ccontroller::beginwidget ()
} Public
function run ()
{
//This method will be called by Ccontroller::endwidget ()}
This example defines a range of input UI components-rangeinputfield by extending Cinputwidget, which allows the user to enter two digits to define a domain. Cinputwidget supports the use of Cmodel or direct use of variables, Rangeinputfield also retains this tradition.
Rangeinputfield defines three sets of properties.
$attributeFrom and $attributeTo are used for Cmodel, in conjunction with cHTML activexxx methods, activexxx can automatically generate text box labels and text boxes.
Property $namefrom, $nameTo, $valueFrom, $valueTo the programmer can customize the label of the text box.
According to the default directory structure for YII application, the newly created Rangeinputfield are placed under the Protected/components directory, so create protected/components/rangeinputfield.php
Class Rangeinputfield extends Cinputwidget {public $attributeFrom;
Public $attributeTo;
Public $nameFrom;
Public $nameTo;
Public $valueFrom;
Public $valueTo; function Run () {if ($this->hasmodel ()) {echo Chtml::activetextfiel
D ($this->model, $this->attributefrom);
Echo '-> ';
Echo Chtml::activetextfield ($this->model, $this->attributeto);
}else {echo Chtml::textfield ($this->namefrom, $this->valuefrom);
Echo '-> ';
Echo Chtml::textfield ($this->nameto, $this->valueto);
}/** * @return Boolean whether this widget * are associated with a data model. */protected function Hasmodel ()
{return $this->model instanceof Cmodel && $this->attributefrom!==nul
L && $this->attributeto!==null; }
}
This customizes a new UI component Rangeinputfield, only overloads the Run method, and Init uses the methods in its parent class.
Here's how to test this newly created custom UI component, Rangeinputfield, using the Formmodel (Cmodel) method to use this UI component.
Create a rangefrom.php under Protected/models
Class Rangeform extends Cformmodel
{public
$from;
public $to;
function rules ()
{return
array (
' from,to ', ' numerical ', ' integeronly ' =>true),
Array (' From ', ' compare ', ' compareattribute ' => ' to ',
' operator ' => ' <= ', ' Skiponerror ' => true)
;
}
Then modify the default controller default method, protected/controllers/sitecontroller.php the Actionindex method.
Public Function Actionindex ()
{
$success =false;
$model =new rangeform ();
if (!emptyempty ($_post[' rangeform '))
{
$model->attributes=$_post[' Rangeform '];
if ($model->validate ()) $success =true
}
$this->render (' index ', array (
' model ' => $model,
' success ' => $success,
));
}