Ok, I’ve read through the book, tutorials and forum posts, but I can’t seem to get this right. I’m making a chat room application where Comment is the main model. I have it working, except that now I’m trying to make a “liveindex” view for the comments and I want to pass the comment model data to a foreach similar to how its done in the _comment partial view in the blog tutorial. Here are the parts that I have so far relevant to this problem:
model/Comment.php relations function
const STATUS_ENABLED=1;
const STATUS_DISABLED=0;
[..snipped code here..]
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(
'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),
'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),
'comments' => array(self::HAS_MANY, 'Comment', 'id', 'condition'=>'comments.status='.Comment::STATUS_ENABLED, 'order'=>'comments.create_time DESC'),
);
}
CommentController.php actionLiveindex function
public function actionLiveindex()
{
$dataProvider=new CActiveDataProvider('Comment', array(
'criteria'=>array(
'condition'=>'status=1',
'order'=>'create_time DESC',
),
));
$model=new Comment;
if(isset($_POST['Comment']))
{
$model->attributes=$_POST['Comment'];
$model->status = 1; # Default the comment to "Enabled"
$model->save();
}
$this->render('liveindex',array(
'dataProvider'=>$dataProvider,
'model'=>$model,
));
}
views/comment/liveindex.php
<?php
$this->breadcrumbs=array(
'Comments',
);
$this->menu=array(
array('label'=>'Create Comment', 'url'=>array('create')),
array('label'=>'Manage Comment', 'url'=>array('admin')),
);
?>
<?php echo $this->renderPartial('_form',array( 'model'=>$model, 'rows'=>2)); ?>
<h2>Comments</h2>
<div id="comments">
<?php if($model->count()>=1): ?>
<h3>
<?php echo $model->count() . ' comment(s)'; ?>
</h3>
<?php $this->renderPartial('_comments',array(
'comments'=>$dataProvider,
)); ?>
<?php endif; ?>
</div>
views/comment/_comments.php
<?php foreach($comments as $comment): ?>
<div class="comment" id="c<?php echo $comment->id; ?>">
<?php echo "#{$comment->id}"; ?>
<div class="author">
<?php echo $comment->createUser; ?> says:
</div>
<div class="time">
<?php echo date('F j, Y \a\t h:i a',$comment->create_time); ?>
</div>
<div class="content">
<?php echo nl2br(CHtml::encode($comment->content)); ?>
</div>
</div><!-- comment -->
<?php endforeach; ?>
So when I try to go to I get the following error:
If I remove the $comment->createUser line from the _comments.php view, then it just says that create_time is not defined. So $comment is not getting set to a model data instance. Any ideas?