ancor/yii2-constant-label

为任何模型常量创建标签

安装次数: 222

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

类型:yii2-extension

dev-master 2016-03-12 14:03 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:58:26 UTC


README

欢迎通过以下方式告诉我您想添加的其他内容:

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

$ php composer.phar require ancor/yii2-constant-label

或者

"ancor/yii2-constant-label": "dev-master"

将以下内容添加到您的 composer.json 文件的 require 部分:

添加到模型中

要使用 ConstantLabelBehavior,请将以下代码插入您的 Model 类中:

use common\behaviors\ConstantLabelBehavior;

/**
 * @mixin ConstantLabelBehavior
 */
class MyModel extends Model
{
    const STATUS_ACTIVE  = 10;
    const STATUS_DELETED = 0;

    public function behaviors()
    {
      return [
          [
              'class' => ConstantLabelBehavior::className(),
              'constantLabels' => [
                  'status' => [
                      self::STATUS_ACTIVE  => 'User is active',
                      self::STATUS_DELETED => 'User deleted',
                  ]
              ],
          ]
      ];
    }
}

使用方法

$model = new MyModel();


// return key-value array with constant values as key and constant label as value
$labels = $model->getConstantLabels('status');

// return label for one constant
$label = $model->getConstant('status', $model::STATUS_ACTIVE);

// return values of all constants
$values = $model->getConstantValues('status'); // [10, 0]

// also it can be use in validation rules
[
    ['status', 'in', 'range' => $model->getConstantValues('status')],
]