我为自定义查询创建了网格视图。它对我来说很好,我必须在其中添加过滤器,但这对我不起作用。我该如何在其中添加过滤器?
这是我的所有代码。
控制器:DealController.php
public function actionAdmin() {
$filtersForm=new FiltersForm;
if (isset($_GET['FiltersForm']))
$filtersForm->filters=$_GET['FiltersForm'];
$sql = 'SELECT d.DealID,d.PromoCode,d.Title,d.Image,d.Description,
d.TOC,d.DealCategoryID,d.Discount,d.ValidityStart,d.ValidityEnd,
d.MerchantID,dc.CategName,pt.TierName,m.StoreName,
CASE WHEN d.DealType = 1 THEN "Normal"
WHEN d.DealType = 2 THEN "Birthday Special"
WHEN d.DealType = 3 THEN "Registration Deal" END AS DealType,
CASE WHEN d.Status = 1 THEN "Active" ELSE "InActive" END AS Status,
c.CategName AS MerchantCategory
FROM deal AS d
LEFT JOIN merchant AS m
ON m.MerchantID = d.MerchantID
LEFT JOIN category AS c
ON m.SubCategoryID = c.CategID
LEFT JOIN dealcategory AS dc
ON dc.CategID = d.DealCategoryID
LEFT JOIN dealpermission AS dp
ON dp.DealID = d.dealID
LEFT JOIN programtier AS pt
ON pt.TierID = dp.TierID
GROUP BY DealID';
$rawData = Yii::app()->db->createCommand($sql);
$rawDataWithArray = Yii::app()->db->createCommand($sql)->queryAll();
$filteredData=$filtersForm->filter($rawDataWithArray);
$count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM (' . $sql . ') as count_alias')->queryScalar();
$model = new CSqlDataProvider($rawData, array(
'keyField' => 'DealID',
'totalItemCount' => $count,
'sort' => array(
'attributes' => array(
'DealID','Merchant Category','Title','Image','Description',
'TOC','DealCategoryID','Discount','ValidityStart','ValidityEnd',
'DealType','MerchantID','Status','CategName','TierName','StoreName'
),
'defaultOrder' => array(
'DealID' => CSort::SORT_DESC,
),
),
'pagination' => array(
'pageSize' => 10,
),
));
$this->render('admin', array(
'model' => $model,'filtersForm' => $filtersForm,
));
}
查看:Admin.php
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'deal-grid',
'dataProvider' => $model,
'ajaxUpdate' => true,
'filter'=>$filtersForm,
'columns' => array(
array('header'=>'Title',
'value'=>'$data["Title"]',
'filter' => true,
),
array(
'header' => 'Image',
'value' => function($data) {
if($data['Image'] != '') {
return '<img src="'.Yii::app()->baseUrl.'/upload/deal/logo/'.$data['Image'].'" width="50" height="50" >';
}
},
'type' => 'raw',
'filter' => true,
),
array('header'=>'Merchant Category',
'value'=>'$data["MerchantCategory"] !="" ? $data["MerchantCategory"] : null',
'filter' => true,
),
array('header'=>'Merchant Name',
'value'=>'$data["StoreName"] !="" ? $data["StoreName"] : null',
'filter' => true,
),
array('header'=>'Promo Code',
'value'=>'$data["PromoCode"] !="" ? $data["PromoCode"] : null',
),
//'Description',
array (
'header' => 'Validity Start',
'value' => ' $data["ValidityStart"]!="0000-00-00 00:00:00" ? date("d-m-Y H:i:s",strtotime($data["ValidityStart"])) : null ',
),
array (
'header' => 'Validity End',
'value' => ' $data["ValidityEnd"]!="0000-00-00 00:00:00" ? date("d-m-Y H:i:s",strtotime($data["ValidityEnd"])) : null ',
),
array (
'header' => 'Membership Tier',
'value'=>' $data["TierName"]!="" ? $data["TierName"] : null ',
),
array (
'header' => 'Is Birthday Deal',
'value'=>' $data["DealType"]=="Birthday Special" ? "Yes" : "No" ',
),
array (
'header' => 'Status',
'value' => function($data) {
$status = $data["Status"];
if($status == 'Active') {
$statusClass = 'gridStatusSuccess';
$statusId = 2;
$title = "InActive";
} else if($status == 'InActive') {
$statusClass = 'gridStatusError';
$statusId = 1;
$title = "Active";
}
return '<span style="cursor:pointer" id="status-'.$data["DealID"].'" title="Click to '.$title.'" class="'.$statusClass.'" onclick="updateStatus('.$data["DealID"].','.$statusId.');">'.$status.'</span>
<img src="'.yii::app()->baseUrl.'/themes/abound/img/loading.gif" id="loading-'.$data["DealID"].'" style="display:none;width:25px;height:25px;" />';
},
//'filter' => $model->getStatus(),
'type' => 'raw'
),
array(
'class' => 'CButtonColumn',
'template' => '{update}{view}',
'buttons' => array(
'update' => array('url' => '$this->grid->controller->createUrl("update",array("id"=>$data["DealID"]))'),
'view' => array('url' => '$this->grid->controller->createUrl("view",array("id"=>$data["DealID"]))'),
),
),
FiltersForm.php
<?php
/**
* Filterform to use filters in combination with CArrayDataProvider and CGridView
* @see http://www.yiiframework.com/wiki/232/using-filters-with-cgridview-and-carraydataprovider/
*/
class FiltersForm extends CFormModel
{
/**
* @var array filters, key => filter string
*/
public $filters = array();
/**
* Override magic getter for filters
* @param string $name
*/
public function __get($name)
{
if (!array_key_exists($name, $this->filters)) {
$this->filters[$name] = '';
}
return $this->filters[$name];
}
/**
* Override magic setter for filters
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
$this->filters[$name] = $value;
}
/**
* Filter input array by key value pairs
* @param array $data rawData
* @return array filtered data array
*/
public function filter(array $data)
{
foreach ($data AS $rowIndex => $row) {
echo '<pre>';
print_r($this->filters);
die;
foreach ($this->filters AS $key => $searchValue) {
if (!is_null($searchValue) AND $searchValue !== '') {
$compareValue = null;
if ($row instanceof CModel) {
if (isset($row->$key) == false) {
throw new CException("Property " . get_class($row) . "::{$key} does not exist!");
}
$compareValue = $row->$key;
} elseif (is_array($row)) {
if (!array_key_exists($key, $row)) {
throw new CException("Key {$key} does not exist in array!");
}
$compareValue = $row[$key];
} else {
throw new CException("Data in CArrayDataProvider must be an array of arrays or an array of CModels!");
}
if (stripos($compareValue, $searchValue) === false) {
unset($data[$rowIndex]);
}
}
}
}
return $data;
}
}
),)); ?>
答案 0 :(得分:0)
答案 1 :(得分:0)
如果您想使用“Title,StoreName,PromoCode”属性进行过滤,请在模型中添加以下内容。
注意:添加您需要用于过滤的所有字段。
public function rules()
{
return array(
array('Title, StoreName, PromoCode, 'safe', 'on'=>'search'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('Title',$this->Title);
$criteria->compare('StoreName',$this->StoreName,true);
$criteria->compare('PromoCode',$this->PromoCode,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}