【问题标题】:How to not to display image if it doesn't exist in widget如果小部件中不存在图像,如何不显示图像
【发布时间】:2012-12-07 18:12:47
【问题描述】:

我正在使用 yii cdetail 小部件进行查看,但是..我想知道如果图像不存在如何找到方法。

我收到错误:尝试获取非对象的属性

<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
    'id',
            'name',
    'keywords',
   array(
    'label'=>'Image',
    'type'=>'raw',
    'value'=>$fileModel->name ? CHtml::image(Yii::app()->request->baseUrl.'/uploads/'.$model->logo_file_id.'/'.$fileModel->file_name.$fileModel->extension,"image_url") : null,
        ),

    'contact_name',
    'description',
    'status',
    'created',

),
)); ?>

谁能告诉我这里有什么问题?

【问题讨论】:

  • 假设$model总是被设置,那么$fileModel就是null会导致异常。您必须添加检查是否设置了$fileModel(或者即使设置了,请检查文件是否存在于磁盘上)。

标签: database image yii


【解决方案1】:

在模型中,您可以使用 getter 方法返回图像,如果图像不存在则返回默认值:

public function getImage() {
    $url = Yii::app()->request->baseUrl.'/uploads/'.$this->logo_file_id.'/'.$fileModel->file_name.$fileModel->extension;
    if(file_exists($url)){
        return $url
    }
    //return the default image for example
}

那么在你看来你会做的事

'value'=> CHtml::image($model->Image,"image_url"),
//Note that i'm calling "Image" and not getImage()

当然这段代码需要改进,因为getImage方法中不会定义$fileModel,但我不知道它的作用是什么!

【讨论】:

  • 值得一提的是,如果没有设置$this-&gt;logo_file_id$fileModel-&gt;file_name(即没有图像),getter 必须返回某个“no_image.jpg”文件的路径。
【解决方案2】:

请试试这个..

"value"=>'($data->picture !=="") ? CHtml::image(Yii::app()->request->baseurl."/upload/technician/".$data->picture,"",array(\'width\'=>100, \'height\'=>50)) : ""',

希望对你有帮助……

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多