Monday, 20 June 2016

CGridView Multiple rows update , Bulk Update of records in YII

By keeping a simple check box before each record in CGridView we can achieve bulk update of records. User can check the selected records and click on UpdateALL button , this is very useful when multiple records having same data to update. Here in this case we are having File Monitoting System . The Inward section receives more than 200 files daily and in which some files belongs to same section with same PR Number so instead of updating each file and giving the file number and forwarding to section, User can simply select the files and update the selected files at once.




1. To achieve above, first we design the view part. So in the admin view of the main table (here say it      is files) then the path would be >application_folder/protected/views/files/admin.php , Open the
     file in which we have a CGridView defined already

     First note the user about this simple action, the below statements is for that purpose only

   <b><font color="red"> Bulk Update: </font> Select same file number inward list by clicking the    check boxes beside inward numbers and then click new button "Update ALL" give all the     
   required fields and click save </b> 

   Then we need a Button with label "Update ALL" in our view,
   
   <?php
            $baseUrl = Yii::app()->baseUrl;
            $imgpath = $baseUrl.'/images/new.gif';
    ?>
   <div class="row buttons">
    <center>
        <table border='0'><tr>
             <td> <img src="<?php echo $imgpath ?>" /></td>
             <td><?php echo CHtml::button('Update 
                                           ALL',array('name'=>'btnupdateall','class'=>'updateall-button')); ?>
            </td>
         </tr></table>
    </center>
    </div>

   Now we need to register a client script (JQuery script) for the button, Please add the following underlined lines to the script.
 <?php
       Yii::app()->clientScript->registerScript('search', "
        $('.search-button').click(function(){
$('.search-form').toggle();
return false;
      });
      $('.search-form form').submit(function(){
p$('#inward-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
      });
      $('.updateall-button').click(function(){
       var atLeastOneIsChecked = $('input[name=\"inward-grid_c0[]\"]:checked').length > 0;
        if (!atLeastOneIsChecked)
        {
                alert('Please select atleast one inward number to Update');
        }
        else if (window.confirm('Are you sure you want to Update ALL the selected inward files?'))
        {
                document.getElementById('inward-search-form').action='index.php?r=inward/updateall';
                document.getElementById('inward-search-form').submit();
        }
      });
      ");
  ?>

and Now in columns of the CGridView  add a check box before the file number field

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'inward-grid',
'selectableRows'=>2,   // Two means many 0 means none
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
        array(
                    'value'=>'$data->inw_no',
                    'class'=>'CCheckBoxColumn',
                    ),
'inw_no',

Now the check box is added to the gridview.

2. The Action Part:  We have defined the action for the UpdateALL button in our view now we have        to write the action in our controller i.e., inward controller. (note the above highlighted text
      action=index.php?r=inward/updateall)

     ////////////////////////////////// UPDATE ALL ////////////////////////////////////////////////////

     public function actionUpdateall()
    {
   $session=new CHttpSession;
        if (isset($_POST['inward-grid_c0']))
        {
               $session->open();
               $session['sel'] = $_POST['inward-grid_c0'];
        }
       
       // if(isset($_POST['inward-grid_c0']))
        if(isset($session['sel']))
        {
                $upd_inws = $session['sel'];
// $upd_inws = $_POST['inward-grid_c0'];
                $uname=Yii::app()->user->name;
                $baseUrl = Yii::app()->baseUrl;
                $cs = Yii::app()->getClientScript();

                $cs->registerScriptFile($baseUrl.'/js/utility.js');
                $cs->registerScriptFile($baseUrl.'/js/validations.js'); 
                
                /* $model_inw=new Inward;
                $model_inwTrans = new InwTrans; */
                $model = new Inward;
            $cnt=count($_POST);
            $isinw = isset($_POST['Inward']);
                //if(isset($_POST['Inward']))
                
                //if(isset($_POST['Inward']))
                if(isset($_POST['frender']))
                {
                                             
                        $model->attributes=$_POST['Inward'];
                        $valid = true;

                        if(($uname<>'record.collectorate') and 
                                ($model->sec_fno!='' or $model->sec_fno!=null) or 
                                ($model->sec_year!='' or $model->sec_year!=null)){
                                //$model->scenario='PR';
                           if(($model->sec_fno!='')and($model->sec_year!='')){
                            $valid=true;
                           }else{
                            $valid=false;
                           }
                        }
                      
                        if(($uname==='record.collectorate') and $model->clo_yn==='Y'){
                           // $model->scenario='finalization';
                        if(($model->sec_fno!='')and($model->sec_year!='')and($model->nfp!='')
                        and($model->cfp!='')and($model->tot!='')and($model->clo_date!='')and
                        ($model->clo_cat!='')){
                        $valid=true;
                        }else{
                        $valid=false;
                        }
                        }
                            

                           // Dialog::message('Model',"model attributed $model->sec_fno");

                        if($valid){
// Dialog::message('title',"username is $uname");
$curYear= date('Y');
$model->sec_year = $curYear - $model->sec_year;
                               foreach ($upd_inws as $inwno){
                                $umodel = Inward::model()->findByPk($inwno);
                              //  Dialog::message('INFO',"Got Inward number $umodel->inw_no");
                                 if($umodel->updateallFields($model)){
                                        $umodel->save();
                                  }
                               } 
                               $session->close();

// destroys all data registered to a session.
                       //  $session->destroy();
                      //$this->actionAdmin();
                      Dialog::message('INFO', "Records Saved Successfully Click Home button before proceeding");
                               $searchModel=new Inward('search');
                               $searchModel->unsetAttributes();  // clear any default values
  $searchModel->sec_fno=$model->sec_fno;
  $searchModel->sec_year=$model->sec_year;
                      $this->render('admin',array(
    'model'=>$searchModel,
      ));
                        }else{
                       
                          Dialog::message('ERROR', "unable to save Please Enter all the fields");
                       /*  $process = Yii::app()->createController('FirstController'); //create instance of controller
                         $process->test1();  */
                        // InwardController::errorpage();
                           $this->render('errorpage');
                        }

                     
                }else{
               
                 $this->render('updateall',array(
                        'model'=>$model,
                 ));
                }
        }
        else
        {
                //Yii::app()->user->setFlash('error', 'Please select at least one record to Update.');
          Dialog::message('ERROR', "Please select at least one record to Update.");
          $model = new Inward;
               $this->render('admin',array(
   'model'=>$model,
      ));
        }               
    }
////////////////////////////////////////////////////////////////////////////////////////////////////

3. Finally the UpdateAll view has to be created with the fields which are common for the files. ie., in our views/app_folder/updateall.php



//////////////////////////////// updateall.php  ////////////////////////////////////////////////////

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'inward-form',
        'enableAjaxValidation'=>false,
        'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>

<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<center>
<?php 
     $uname=Yii::app()->user->name;
?>
<table id="withborder" border=0 cellspacing=0 cellpadding=0 bgcolor="lightblue">
<tr><td>
<table border=0 cellspacing=0 cellpadding=0 bgcolor="lightblue">
<div class="row"> <tr><td>
                <?php echo $form->labelEx($model,'PR Number'); ?>
</td><td>
<?php echo $form->textField($model,'sec_fno',array('size'=>8,'maxlength'=>11)); ?>
<?php echo $form->error($model,'Sec. Asst.'); ?>
<?php echo "PR year"; ?>
   <?php  
$curYear= date('Y');
$prevYear = $curYear-5;
   echo $form->dropDownList ($model, 'sec_year', range($curYear,$prevYear), array('prompt'=>'Select Year'));  ?>
  <?php echo $form->error($model,'sub_scode'); ?>
</td>
</tr>
</div>
<?php
    if($uname<>'record.collectorate'){
?>
 <div class="row">
   <tr><td>
                <?php echo $form->labelEx($model,'Forward to --->'); ?>
      </td><td>
 <?php echo $form->dropDownList($model, 'sec_code' , CHtml::listData(Sections::model()->findAll(), 'sec_code', 'sec_name'),
                        array(
                                'prompt'=>'Select Section',
                                'ajax'=> array(
                                'type' => 'POST',
                                'url'=>CController::createUrl('Inward/Sec'),
                                'update'=>'#'.CHtml::activeId($model,'sub_scode'),
                                )
                        )
                    );
        ?>
                <?php echo $form->error($model,'Sec. Asst.'); ?>
          <?php echo "Sec.Asst."; ?>

 <?php echo $form->DropDownList($model,'sub_scode',CHtml::listData(SubSections::model()->findAllByAttributes(array('sec_code'=>$model->sec_code)),'sub_scode','sub_section'),array('prompt'=>'Select Subsection')); ?>
                <?php echo $form->error($model,'sub_scode'); ?>
         </td>
        </tr>
    </div>

 <div class="row">
                <tr>
                <td>
                <?php echo $form->labelEx($model,'File Status'); ?>
                </td>
                <td>
                <?php echo $form->textField($model,'filestatus',array('size'=>50,'maxlength'=>300)); ?>
                            <?php echo $form->error($model,'filestatus'); ?>
                </td>
                </tr>
        </div>


        <div class="row">
                <tr>
                <td>
                <?php echo $form->labelEx($model,'Remarks'); ?>
                </td>
                <td>
                <?php echo $form->textField($model,'sec_rem',array('size'=>50,'maxlength'=>360)); ?>
                            <?php echo $form->error($model,'sec_rem'); ?>
                </td>
                </tr>
        </div>
<?php } ?>
<?php   $tuname=Yii::app()->user->name; ?>

<?php  if($tuname=='record.collectorate') { ?>

<tr>
        <div class="row">
        <td>
<?php echo $form->labelEx($model,'close the file?'); ?> 
</td> <td>
<?php echo $form->dropDownList($model,'clo_yn',
array('N' =>'No', 'Y'=> 'Yes'),
array(
'ajax'=>array(
          'type'=>'POST',
          'url'=>CController::createUrl('Inward/Dis'),
          'update'=>'#description_id',
)));
?>
        </td>
</div>
</tr>

</table>
<table border=0 cellspacing=0 cellpadding=0 bgcolor="lightblue">
<?php $tc=$model->clo_yn; ?>
<tr>
<td>
<div id="description_id">
<?php if($tc=='Y'){ ?>

<?php
echo "<table>";
echo "<tr><td>";
echo "<b>Close type</b>";
echo "</td>";
echo "<td>";
echo $form->dropDownList($model,'clo_cat',array('D'=>'D','L'=>'L','N'=>'N','R'=>'R'),array('prompt'=>'Select Dis'));
echo "</td>";
echo "</tr>";
echo "<tr><td>";
echo "<b>Closing Date <br/> (Year-Mon-Date)</b>";
echo "</td>";
echo "<td>";
 echo $form->textField($model,'clo_date',array('size'=>30,'maxlength'=>30));
echo "</td>";
echo "</tr>";
echo "<tr><td>";
echo "<b>NFP</b>";
echo "</td>";
echo "<td>";
 echo $form->textField($model,'nfp',array('size'=>10,'maxlength'=>10));
echo "</td>";
echo "</tr>";
echo "<tr><td>";
echo "<b>CFP</b>";
echo "</td>";
echo "<td>";
echo $form->textField($model,'cfp',array('size'=>10,'maxlength'=>10));
echo "</td>";
echo "</tr>";
echo "<tr><td>";
echo "<b>Total</b>";
echo "</td>";
echo "<td>";
echo $form->textField($model,'tot',array('size'=>10,'maxlength'=>10));
echo "</td>";
echo "</tr>";
echo "<tr><td>";
echo "<b>Remarks</b>";
echo "</td>";
echo "<td>";
 echo $form->textField($model,'clo_rem',array('size'=>45,'maxlength'=>360));
echo $form->error($model,'clo_rem'); 
echo "</td>";
echo "</tr>";
echo "</table>";
?>

<?php } ?>
</div>
</td>
</tr>
<?php  }
echo CHtml::hiddenField('frender' , '1', array('id' => 'frender'));

 ?>
<?php /// END OF CLOSING IF for RECORD SECTION ?>

        <div class="row buttons">
         <tr>
           <td><td>
           <td align="left">
                <?php echo CHtml::submitButton($model->isNewRecord ? 'Save' : 'Save'); ?>
                <?php // echo CHtml::button('Save',array('submit' => array('inward/updateall'))); ?>
           </td>
        </tr>
        </div>
</table>
</td>
</tr>
</table>

<?php $this->endWidget(); ?>

</div><!-- form -->

</center>

Thats it.. I have done for my example with defined fields, change the fields according to your requirement.

GOOD LUCK!!!

Thursday, 24 March 2016

Model rules for date validation and triming the values before validation

Today I faced problem with validating date fields .

I am accepting date using CJuiDateTimepicker it is working fine, but when I gave regular expression to validate a date field. It is giving error even for the valid date.

The main cause for the above situation is the DatePicker picking up date and a space appended to the date at the end of date. However we have 'date' datatype in mysql for these fields so the dates are automatically trimmed and saved in DB perfectly.

But to validate the dates we have define the rules as below

array('heardt,fdate,secdt,judgedt,nheardt,mandsurdt,leactdt,serorddt,dispdt', 'filter', 'filter'=>'trim'),    // This will trim the values
            array('heardt,fdate,secdt,judgedt,nheardt,mandsurdt,leactdt,serorddt,dispdt','match' ,'pattern'=> '/^([0-9]{4})-([0-1]{0,1}[0-9]{1})-([0-3]{0,1}[0-9]{1})$/','allowEmpty'=>true,'message'=> 'Date Format is YYYY-MM-DD'),
/* The above one validates the format of date. This format accepts 0000-00-00 as date */

array('dispdt','match','pattern'=> '/^([0-9]{4})-([0-1]{0,1}[0-9]{1})-([0-3]{0,1}[0-9]{1})$/','allowEmpty'=>false, 'message'=>'Disposed date mandatory when case is disposed','on'=>'disposed'),

/* The above one works when $model->scenario is assaigned to disposed. */

By this we can validate the dates using model rules

Wednesday, 23 March 2016

End Date should be greater than Start Date using CJuiDatePicker

<?php 
echo $form->labelEx($model, 'start_date');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength
'class' => "input-small"
),
'options' => array(
'showAnim' => 'fold',
'dateFormat' => 'yy-mm-dd',
'changeMonth' => true,
'changeYear' => true,
'yearRange' => '2000:2099',
'onSelect' => 'js:function( selectedDate ) {
    // #end_date is the ID of end_date input text field
    $("#end_date").datepicker( "option", "minDate", selectedDate );
     }',
    ),
));

