douza6300 2014-01-20 01:14 采纳率: 0%
浏览 83
已采纳

如何在Yii中使用CListView自定义dataProvider

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')));
}
}
  • 写回答

1条回答 默认 最新

  • douque9815 2014-01-20 03:04
    关注

    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,
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理