phpyiiclistview

display data for every n-th data using clistview


how can i display data for every let's say odd entry? So first record Z, second record do Y, third record do Z, fourth do Y. or lets say i get from model every nth record, and another that does n-1?

public function getNewItem()//for main page grids
    {
        $criteria = new CDbCriteria;

        $criteria->order = 'posted_date DESC';
        $criteria->compare('product_status',"Y");
        $criteria->compare('product_approval_status',"Y");      
//????

        return new CActiveDataProvider( $this, array(
                'criteria'=>$criteria,
                'pagination'=>false,
        ));

    }

Solution

  • There are two ways to do this; depending on how complex your filtering needs to be;

    First method you can modify your criteria compare to filter by only odd or even records like this

            $criteria = new CDbCriteria;
    
            $criteria->order = 'posted_date DESC';
            $criteria->compare('product_status',"Y");
            $criteria->compare('product_approval_status',"Y");
    
            $criteria->addCondition('MOD(id,2)=1','AND');
    

    or any such condition to get the corresponding subset of records

    Second method is to filter it in the partial file you use in the CListView, I use this method to usually add additional code not for filtering, for example you want to add a new row every forth element, For this use the $indexand $widget variable made available in the itemView attribute in the CListView call with something like this.

    <?php if(($index)%6 == 0 || $index == 0 ){ ?>
         <div class="row">
    <?php } ?>
    
      // Regular view rendering code
      // ...
    
     <?php if(($index+1)%6 == 0 || ($index+1) == $widget->dataProvider->itemCount){ ?>
        </div>
    <?php }
    

    Here I have used this to insert a new div for every 6 items in the list or if its the first/last item This is useful for conditional rendering of items/ adding classes etc.