echo $form->labelEx($model, 'end_date');            
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength                        
'class' => "input-small"
),
'options' => array(
'showAnim' => 'fold',
'dateFormat' => 'yy-mm-dd',
'changeMonth' => true,
'changeYear' => true,
),
));
            
?>

Saturday, 19 March 2016

Ajax Partial Rendering in YII rendering calender controls and partial views

Lets consider a senario such that certain controls to be displayed based on selection of dropdown in which it may contain calender controls (such as CJUIDateTimePicker) or a ajax calls which in turns calls another view. To achieve the above situation

In my case , While entering land details the user selects "whether regularization applied?" column to Yes/NO selection.
If Yes then we have to accept the "date of application" and again We need to know whether "Depreciation Claimed or not by the applicant" and , If yes then we have to accept the reasons and date from the user.
For this, I have main model "land" which consists fields "reg_applied varchar(1) , app_dt date, dclaimed varchar(1) , reasons varchar(300) and finally dcdate date."

First we have _createform.php (app_folder\protected\views\land\_createform.php):

<?php echo $form->dropDownList($model,'reg_applied',array('N'=>'NO','Y'=>'YES'),  
        array('prompt'=>'Select',

                    'ajax'=>array( 'type'=>'POST',   
                   'url'=>CController::createUrl('Land/areg',array('id'=>$model->id)), 
                      'update'=>'#areg', 

          ))); ?>  
        <?php echo $form->error($model,'reg_applied'); ?>

