Yii-CDetailView使用模型函数(使用模型属性)的值



某个类有一个名为status的属性(可以是0或1)。在相应的模型中,我定义了两个变量STATUS_CLOSED = 1STATUS_OPEN = 2

我使用CDetailView在"视图"视图中显示模型信息,如:

$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'account_number',
'account_type',
array(
'label'=>'Banco',
'type'=>'raw',
'value'=>CHtml::encode($model->bank->bank_name),
),
),
));

我在我的模型中定义了这两个函数:

public function statusLabels()
{
return array(
self::STATUS_CLOSED => 'Inactiva',
self::STATUS_OPEN   => 'Activa',
);
}
public function getStatusLabel($status)
{
$labels = self::statusLabels();
if (isset($labels[$status])) {
return $labels[$status];
}
return $status;
}

我需要自定义CDetailView(可能使用这两个函数)以显示相应的标签,具体取决于状态值。

我以为这会奏效:

$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'account_number',
'account_type',
array(
'label'=>'Estado',
'type'=>'raw',
'value'=>$model->statusLabel($model->status),
),
),
));

但我得到了:Missing argument 1 for BankAccount::getStatusLabel()

我做错了什么?

好的,首先你不需要发送模型的状态,因为模型已经知道自己的状态,所以我会把你的函数改为:

public function getStatusLabel() {
$labels = self::statusLabels();
if (isset($labels[$this->status])) {
return $labels[$this->status];
}
return $this->status;
}

那么你的小部件就是这样的:

$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'account_number',
'account_type',
array(
'label'=>'Estado',
'type'=>'raw',
'value'=>$model->statusLabel
),
),
));

此外,它不会导致错误,但实际上您应该将函数statusLabels()设置为静态函数。

public static function statusLabels() {
...
}

最新更新