-2

例として、Page モデルの Comment モデルを作成します。昨日はすべて問題ありませんでしたが、今日コメントを確認すると、http://pastebin.com/VE1G5Q6Nというエラーが発生しました。

コメント.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();
        }
    }
}

ビュー/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.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',
    ),
)); ?>

ビュー/_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 -->
4

1 に答える 1

1

この問題は、Yii が GridView 列の値内にあるコードを評価しようとしたときに発生しています。参照している各プロパティが に存在することを確認してください$data

問題が発生し始めたばかりなので、犯人は"value" => "$data->page->title". おそらく、ページ関係を持たない新しいレコードがあるため、$data->pagenull です。

編集

実は、以前は気がつきませんでしたが、エラー出力では特にプロパティ参照が強調表示されていますCComponent->evaluateExpression("$data->user->username", array("data" => Comment, "row" => 0))。上記と同じ理由で、$data->userおそらく null です。

于 2013-08-08T14:37:34.003 に答える