<div id="areg">   
</div>

In above dropdown we defined a ajax call to the action 'areg' . and updates the div content which is having id as 'areg'.

Now we have to define the action 'areg' in our LandController.php (app_folder\protected\controller\LandController.php)

public function actionAreg($id){ 
        if(($id==null)or($id=='')or(empty($id)))  
            $model=new Land; 
        else 
            $model=$this->loadModel($id); 
        $stat=$_POST['Land']['reg_applied'];
       $output=$this->renderPartial('_areg',array('model'=>$model,'stat'=>$stat),true,true);
        echo $output;     
}                               

Now we have to define our partial form i.e., nothing but "_areg.php" in our views folder (app_folder\protected\views\land\_areg.php)

<?php if(strtoupper($stat)=='Y'){    /* This is defined in controller and we are passing as argument  in the render partial method */  ?>
<table>
<tr>
<td><b> If Yes (applied) - </b></td>
<td><b>Date of application </b></td>
<td>
    <?php                                                                                                                         
                     $this->widget('zii.widgets.jui.CJuiDatePicker',array(                  
            'model'=>$model,
            'attribute'=>'app_dt',
            'value'=>date('Y-m-d',strtotime($model->app_dt)),
            'language'=>'',
            'options'=>array(
                'showAnim'=>'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
                    //    'showAnim'=>'slideDown',
                'showHour'=>false,
                'showMinute'=>false,
                'showTime'=>false,
                'changeMonth'=>true,
                'changeYear'=>true,
                'dateFormat'=>'yy-mm-dd',
                'timeFormat'=>'',
                'showButtonPanel'=>true,
            ),
            'htmlOptions'=>array(   
            'style'=>'height:20px;'
        ),
));
?>
</td>

<td><b>Depreciation Claimed</b></td>
<td>
            <?php echo CHtml::dropDownList('Land[
dclaimed]',"$model->dclaimed",
                    array('N'=>'NO','Y'=>'YES'),
                    array('ajax'=>array(
                      'type'=>'POST',
                      'url'=>CController::createUrl('Land/dclaim',array('id'=>$model->id)),
                      'update'=>'#dclaim',
                    ))
                    );?>
