【问题标题】:Yii 1.3 zii.widgets.grid.CGridView adding custom function to classYii 1.3 zii.widgets.grid.CGridView 向类添加自定义函数
【发布时间】:2015-07-06 09:32:34
【问题描述】:

我的一个控制器中有用于处理数据库的功能。 像这样的:

static function getCamByClassId($id)
{
    $connection=Yii::app()->db;
    $command=$connection->createCommand("some query");
    $camReader=$command->query();
    $camList=$command->queryAll();
    return $camList;
}

我也在使用 zii 小部件。像这样:

    $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'someId',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        array(
            'name' => 'Image',
            'type' => 'raw',
            'value' => 'CHtml::image("/uploads/thumb_".$data->Lesson_ID."_".$data->Image, "" ,array(\'width\'=>195, \'height\'=>110))', 
        ,
        ),  
...
),));

现在我需要在那里使用其他图片,这是通过这种方法获得的。 我试图替换 'value' 上的属性

'value' => 'CHtml::image(".$this->getCamByClassId($data->Lesson_ID)[0][\'Cam1\'].", "default image" ,array(\'width\'=>195, \'height\'=>110))',

然后我收到这个异常:

Property "CDataColumn.getCamByClassId" is not defined.

我看到将方法复制到 CDataColumn.php 中是没有意义的,因为它会查找属性并且我无法将方法返回值设置为此 calss 的某些属性,因为它的结果取决于 $id 参数。我如何将 getCamByClassId 的“值”属性结果传递给?
更新 好的,我可以像LessonController::getCamByClassId 一样使用它,但是我怎样才能通过$data->LessonId 呢?
UPDATE1 试过这个

'value' => 'CHtml::image(".$this->grid->controller->getCamByClassId($data->Lesson_ID).", "default image" ,array(\'width\'=>195, \'height\'=>110))',

它说:CGridView 类的对象无法转换为字符串 更新2 检查了topher的最后一个建议

'value' => function($data, $row) {
    return CHtml::image(
        LessonController::getCamByClassId($data->Lesson_ID)[0]['Cam1'],
        "default image",
        array('width'=>195, 'height'=>110)
    );
}

我的错误:我有一个错字。现在它说 0 是未定义的偏移量,要调试它。

【问题讨论】:

    标签: php yii


    【解决方案1】:

    value 中的$this 指的是CDataColumn 实例,而不是您的控制器。由于您的方法是静态的并且假设您的控制器是自动加载的,您可以使用以下方法调用该方法:

    myController::getCamByClassId(...)
    

    如果不是,您可以通过CDataColumngrid 属性访问它,该属性依次返回具有controller 属性的CGridView object

    $this->grid->controller->getCamByClassId(...)
    

    为了可读性和更易于维护,您可以使用匿名函数:

    'value' => function($data, $row) {
        return CHtml::image(
            LessonController::getCamByClassId($data->Lesson_ID)[0]['Cam1'],
            "default image",
            array('width'=>195, 'height'=>110)
        );
    }
    

    【讨论】:

    • 好的,我可以使用 myController::getCamByClassId(...) 方法。但是然后它说 $data->Lesson_ID id 未定义变量,但是它已定义并且我使用它。
    • 我会检查你的第二个变种。
    • 我已经更新了答案。应该更容易调试。
    • 我明天或者今天有时间去看看。
    【解决方案2】:

    您使用 $this->getCamByClassId 但它被定义为静态。所以要么删除静态属性,要么使用 self::getCamByClassId。

    让我们知道这是否有效

    标记

    【讨论】:

    • $this->myStaticMethod()valid PHP code。这是否是好的做法是另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多