gpt4 book ai didi

gridview - Yii2 格式化程序 - 创建自定义格式

转载 作者:行者123 更新时间:2023-12-05 08:55:24 26 4
gpt4 key购买 nike

我想为 DetailView 和 GridView 创建我自己的格式选项。我现在正在使用可用的格式化程序选项,例如日期时间:

<?= DetailView::widget([
'model' => $model,
'attributes' => [
'current_date:datetime'
]
]?>

我想要这样的格式化程序:

 <?= DetailView::widget([
'model' => $model,
'attributes' => [
'current_date:datetime',
'colorId:color'
]
]?>

color 会将 colorId(它是 int - 颜色标识符)转换为颜色名称。我知道我可以在模型中有一个函数/虚拟属性,但我想在任何地方使用它,而不仅仅是在那个特定的模型上。我一直在搜索,但只发现我需要 specific formatter .

最佳答案

您可以扩展 Formatter 类并将“颜色”作为一种新的格式来处理。像这样的……

class MyFormatter extends \yii\i18n\Formatter
{
public function asColor($value)
{
// translate your int value to something else...
switch ($value) {
case 0:
return 'White';
case 1:
return 'Black';
default:
return 'Unknown color';
}
}
}

然后通过更改您的配置切换到使用这个新的格式化程序...

'components' => [
'formatter' => [
'class' => '\my\namespace\MyFormatter',
// other settings for formatter
'dateFormat' => 'yyyy-MM-dd',
],
],

现在您应该能够像您要求的那样在 gridview/datacolumn 中使用颜色格式:

'colorId:color'

...或者通常通过调用应用程序的格式化程序组件:

echo Yii::$app->formatter->asColor(1);  // 'Black'

请注意,此代码未经测试,可能包含错误。

关于gridview - Yii2 格式化程序 - 创建自定义格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46089960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com