Ansari Khalid
Ansari Khalid

Reputation: 57

Yii2 ActiveDataProvider fetch result correct but showing totalCount 0 in summary text

I am trying to filter data using dropdown so the query executed perfectly produces a result is always correct but in summary total count is '0' always but not first time when page loaded. This is annoying me I am completely unable to trace the error through debugging tool.

But the important thing is that the same code is working fine on my local machine whenever I deployed the same code to production it shows 0 counts

My Model Code :

public function search($params) {

    $query = Tasks::find();

    $query->where(['q_id' => $this->job_id]);

    // $query->orderBy('created_at DESC');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => [
            'pageSize' => 20,
        ],
    ]);


    $this->load($params);

    if (!empty($this->keyword) || $this->keyword != '') {

        $query->andWhere('MATCH(task_title,task_description, priority) AGAINST("' . $this->keyword . '*" IN BOOLEAN MODE)');
    }

    if (is_numeric($this->filterby)) {
        $query->andFilterWhere(['status' => $this->filterby]);
    } else {
        $query->andFilterWhere(['IN', 'status', [10, 4, 2]]);
    }

    if (!empty($this->sortby) || $this->sortby != '') {
        $query->orderBy($this->sortby . ' DESC');
    }

    return $dataProvider;
}

This is my view code :

<?php
yii\widgets\Pjax::begin(['id' => 'tasks-pjax', 'timeout' => 10000]);
echo \yii\widgets\ListView::widget([
    'layout' => '{summary}<br/>{items}{pager}',
    'dataProvider' => $dataProvider,
    'summary' => '<div class="col-lg-12 hidden-xs"><p class="text-muted text-success"> {totalCount} Tasks Found!</p></div>',
    'summaryOptions' => ['style' => 'margin-bottom: 5px;margin-top:5px;', 'tag' => 'span'],
    'id' => 'tasks-list',
    'itemOptions' => ['class' => 'task-item'],
    'emptyText' => 'No Task Found !',
    'emptyTextOptions' => ['class' => 'list-group-item', 'style' => 'margin-left: 15px; margin-right:15px; color: red'],
    'itemView' => '_tasks',
    'pager' => [
        'class' => 'kop\y2sp\ScrollPager',
        'container' => '#tasks-list',
        'item' => '.task-item',
        // 'next' => '.next a',
        'triggerOffset' => 20,
        'noneLeftText' => '',
    ]
])
?>
<?php yii\widgets\Pjax::end(); ?>

Controller Code :

public function actionIndex() {

    $searchModel = new \frontend\models\TasksSearch();

    if (Yii::$app->request->get('q_id')) {
        $qModel = QPosts::findOne(['q_id' => base64_decode(Yii::$app->request->get('q_id'))]);
        $searchModel->q_id = $qModel->q_id;

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if (Yii::$app->user->identity->id == $qModel->user_id || Yii::$app->user->identity->id == $xxxModel->xxx_id) {
            return $this->render('index', [
                        'searchModel' => $searchModel,
                        'dataProvider' => $dataProvider,
                        'qModel' => $qModel,
            ]);
        } else {
            return $this->redirect(['xxxx/xxxx', 'id' => $qModel->q_id]);
        }
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Upvotes: 2

Views: 1440

Answers (2)

Steve M.
Steve M.

Reputation: 21

I had a similar issue. My activerecord query had a joinWith and I forgot to add a groupBy in the query so it was duplicating rows. I was using the ListView widget and it was getting the {items} {pager} or {summary} wrong (I forget). Anyway adding a groupBy on my query with a joinWith solved my issue.

Upvotes: 2

e-frank
e-frank

Reputation: 749

can you post your grid code? is there a pjax around? what is in your $dataProvider->models?

just a few other things i noticed, without answering your original question:

instead of

$query->orderBy($this->sortby . ' DESC');

try

$query->orderBy([$this->sortby => SORT_DESC]);

or what i am doing with states (open/closed/pending/cancelled, active=open or pending, inactive=closed or cancelled):

<?php
namespace common\models;
use Yii;

class Status
{
    const UNDEFINED = 0;
    const OPEN      = 1;
    const CLOSED    = 2;
    const CANCELLED = 4;
    const PENDING   = 8;

    const ACTIVE    = 9;
    const INACTIVE  = 6;


    static function asArray() {
        return [
            self::OPEN      => Yii::t('app', 'Open'),
            self::CLOSED    => Yii::t('app', 'Closed'),
            self::CANCELLED => Yii::t('app', 'Cancelled'),
            self::PENDING   => Yii::t('app', 'Pending'),
        ];
    }

    static function asFilter() {
        return [
            self::ACTIVE    => Yii::t('app', 'Active'),
            self::INACTIVE  => Yii::t('app', 'Inactive'),
            self::OPEN      => Yii::t('app', 'Open'),
            self::CLOSED    => Yii::t('app', 'Closed'),
            self::CANCELLED => Yii::t('app', 'Cancelled'),
            self::PENDING   => Yii::t('app', 'Pending'),
        ];
    }

}

in function search($params):

if (!empty($this->status))
    $query->andWhere('task.status & :status = task.status', [':status' => $this->status]);

a custom StatusColumn:

<?php
namespace common\grid;

use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\web\JsExpression;
use yii\web\View;
use yii\helpers\Url;
use common\models\Status;

class StatusColumn extends \yii\grid\DataColumn {

    public $attribute      = 'status';
    public $headerOptions  = ['class' => 'text-center', 'style' => 'width: 10em'];
    public $contentOptions = ['class' => 'text-center'];
    public $footerOptions  = ['class' => 'text-center'];

    private $sum1 = 0;
    private $sum2 = 0;

    public function renderDataCell($model, $key, $index) {
        $value      = $model->__get($this->attribute);
        $this->sum1 += ($value === null ? 0 : ($value & Status::ACTIVE ? 1 : 0));
        $this->sum2 += ($value === null ? 0 : ($value & Status::INACTIVE ? 1 : 0));
        return parent::renderDataCell($model, $key, $index);
    }

    protected function renderFooterCellContent() {
        $this->footer = sprintf('%d/%d', $this->sum1, $this->sum2);
        return parent::renderFooterCellContent();
    }

    public function init() {
        parent::init();

        if ($this->content === null) {
            $this->content = function($data, $key, $index) {
                $value = $data->__get($this->attribute);

                switch ($value) {
                    case Status::OPEN :
                        return sprintf('<div class="label label-primary">%s</div>', Yii::t('app', 'Open'));
                        break;

                    case Status::CLOSED :
                        return sprintf('<div class="label label-success">%s</div>', Yii::t('app', 'Closed'));
                        break;

                    case Status::CANCELLED :
                        return sprintf('<div class="label label-danger">%s</div>', Yii::t('app', 'Cancelled'));
                        break;

                    case Status::PENDING :
                        return sprintf('<div class="label label-info">%s</div>', Yii::t('app', 'Pending'));
                        break;

                    default:
                        return sprintf('<div class="label label-default">%s</div>', Yii::t('app', 'undefined'));
                        break;
                }

                return $value;
            };
        }

        if ($this->filter === null) {
            $this->filter = Status::asFilter(); 
        }

        if ($this->footer === null) {
            $sum1 = 0;
            $sum2 = 0;
            $this->footer = sprintf('%d/%d', $this->sum1, $this->sum2);
        }
    }
}

?>

and use it in grid:

    [
        'class' => 'common\grid\StatusColumn',
    ],

Upvotes: 0

Related Questions