</td>

</tr>
<tr>
<td colspan='5'>
</td>
<div id="dclaim">
    </div>

</tr>
</table>


Here in the above partial form we are calling another ajax call for the dropdown dclaimed. Remember We have to know whether "Depreciation Claimed or not by the applicant" and , If claimed then we have to accept the reasons and date from the user.To acheive this we are calling ajax call and we have to handle the code that if claimed ie., $model->dclaimed =='Y' then we have to display the fields reasons and date

Again move to controller (our LandController.php) and define the action dclaim (app_folder\protected\controller\LandController.php)

public function actionDclaim($id){
        if(($id==null)or($id=='')or(empty($id)))
            $model=new Land;
        else
            $model=$this->loadModel($id);
        $stat=$_POST['Land']['dclaimed'];
        $output=$this->renderPartial('_dclaim',array('model'=>$model,'stat'=>$stat),true,true);
        echo $output;
    }


and here we are rendering partial view dclaim , remember the view elements which are showing are shown in the position where our div dclaim defined. So we have to customize the positions of controls according to our requirement

Now define partial view (app_folder\protected\views\land\_dclaim.php)

<?php if(strtoupper($stat)=='Y'){ ?>
<table>
<tr>
<td rowspan="2"><b> If Yes </b></td>
<td colspan="1"><b>Details</b></td>
<td colspan="3">
    <?php echo CHtml::textArea('Land[reasons]', "$model->details",array('rows'=>4,'cols'=>40,'style'=>'width:270px;height:80px;')); ?>
    </td>
    </tr><tr>
<td><b>Date of Execution </b></td>
<td>

    <?php
             $this->widget('zii.widgets.jui.CJuiDatePicker',array(
            'model'=>$model,
            'attribute'=>'dcdate',
            'value'=>date('Y-m-d',strtotime($model->dcdate)),
            'language'=>'',
            'options'=>array(
                'showAnim'=>'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
                    //    'showAnim'=>'slideDown',
                'showHour'=>false,
                'showMinute'=>false,
                'showTime'=>false,
                'changeMonth'=>true,
                'changeYear'=>true,
                'dateFormat'=>'yy-mm-dd',
                'timeFormat'=>'',
                'showButtonPanel'=>true,
            ),
            'htmlOptions'=>array(  
            'style'=>'height:20px;'
        ),
));
?>
</td>
</tr>
</table>

<?php } ?>

