Using ClistView and DAO - Call to a member function getAttributeLabel() on a non-object

StackOverflow https://stackoverflow.com/questions/22147845

  •  19-10-2022
  •  | 
  •  

문제

I'm posting again an existing post but with some changes. Actually, in the previous post I had an 'Invalid argument supplied for foreach' error, which was solved by the proposed solution of a user, to change the $command->execute() by $command->queryAll(). This helped me to go through ClistView, but when i tryed to render the _view view, I got the error:

Call to a member function getAttributeLabel() on a non-object in C:\wamp\www\contest\protected\views\contest_view.php on line 8 where the command is getAttributeLabel('id')); ?>

which is normal because what I got from CArrayDataProvider is an array. As suggested by the user, I should use CActiveDataProvider an array of CActiveRecord. Actually, I'm using DAO to have better performance and would like to avoid using CActiveRecord.

Follow the code to better understand what I'm doing.

In my index action I created the dataprovider in the following way

$connection=Yii::app()->db;
$user_id = Yii::app()->user->id;
$sql = 'SELECT * FROM post
        LEFT JOIN comment ON post.id = comment.post_id
        AND comment.user_id =:user_id
        LIMIT 0 , 30 ';
$command=$connection->createCommand($sql);
$command->bindParam(':user_id', $user_id,PDO::PARAM_STR);

$rawData = $command->queryAll();

$dataProvider=new CArrayDataProvider($rawData, array(
                    'id'=>'user',
                    'sort'=>array(
                    'defaultOrder' => 'post.created',
                    ),
                    'pagination'=>array(
                    'pageSize'=>10,
                    ),
        ));

then I render the index view

$this->render('index',array(
            'dataProvider'=>$dataProvider,
            'category_id'=>$category_id,
        ));

Index view is doing

<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_view',
)); ?>

and I got the error

Call to a member function getAttributeLabel() on a non-object in C:\wamp\www\contest\protected\views\contest_view.php on line 8

where the code is

<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>

Can you help me? Thank you in advance

도움이 되었습니까?

해결책

This variable $data is an array that does not have a property getAttributeLabel(). You need to use this approach:

CHtml::encode(Users::model()->getAttributeLabel('id'))

Where Users - the name of the model which you need to get the label.

다른 팁

I think you should use queryAll() instead of execute():

$rawData = $command->queryAll();

http://www.yiiframework.com/doc/api/1.1/CDbCommand/#execute-detail

This method is meant only for executing non-query SQL statement. No result set will be returned.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top