如何在checkBoxHtmlOptions中使用$ data-> id

时间:2015-05-06 13:34:13

标签: php yii

我正在使用yii cgridview,我想在复选框中添加alt。我成功地添加了这个,但我想添加$data->rem_type我的意思是变量。这是我试过的代码

array(
     'name' => 'check',
     'id' => 'selectedIds',
     'value' => '$data->rem_id',
     'class' => 'CCheckBoxColumn',
     'selectableRows' => '100',
     'checkBoxHtmlOptions'=>array(
      'alt'=>'$data->rem_type'),
),

但它产生了像这样的HTML

<input alt="{$data->rem_type}" value="12" id="selectedIds_0" type="checkbox" name="selectedIds[]">

如果我删除了引号(即'alt'=>$data->rem_type)),则会显示错误Undefined variable: data

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:1)

好的,所以我没有对此进行过测试,但我认为你可以这样做:

CCheckBoxColumn扩展为CheckBoxColumn并覆盖getDataCellContent函数:

class CheckBoxColumn extends CCheckBoxColumn {

    public function getDataCellContent($row) {
        $data = $this->grid->dataProvider->data[$row];
        if ($this->value !== null)
            $value = $this->evaluateExpression($this->value, array('data' => $data, 'row' => $row));
        elseif ($this->name !== null)
            $value = CHtml::value($data, $this->name);
        else
            $value = $this->grid->dataProvider->keys[$row];

        $checked = false;
        if ($this->checked !== null)
            $checked = $this->evaluateExpression($this->checked, array('data' => $data, 'row' => $row));

        $options = $this->checkBoxHtmlOptions;
        if ($this->disabled !== null)
            $options['disabled'] = $this->evaluateExpression($this->disabled, array('data' => $data, 'row' => $row));

        if (array_key_exists("alt", $options)) { //checks if you have set an alt
            $options['alt'] = $this->evaluateExpression($options['alt'], array('data' => $data, 'row' => $row)); //if you have it will evaluate the expression
        }

        $name = $options['name'];
        unset($options['name']);
        $options['value'] = $value;
        $options['id'] = $this->id . '_' . $row;
        return CHtml::checkBox($name, $checked, $options);
    }

}

我复制了原始function

中的大部分代码

并添加了这部分:

if (array_key_exists("alt", $options)) { //checks if you have set an alt
    $options['alt'] = $this->evaluateExpression($options['alt'], array('data' =>data, 'row' => $row)); //if you have it will evaluate the expression
}

可能有一种方法可以做得更好,即不复制代码,但我会告诉你。

将其保存在您的组件文件夹中,将其包含在config.php中。 并在您的小部件中使用此类:

array(
     'name' => 'check',
     'id' => 'selectedIds',
     'value' => '$data->rem_id',
     'class' => 'CheckBoxColumn',// <-- instead of CCheckBoxColumn
     'selectableRows' => '100',
     'checkBoxHtmlOptions'=>array(
      'alt'=>'$data->rem_type'),
),

让我知道它是否有效!