and finally don't forget to define access rules for the above two actions ie.,

public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view','areg','dclaim'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('admin','create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

Now, the requirement fulfilled up to entry level. We need to treat update screen differently, i.e., in create action simply we defined the controls to be displayed based on selection. But in update screen the selection was done already we have to show them directly on loading the screen in addition to the above actions defined. i.e., if the user selected "regularized" column as yes and given application date.

So in update form (app_folder\protected\views\land\_updateform.php), note we have same as _createform but the div 'areg' is defined here.

<?php echo $form->dropDownList($model,'reg_applied',array('N'=>'NO','Y'=>'YES'),  
        array('prompt'=>'Select',                                                                                                      

                    'ajax'=>array(                                                                                                             
                      'type'=>'POST',                                                                                                         
                      'url'=>CController::createUrl('Land/areg',array('id'=>$model->id)),           
                      'update'=>'#areg',                                                                                                     
                ))); ?>                                                                                                                                 
        <?php echo $form->error($model,'
reg_applied'); ?>                                                        
<div id="areg">  
            <?php $stat=$model->reg_applied; ?>
    <?php if(strtoupper($stat)=='Y'){ ?>
    <table>
    <tr>
    <td rowspan="4"><b> If Yes (applied) - </b></td>
    <td><b>Date of application </b></td>
    <td>
    <?php
            $this->widget('zii.widgets.jui.CJuiDatePicker',array(
            'model'=>$model,
            'attribute'=>'app_dt',
            'value'=>date('Y-m-d',strtotime($model->app_dt)),
            'language'=>'en-AU',
            'options'=>array(
                'showAnim'=>'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
                    //    'showAnim'=>'slideDown',
                'showHour'=>false,
                'showMinute'=>false,
                'showTime'=>false,
                'changeMonth'=>true,
                'changeYear'=>true,
                'dateFormat'=>'yy-mm-dd',
                'timeFormat'=>'',
                'showButtonPanel'=>true,
            ),
            'htmlOptions'=>array(  
            'style'=>'height:20px;'
        ),
        ));
        ?>
    </td>

<td><b>Depreciation Claimed</b></td>
<td>
            <?php echo $form->dropDownList($model,'dclaimed',
                    array('N'=>'NO','Y'=>'YES'),
                    array('ajax'=>array(
                      'type'=>'POST',
                      'url'=>CController::createUrl('Land/dclaim',array('id'=>$model->id)),
                      'update'=>'#dclaim',
                    ))
                    );?>
    </td>

</table>   
<?php } // End of condition ?>                                         
 </div> 

I have shown a example, similarly we have to do for "Depreciation Claimed" condition also. Otherwise the controls shown in ajax action only, but if in create action user have already given the date, etc., so before giving him/her provision to update we need to show them in the screen.

Hope this post is useful

Tuesday, 23 February 2016

Yii CHtml Controls and Examples

    CHtml::activeCheckBox()

    Generates a check box for a model attribute. The attribute is assumed to take either true or false value. If the attribute has input error, the input field's CSS class will be appended with errorCss.
    Syntax:
    public static string activeCheckBox(CModel $model, string $attribute, array $htmlOptions=array ( ))
    Example:
    $model = Post::model()->findByPk(1);
    echo CHtml::activeCheckBox($model, 'status', array('1'=>'Draft','2'=>'Publish'));

    CHtml::activeCheckBoxList()

    Generates a check box list for a model attribute. The model attribute value is used as the selection. If the attribute has input error, the input field's CSS class will be appended with errorCss.
    Syntax:
    public static string activeCheckBoxList(CModel $model, string $attribute, array $data, array $htmlOptions=array ( ))
    Example:
    /**
    Suppose that:
    1. category_id is an attribte of Post model.
    2. id, title are attribtes of Category model.
    */
     
    $model = Post::model()->findByPk(1);
    echo CHtml::activeCheckBoxList($model, 'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'title'));

    CHtml::button()

    Create a html button
    Syntax:
    public static string button(string $label='button', array $htmlOptions=array ( ))
    Example:
    echo CHtml::button('Submit', array('submit' => array('post/create')));

    CHtml::textField()

    Create a html textfield input.
    Syntax:
    public static function textField($name,$value='',$htmlOptions=array())
    Example:
    CHtml::textField('Text name', 'This is default value');

    CHtml::dropDownList()

    Generates a drop down list.
    Syntax:
    public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))
    Example:
    $selected = 1;
    echo CHtml::dropDownList('status', $selected, 
                  array('1' => 'Draft', '2' => 'Publish');

    CHtml::listOptions()

    Generates the list options.
    Syntax:
    public static string listOptions(mixed $selection, array $listData, array &$htmlOptions)
    Example:
    $selection = 'M'; // or 'F'
    $htmlOptions = array('id' => 'option_id');
    echo CHtml::listOptions($selection, 
                  array('M' => 'Male', 'F' => 'Female'),
                  $htmlOptions
                  );

    CHtml::listData()

    Generates the data suitable for list-based HTML elements. The generated data can be used in dropDownList, listBox, checkBoxList, radioButtonList, and their active-versions (such as activeDropDownList)
    Syntax:
    public static array listData(array $models, mixed $valueField, mixed $textField, mixed $groupField='')
    Example:
    $models = categories::model()->findAll();
    //format models resulting using listData     
    $category_list = CHtml::listData($models,'category_id', 'category_name');    
    print_r($category_list);

    CHtml::cdata()

    Encloses the given string within a CDATA tag.
    Syntax:
    public static string cdata(string $text)
    Example:
    <![CDATA[This is CData content]]>

    CHtml::label()

    Generates a label tag.
    Syntax:
    public static string label(string $label, string $for, array $htmlOptions=array ( ))
    Example:
    echo CHtml::label('Click here','checkbox-id');
    echo CHtml::checkbox('checkbox_name',true,array('id'=>'checkbox_id','class'=>'checkbox_class'));

    CHtml::checkBoxList()

    Generates a check box list. A check box list allows multiple selection, like listBox. As a result, the corresponding POST value is an array.
    Syntax:
    public static string checkBoxList(string $name, mixed $select, array $data, array $htmlOptions=array ( ))
    Example:
    echo "<strong>".CHtml::label('Simple Poll','checkbox-list-id') . "</strong><br>";
     
    echo CHtml::checkBoxList('checkbox_list_name', 'codexamples', array(
        'codexamples' => 'Codexamples.com',
        'google' => 'Google.com',
        'wikipedia' => 'Wikipedia.com',
        'youtube' =>'Youtube.com'
        ), 
    array('id'=>'checkbox-list-id','class'=>'checkboxlist'));

    CHtml::checkBox

    Generates a check box.
    Syntax:
    public static string checkBox(string $name, boolean $checked=false, array $htmlOptions=array ( ))
    Example:
    echo CHtml::label('Click here','checkbox-id');
    echo CHtml::checkbox('checkbox_name',true,array('id'=>'checkbox_id','class'=>'checkbox_class'));

    CHtml::link()

    Generating a link tag.
    Syntax:
    public static string link(string $text, mixed $url='#', array $htmlOptions=array ( ))
    Example:
    CHtml::link('Post Link',array('post/index'));

    CHtml::cssFile()

    Links to the specified CSS file.
    Syntax:
    public static string cssFile(string $url, string $media='')
    Example:
    $url = '/css/style.css';
    echo CHtml::cssFile($url,'screen');

    CHtml::dateField()

    Generates a date field input.
    Syntax:
    public static string dateField(string $name, string $value='', array $htmlOptions=array ( ))
    Example:
    echo CHtml::dateField('date_name',date("Y-m-d"),array('id'=>'date_id'));

    CHtml::emailField()

    Generates an email field input.
    Syntax:
    public static string emailField(string $name, string $value='', array $htmlOptions=array ( ))
    Example:
    echo CHtml::emailField('email_name','default@email.com',array('id'=>'date_id','placeholder'=>'Email field'));

    CHtml::error()

    Displays the first validation error for a model attribute.
    Syntax:
    public static string error(CModel $model, string $attribute, array $htmlOptions=array ( ))
    Example:
    echo $form->error($model,'attribute_name');

    CHtml::encodeArray()

    Encodes special characters in an array of strings into HTML entities. Both the array keys and values will be encoded if needed. If a value is an array, this method will also encode it recursively. The application charset will be used for encoding.
    Syntax:
    public static array encodeArray(array $data)
    Example:
    $array = array(
        'cat1'=>'<p>This is content of category number 1</p>',
        'cat2'=>'<p>This is content of category number 3</p>',
        );
     
    $encodeArray = CHtml::encodeArray($array);
    print_r($encodeArray);

    CHtml::fileField()

    Generates a file input. Note, you have to set the enclosing form's 'enctype' attribute to be 'multipart/form-data'. After the form is submitted, the uploaded file information can be obtained via $_FILES[$name] (see PHP documentation).
    Syntax:
    public static string fileField(string $name, string $value='', array $htmlOptions=array ( ))
    Example:
    echo CHtml::fileField('file_name','');

    CHtml::getIdByName()

    Generates a valid HTML ID based on name.
    Syntax:
    public static string getIdByName(string $name)
    Example:
    echo CHtml::getIdByName('title');

    CHtml::image()

    Generates an image tag.
    Syntax:
    public static string image(string $src, string $alt='', array $htmlOptions=array ( ))
    Example:
    echo CHtml::image('http://codexamples.com/themes/responsive/img/logo-dark.png','Code Examples',array(,'onclick'=>'js:alert("Welcome to Codexamples.com.\n This is Codexamples logo")'));