VariantColumn.php 2 KB
<?php
    
    namespace artbox\catalog\catalog\columns;
    
    use artbox\core\admin\grid\columns\Column;
    use yii\db\Query;
    use yii\helpers\Html;
    
    class VariantColumn extends Column
    {
        /**
         * Default options
         *
         * @var array
         */
        public $contentOptions = [
            'class' => 'number-adm',
        ];
        
        /**
         * @deprecated
         * @var array
         */
        public $filterOptions = [
            'class' => 'form-control',
        ];
        
        protected $variantCounts = [];
        
        public function init()
        {
            parent::init();
            
            $reader = ( new Query() )->select(
                [
                    'product_id',
                    'count(product_id) as count',
                ]
            )
                                     ->from('variant')
                                     ->groupBy('product_id')
                                     ->where(
                                         [
                                             'product_id' => $this->grid->dataProvider->getKeys(),
                                         ]
                                     )
                                     ->createCommand()
                                     ->query();
            while ($row = $reader->read()) {
                $this->variantCounts[ $row[ 'product_id' ] ] = $row[ 'count' ];
            }
        }
        
        /**
         * @inheritdoc
         *
         * @param mixed $model
         * @param mixed $key
         * @param int   $index
         *
         * @return string
         */
        protected function renderDataCellContent($model, $key, $index)
        {
            return $this->variantCounts[$key];
        }
        
        /**
         * @inheritdoc
         * @return string
         */
        public function renderFilterCell()
        {
            return Html::tag('td', $this->renderFilterCellContent(), []);
        }
    }