Social Icons

Pages

Monday, July 8, 2013

filter by concatenation of model fields in CGridView

I have user model with first_name and last_name . It will show as full name (first_name+last_name). Now i want to search in Cgridview.


class User extends CActiveRecord
{
        public $fullName;


in search

$criteria->addSearchCondition('concat(first_name, " ", last_name)', $this->fullName); 


in rules()
array('..., fullName', 'safe', 'on' => 'search'),

in model  created a function
 public function getFullName()
        {
                return $this->first_name . ' ' . $this->last_name;
        }

And last I've put it in my view:

<?php $this->widget('zii.widgets.grid.CGridView', array(
      
        .......
          'columns' => array(
                array(
                        'name' => 'full_name',
                        'value' => '$data->getFullName()',
                ),
               
                ...


Tuesday, July 2, 2013

Yii ajax request and json response

This  will help you to understand the details of yii ajax request and response from controller.

In view.php


<?php
Yii::app()->clientScript->registerScript('productform','
$("#category").live("change",function(){
 $.ajax({
   url:'".Yii::app()->createAbsoluteUrl("site/productlist")."',
   type:"POST",        
   data:"catid="+$("#Cat_id option:selected").val(),
   dataType:"json",
   "success":function(data){            
         if(data==null){
              $("#product_type").empty();
         }else{
              var obj = eval(data);
              $("#product_type").empty();
              $.each(obj, function(key, value) {
                 $("#product_type").append("<option value="+key+">"+value+"</option>");
              });
                 
         }
       }
      });
    });
');
?>


<div class="row">
<?php echo $form->labelEx($model,'category'); ?>
<?php echo $form->dropDownList($model,'category',$categorylist); ?>
<?php echo $form->error($model,'category'); ?>
 </div>

<div class="row">
<?php echo $form->labelEx($model,'product_type'); ?>
<?php echo $form->dropDownList($model,'product_type',
                                array(''=>'Select Product')); ?>
<?php echo $form->error($model,'product_type'); ?>
 </div>
?>






controller.php


<php
class SiteController extends Controller
{
public function actionProductlist()
 {
  if(Yii::app()->request->isPostRequest)
  {
    if(isset($_POST['catid']) && $_POST['catid']!=''){
       $Productmodel=Product::model()->
                         findAll(array('condition'=>'isactive=1 and 
                         catid='.$_POST['catid'],'order'=>'name'));
       if($Productmodel){
          $data=CHtml::listData($Productmodel,'productid','name');
          print_r(json_encode($data));
       }
    }
  }
  else
   throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
 }
}
?>