Yii2基于过滤选项

时间:2015-09-30 09:51:49

标签: php gridview yii2

我在单选按钮上放置了GridView和6个过滤器选项。点击过滤器后,GridView会根据点击的过滤器发生变化。这是一张图片:

enter image description here

现在,我希望根据所选的过滤器获取表格的总Converted Amount。例如,如果我选择Draft过滤器,则该表格将显示所有Draft个报销,并将其Converted Amount汇总,并且总计将放置在表格上方的右上角,如下所示照片。

我尝试使用谷歌搜索解决方案,但我找不到答案。这是我控制器中代码的一小部分:

$refreshData = false;

if (isset(Yii::$app->request->getBodyParams()['sortby'])) {
    $refreshData = true;
    $sortby = Yii::$app->request->getBodyParams()['sortby'];
} else {
    $sortby = 'Show All';
    $dataProvider = new ActiveDataProvider([
        'query' => Reimbursement::find()->where(['company_id' => new \MongoId($session['company_id'])])
    ]);
}

// get all reimbursements
$reimbursements = Reimbursement::findAll(['company_id' => new \MongoId($session['company_id'])]);

if (isset(Yii::$app->request->getBodyParams()['sortby'])) {
    if(Yii::$app->request->getBodyParams()['sortby'] != '' && Yii::$app->request->getBodyParams()['sortby'] != 'Show All') {
        $refreshData = true;
        $reimbursements = Reimbursement::findAll(['company_id' => new \MongoId($session['company_id']), 'status' => Yii::$app->request->getBodyParams()['sortby']]);
        // $ids = [];
        // foreach ($reimbursements as $i => $model) {
        //     $ids[] = $model['_id'];
        // }

        // $command = Yii::$app->db->createCommand('SELECT sum(total) FROM estimate WHERE `_id` IN ('.implode(',',$ids).')'); // please use a prepared statement instead, just a proof of concept
        // $sum = $command->queryScalar();
    } elseif (Yii::$app->request->getBodyParams()['sortby'] == 'Show All') { 
        $refreshData = true;
    }
}

$dataProvider = new ArrayDataProvider([
    'allModels' => $reimbursements,
]);

if($refreshData) {
    return $this->renderPartial('_index', [
        'dataProvider' => $dataProvider, 
    ]);
}

$dataProvider->pagination->pageSize = 10;
return $this->render('index', [
    'searchModel' => $searchModel,
    'dataProvider' => $dataProvider,
    'rModel' => $rModel,
]);   

您可能已经注意到我在if(Yii::$app->request->getBodyParams()['sortby'] != '' && Yii::$app->request->getBodyParams()['sortby'] != 'Show All')条件下评论了一些代码行。我尝试了那个,它没有用。

我该如何实现?

1 个答案:

答案 0 :(得分:0)

        $reimbursements = Reimbursement::find()->where(['company_id' => new \MongoId($session['company_id'])]);

    if (isset(Yii::$app->request->getBodyParams()['sortby'])) {
        $refreshData = true;
        $sortby = Yii::$app->request->getBodyParams()['sortby'];
        $reimbursements->andWhere(['status' => Yii::$app->request->getBodyParams()['sortby']]);
    } else {
        $refreshData = false;
        $sortby = 'Show All';
    }

    $dataProvider = new ActiveDataProvider([
        'query' => $reimbursements,
    ]);

    $totalSum = $reimbursements->sum('total');