PHP code example of kakadu-dev / yii2-enum

1. Go to this page and download the library: Download kakadu-dev/yii2-enum library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kakadu-dev / yii2-enum example snippets




namespace common\models\Users\Enums;

use Yii;
use Kakadu\Yii2Enum\Enum;

class UserStatus extends Enum
{
    const DELETED = 0;
    const ACTIVE  = 1;

    protected static $attribute = 'status';

    public static function all(): array
    {
        return [
            self::DELETED => Yii::t('app', 'Deleted'),
            self::ACTIVE  => Yii::t('app', 'Active'),
        ];
    }
}

namespace common\models\Users;

use common\models\Users\Enums\UserStatus;

class User extends ActiveRecord
{
    public function rules(): array
    {
        return [
            ['status', 'default', 'value' => UserStatus::ACTIVE],
            ['status', 'in', 'range' => UserStatus::keys()],
        ];
    }
    ...
}

$model = new User(['status' => UserStatus::ACTIVE]);

if (UserStatus::has($model, UserStatus::ACTIVE)) {
    // do something
}

// DetailView widget (or GridView)
DetailView::widget([
    'model'      => $model,
    'attributes' => [
        'id',
        'name',
        [
            'attribute' => 'status',
            'filter'    => UserStatus::all(),
            'value'     => UserStatus::get($model->status),
        ],
        ...
    ],
])

// In form
$form->field($model, 'status')->dropDownList(UserStatus::all())

'i18n'           => [
    'translations' => [
        'kkd-enum*' => \Kakadu\Yii2Enum\EnumTranslation::getConfig(),
    ],
],

common/  
    models/    
        Users/  
            Enums/
                UserStatus.php
            User.php
            UserQuery.php