Search code examples
phpyiiclistview

CHtml:Link in CListView


I am new to Yii. In one of my page I am using the below code to list company names as link.

<?php 
  $ads = Ads::model()->findAll();
  foreach ($ads as $ad)
  {
  ?>
    <li>
  <?php
    echo CHtml::link($ad->company,array('/user/ads/view/id/'.$ad->id.'/')).'<br>';                                                                                                                                          ?>
    </li>
 <?php
  }
 ?>

I want to change it to CListView.
please somebody help me..


Solution

  • CListView expects an ActiveDataProvider, so you should change your code to something like this:

    <?php 
        $ads = new Ads; // and then use the search() method to return an activedataprovider
        $this->widget('zii.widgets.CListView', array(
            'dataProvider' => $ads->search(),
            'itemView' => '_myview',
            'id' => 'blogslistview',       
    )); 
    ?>
    

    This wil render the _myview.php for each record. In the _myview.php file you can access the records attributes with $data->myattribute

    So your _myview.php could look something like this:

    <li>
    <?php
    echo CHtml::link($data->company, array('/user/ads/view/id/' . $data->id . '/'));
    ?>
    </li>
    

    More info:

    http://www.yiiframework.com/doc/api/1.1/CListView http://www.yiiframework.com/doc/api/1.1/CActiveDataProvider