doudi1750 2013-08-08 13:41
浏览 50
已采纳

试图在Comments模型中获取非对象的属性

I make as example Comment model for my Page model. Yesterday all was fine, but when today i go to check comments i have error http://pastebin.com/VE1G5Q6N.

Comment.php

<?php

/**
 * This is the model class for table "{{comment}}".
 *
 * The followings are the available columns in table '{{comment}}':
 * @property integer $id
 * @property string $content
 * @property integer $page_id
 * @property integer $created
 * @property integer $user_id
 * @property string $guest
 */
class Comment extends CActiveRecord
{
    public $verifyCode;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Comment the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{comment}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('content', 'required'),
            array('content, guest', 'required', 'on'=>'Guest'),
            array('page_id, created, user_id', 'numerical', 'integerOnly'=>true),
            array('guest', 'length', 'max'=>255),
            array('content', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'on'=>'Guest'),
            array('id, content, page_id, created, user_id, guest, status', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'user'=>array(self::BELONGS_TO, 'User', 'user_id'),
            'page'=>array(self::BELONGS_TO, 'Page', 'page_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'content' => 'Текст',
            'page_id' => 'Страница',
            'created' => 'Дата',
            'user_id' => 'Пользователь',
            'guest' => 'Имя (гость)',
            'status' => 'Статус',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('content',$this->content,true);
        $criteria->compare('page_id',$this->page_id);
        $criteria->compare('created',$this->created);
        $criteria->compare('user_id',$this->user_id);
        $criteria->compare('guest',$this->guest,true);
        $criteria->compare('status',$this->status,true);

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

    public function beforeSave()
    {
        if ($this->isNewRecord){
            $this->created = time();
        }

        if (!Yii::app()->user->isGuest) {
            $this->user_id = Yii::app()->user->id;
        }

        return parent::beforeSave();
    }

    public static function getComment($page_id)
    {
        $criteria = new CDbCriteria;

        $criteria->compare('page_id', $page_id);
        $criteria->compare('status', 1);

        $criteria->order = 'created DESC';

        return new CActiveDataProvider('Comment', array(
            'criteria'=>$criteria,
        ));
    }
}

CommentController.php

<?php

class CommentController extends Controller
{
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view','create','update','delete'),
                'roles'=>array('2'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new Comment;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Comment']))
        {
            $model->attributes=$_POST['Comment'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Comment']))
        {
            $model->attributes=$_POST['Comment'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
    }

    /**
     * Manages all models.
     */
    public function actionIndex()
    {
        $model=new Comment('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Comment']))
            $model->attributes=$_GET['Comment'];

        $this->render('index',array(
            'model'=>$model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Comment the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=Comment::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param Comment $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

view/index.php

<?php
/* @var $this CommentController */
/* @var $model Comment */

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
    $('.search-form').toggle();
    return false;
});
$('.search-form form').submit(function(){
    $('#comment-grid').yiiGridView('update', {
        data: $(this).serialize()
    });
    return false;
});
");
?>

<h1>Журнал комментариев</h1>

<?php echo CHtml::link('Расширенный поиск','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
    'model'=>$model,
)); ?>
</div><!-- search-form -->

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'comment-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        'id'=>array(
            'name'=>'id',
            'headerHtmlOptions'=>array('width'=>30),
        ),
        'status'=>array(
            'name'=>'status',
            'value'=>'($data->status==1)?"Доступно":"Скрыто"',
            'filter'=>array(0=>"Скрыто",1=>"Доступно"),
        ),
        'content',
        'page_id'=>array(
            'name'=>'page_id',
            'value'=>'$data->page->title',
            'filter'=>Page::getPage(),
        ),
        'created'=>array(
            'name'=>'created',
            'value'=>'date("j.m.Y. H:i", $data->created)',
            'filter'=>false,
        ),
        'user_id'=>array(
            'name'=>'user_id',
            'value'=>'$data->user->username',
            'filter'=>User::getUsername(),
        ),
        'guest',
        array(
            'class'=>'CButtonColumn',
            'updateButtonOptions'=>array('style'=>'display:none'),
        ),
    ),
)); ?>

view/view.php

<?php
/* @var $this CommentController */
/* @var $model Comment */

$this->menu=array(
    array('label'=>'Журнал комментариев', 'url'=>array('index')),
    array('label'=>'Удалить комментарий', 'url'=>'#',
          'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),
          'confirm'=>'Вы уверены что хотите удалить этот комментарий?')),
);
?>

<h1>Просмотр комментария #<?php echo $model->id; ?></h1>

<?php $this->widget('zii.widgets.CDetailView', array(
    'data'=>$model,
    'attributes'=>array(
        'id',
        'content',
        'page_id',
        'created',
        'user_id',
        'guest',
    ),
)); ?>

view/_search.php

<?php
/* @var $this CommentController */
/* @var $model Comment */
/* @var $form CActiveForm */
?>

<div class="wide form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'action'=>Yii::app()->createUrl($this->route),
    'method'=>'get',
)); ?>

    <div class="row">
        <?php echo $form->label($model,'id'); ?>
        <?php echo $form->textField($model,'id'); ?>
    </div>

    <div class="row">
        <?php echo $form->label($model,'status'); ?>
        <?php echo $form->dropDownList($model,'status', array(''=>'',0=>"Скрыто",1=>"Доступно")); ?>
    </div>
    <div class="row">
        <?php echo $form->label($model,'content'); ?>
        <?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>
    </div>

    <div class="row">
        <?php echo $form->label($model,'page_id'); ?>
        <?php echo $form->dropDownList($model,'page_id',Page::getPage(),array('empty'=>'')); ?>
    </div>

    <div class="row">
        <?php echo $form->label($model,'user_id'); ?>
        <?php echo $form->dropDownList($model,'user_id',User::getUsername(),array('empty'=>'')); ?>
    </div>

    <div class="row">
        <?php echo $form->label($model,'guest'); ?>
        <?php echo $form->textField($model,'guest',array('size'=>60,'maxlength'=>255)); ?>
    </div>

    <div class="row buttons">
        <?php echo CHtml::submitButton('Поиск'); ?>
    </div>

<?php $this->endWidget(); ?>

</div><!-- search-form -->
  • 写回答

1条回答 默认 最新

  • douzao9845 2013-08-08 14:37
    关注

    This issue is being generated when Yii tries to evaluate the code you have inside your GridView column values. Make sure each property you're referencing exists on $data.

    Since the issue just started happening, my guess is the culprit is "value" => "$data->page->title". Probably there's a new record that doesn't have a page relationship, so$data->page is null.

    Edit

    Actually, I didn't notice before, but your error output specifically highlights property reference CComponent->evaluateExpression("$data->user->username", array("data" => Comment, "row" => 0)). For the same reasons described above, $data->user is probably null.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记