简体   繁体   中英

How to customize dataProvider using CListView in Yii

I'm trying to output data into the CListView of the current user only. So far, if I put in the $dataProvider, it only outputs ALL the records from the database.

This is my current code:

    $current = Yii::app()->user->id;
    $currentid = Yii::app()->db->createCommand("select * from content where id = ". $current)->queryRow();

    $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider, //This is the original. I tried replacing it
                                   //with $currentid but errors.
    'itemView'=>'_view2',
    'template'=>'{items}<div>{pager}</div>',
    'ajaxUpdate'=>false,
    )); 

From what I understand from the Yii Documentations, $dataProvider stores all the data within the database and places it inside the dataProvider itself and my "_view2" uses that to output all the records.

My Controller codes for the showing/view is as follows:

 public function actionView()
{

    $post=$this->loadModel();
    if(Persons::model()->compare_country(explode("|",$post->country)))
    {
        $post->view_count = $post->view_count + 1;
        Yii::app()->db->createCommand("UPDATE content SET view_count = {$post->view_count} WHERE id = {$post->id}")->execute();
        //$post->save();
        $comment=$this->newComment($post, 'view');

        if (!empty(Yii::app()->session['announcement_message']))
        {
            Yii::app()->user->setFlash('message',Yii::app()->session['announcement_message']);
            Yii::app()->session['announcement_message'] = null;
        }

        $this->render('view',array(
            'model'=>$post,
            'comment'=>$comment,
            'view'=>'view',
        ));
    }
    else
    {
        $this->redirect(Yii::app()->createAbsoluteUrl('news/index',array('page'=>'1')));
    }
}

public function actionShow($id)
{
    $post=$this->loadModel($id);
    $comment=$this->newComment($post);
        $attachments=Attachments::model()->findAllByAttributes(array(
                'content_id' => $id,
                ));
    $this->render('show',array(
        'model'=>$post,
        'comment'=>$comment,
            'attachments'=>$attachments
    ));
}

If you wanted to see my _view2, these are my codes:

 <div class="profile-member-post-box announcement" >
<div class="events-post-bodytext profile-member-info">

    <?php $person=Persons::model()->findByAttributes(array('party_id'=>$data->party_id)); 

    if ($person->party_id === Yii::app()->user->id)
        {
    ?>
            <span><?=CHtml::link($data->title, array('view', 'id'=>$data->id), array('class' => 'titlelink'));?></span>
    <?php 
        $country=Lookup_codes::model()->findByAttributes(array('id'=>$person->country)); 
        $location = empty($country) ? '' : 'of '.$country->name;
        $sysUser=User::model()->findByAttributes(array('party_id'=>$data->party_id));

    ?>
    <p>
        By: <?php echo CHtml::link($person->getusername(), array('persons/view/id/'.$person->showViewLinkId())); ?>
        <span class="date2"> - <?php echo date('M j, Y',strtotime($data->date_created)); ?></span>
    </p>

            <div>
            <?php if(Yii::app()->partyroles->isAdmin() || ((get_access('Announcement','edit') && (Yii::app()->user->id == $data->party_id)) || (get_local_access('sub-admin','edit',$data->id)))):?>
                <a href="<?php echo Yii::app()->createUrl('announcement/update', array('id'=>$data["id"]))?>">Edit</a> | <?php endif;?> <?php echo (Yii::app()->partyroles->isAdmin() || (get_access('Announcement','delete') && (Yii::app()->user->id == $data->party_id)) || (get_local_access('sub-admin','delete',$data->id))) ? CHtml::link('Delete','#',array('submit'=>array('delete','id'=>$data["id"]),'confirm'=>'Are you sure you want to delete this item?')) : NULL?>
            </div>

    <?php
    }
    else
    ?>

</div>

I just need to be able to fix the view to show records only by the current user.

UPDATE!!------------

I'm going to add my actionIndex here:

 public function actionIndex()
{
    if(get_access('Announcement','view') || get_access('Announcement','view_local'))
    {
    $id = Yii::app()->user->id;
    $condition = Persons::model()->get_view_condition('Announcement');
    $criteria=new CDbCriteria(array(
        'condition'=>'1=1 '.$condition,
        'order'=>'date_modified DESC',
        'with'=>'commentCount',
    ));
    /*
    if(isset($_GET['tag']))
        $criteria->addSearchCondition('tags',$_GET['tag']);
 */

    $items=SystemParameters::model()->findAllByAttributes(array(
                'name' => 'blogs_per_page',
                ));

    $dataProvider=new CActiveDataProvider('Announcement', array(
        'pagination'=>array(
            'pageSize'=>strip_tags($items[0]->value),
        ),
        'criteria'=>$criteria,
    ));

   /* $dataProvider=new CActiveDataProvider('Announcement', array(
        'pagination'=>array(
            'pageSize'=>5,
        ),
        'criteria'=>$criteria,
    ));*/

    //$dataProvider=Announcement::model()->findAll();

    $attachments=Attachments::model()->findAllByAttributes(array(
                'content_id' => $id,
                ));

    if (!empty(Yii::app()->session['announcement_message']))
    {
        Yii::app()->user->setFlash('message',Yii::app()->session['announcement_message']);
        Yii::app()->session['announcement_message'] = null;
    }

    $this->render('index',array(
        'dataProvider'=>$dataProvider,
    ));
    }
else
{
    $this->redirect(Yii::app()->createAbsoluteUrl('news/index',array('page'=>'1')));
}
}

Your question is very hard to follow... but I'll attempt to answer by giving an example of how to use the CDataProvider and CListView to display all of the Announcements owned by the current logged in User. This assumes the Announcement model's table has a user_id field which contains the id of the User who owns or created it.

First, in your indexAction() in your controller:

// get the logged in user's ID
$userId = Yii::app()->user->id;
// now define the dataprovider, which will do the SQL query for you
$dataProvider = new CActiveDataProvider( // declare a new dataprovider
  'Announcement', // declare the type of Model you want to query and display
  array( // here we build the SQL 'where' clause
    'criteria' => array( // this is just building a CDbCriteria object
      'condition' => 'user_id=:id', // look for content with the user_id we pass in
      'params' => array(':id' => $userId), // pass in (bind) user's id to the query
      //'order'=>'date_modified DESC', // add your sort order if you want?
      //'with'=>'commentCount', // join in your commentCount table?
    )
  )
);
$this->render('index',array( // render the Index view
  'dataProvider'=>$dataProvider, // pass in the data provider
));

Then in your index.php view:

// create the CListView and pass in the $dataProvider we created above, in the indexAction
$this->widget('zii.widgets.CListView', array(
  'dataProvider'=>$dataProvider, // this is the data provider we just created
  'itemView'=>'_view2',
  'template'=>'{items}<div>{pager}</div>',
  'ajaxUpdate'=>false,
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM