我只想显示每个帖子的注释,
我做到了: 在view.php
帖子中,我有一个视图:
<?php
$this->renderPartial('/TblComments/_comment',array(
'comments'=>$model_comments,
));
?>
这是_comment.php
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('user_id')); ?>:</b>
<?php echo CHtml::encode($data->user_id); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('post_id')); ?>:</b>
<?php echo CHtml::encode($data->post_id); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('comment_body')); ?>:</b>
<?php echo CHtml::encode($data->comment_body); ?>
<br />
<?php echo CHtml::link('Edit', array('tblComments/update', 'id'=>$data->id)); ?>
<br/>
<?php echo CHtml::link('Delete', array('tblComments/delete', 'id'=>$data->id)); ?>
</div>
现在问题是:
Undefined variable: data
我Donot知道为什么吗?请解释并帮助我!
那是因为您没有将 $data
变量传递给 _comment.php
,而是在调用 renderPartial()
时仅通过 $comments
变量。
在上面的示例中使用$data
参数的文件通常是设计用于在ClistView或类似中使用的,您需要传递数据提供商而不是数组(我假设$model_comments
是?)。
ClistView获取数据提供商,并为数据提供商中的每个记录转换为$data
变量(如您在_comments.php
文件中所看到的)。
假设$model_comments
是您模型的"注释"关系,这应该是模型对象的数组?如果是这种情况,您不必创建一个与ClistView一起使用的新CDataprovider,您可以使用CarrayDataprovide将该关系阵列转换为可以在ClistView中使用的数据提供商。因此,类似的东西可能对您有用;
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>new CArrayDataProvider($model_comments, array()),
'itemView'=>'/TblComments/_comment',
));
未测试,您可能需要编辑才能品尝。