M
M
Madion2015-06-08 22:56:07
Yii
Madion, 2015-06-08 22:56:07

How to put filter and sort on CGridView column?

Evening in the hut, dear! Please help me with my question.
The following method has been added to the product model - it determines how many percent of the fields in the product are filled (if at least one picture is added, then +33.3%, if there is a description, then +33.3%, if parameters are added, then +33.3%):

public function getPrcFilling() {
    $result = 0;
    if ( count($this->images) ) { 
      $result += 33.3;
    }
    if ( count($this->params) ) {
      $result += 33.3;
    }
    if ( $this->description != '' ) {
      $result += 33.3;
    }
    return round($result);
  }

as well as:
public function relations()
  {
    return array(
      'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
      'StoreProducts' => array(self::HAS_MANY, 'StoreProducts', array('product_id' => 'id')),
      'params' => array(self::HAS_MANY, 'ProductParams', array('product_id' => 'id')),
      'images' => array(self::HAS_MANY, 'ProductImages', array('product_id' => 'id')),
    );
  }

then added a column to the CGridView:
array(
        'name' => 'prc',
            'header' => '%',
      'value' => '$data->getPrcFilling()',
      'htmlOptions' => array('width' => 10, 'align' => 'center'),
      'filter'=> CHtml::listData(
                      array(
                          0 => array(
                    'id' => 0,
                    'title'=>'0%',
                ),
                1 => array(
                    'id' => 1,
                    'title'=>'34%',
                ),
                2 => array(
                    'id' => 2,
                    'title'=>'67%',
                ),
                3 => array(
                    'id' => 3,
                    'title'=>'100%',
                ),
              ), 
              'id',
              'title'
                  ),
    ),

How can I sort and filter by this column?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vyachin, 2015-06-11
@vyachin

The best option is not to calculate this percentage each time by reading the number of images and parameters from the database, but to store it in a separate field for the product. Then:
1. sorting becomes simple
2. speed is increased by reducing the number of queries to the database
3. filtering is also easy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question