|
| 1 | +# Settings for Yii2 |
| 2 | + |
| 3 | +[](https://travis-ci.org/rkit/settings-yii2) |
| 4 | +[](https://scrutinizer-ci.com/g/rkit/settings-yii2/?branch=master) |
| 5 | +[](http://codecov.io/github/rkit/settings-yii2?branch=master) |
| 6 | +[](https://scrutinizer-ci.com/g/rkit/settings-yii2/?branch=master) |
| 7 | + |
| 8 | +## Installation |
| 9 | + |
| 10 | +1. Installing using Composer |
| 11 | + ``` |
| 12 | + composer require rkit/settings-yii2 |
| 13 | + ``` |
| 14 | + |
| 15 | +2. Run migrations |
| 16 | + ``` |
| 17 | + php yii migrate --migrationPath=@vendor/rkit/settings-yii2/src/migrations/ --interactive=0 |
| 18 | + ``` |
| 19 | + |
| 20 | +## Configuration |
| 21 | + |
| 22 | +Add the following in your config, in section `components` |
| 23 | + |
| 24 | +```php |
| 25 | +'settings' => [ |
| 26 | + 'class' => 'rkit\settings\Settings', |
| 27 | + //'cache' => '…', // cache component name |
| 28 | + //'tableName' => '…' // table name |
| 29 | + //'cacheName' => '…' // a key identifying the values to be cached |
| 30 | + ] |
| 31 | +``` |
| 32 | + |
| 33 | +## Usage |
| 34 | + |
| 35 | +### Basic usage |
| 36 | + |
| 37 | +1. Load |
| 38 | + ```php |
| 39 | + Yii::$app->settings->load(['key' => 'value']); |
| 40 | + ``` |
| 41 | + |
| 42 | +2. Set |
| 43 | + ```php |
| 44 | + Yii::$app->settings->set('key', 'value'); |
| 45 | + // or |
| 46 | + Yii::$app->settings->key = value; |
| 47 | + ``` |
| 48 | + |
| 49 | +3. Get |
| 50 | + ```php |
| 51 | + Yii::$app->settings->get('key'); |
| 52 | + // or |
| 53 | + Yii::$app->settings->key; |
| 54 | + // get all |
| 55 | + Yii::$app->settings->all(); |
| 56 | + ``` |
| 57 | + |
| 58 | +### Editing in the control panel |
| 59 | + |
| 60 | +1. Controller |
| 61 | + ```php |
| 62 | + $model = new Settings(); |
| 63 | + |
| 64 | + if (Yii::$app->request->isPost) { |
| 65 | + if ($model->load(Yii::$app->request->post()) && $model->validate()) { |
| 66 | + Yii::$app->settings->load($model->getAttributes()); |
| 67 | + Yii::$app->session->setFlash('success', Yii::t('app', 'Saved successfully')); |
| 68 | + return $this->refresh(); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + $model->setAttributes(Yii::$app->settings->all()); |
| 73 | + |
| 74 | + return $this->render('index', ['model' => $model]); |
| 75 | + ``` |
| 76 | + |
| 77 | +2. Model |
| 78 | + ```php |
| 79 | + class Settings extends \yii\base\Model |
| 80 | + { |
| 81 | + … |
| 82 | + public function rules() |
| 83 | + { |
| 84 | + return [ |
| 85 | + ['emailPrefix', 'trim'], |
| 86 | + ['emailMain', 'email'], |
| 87 | + … |
| 88 | + ]; |
| 89 | + } |
| 90 | + … |
| 91 | + } |
| 92 | + ``` |
| 93 | + |
| 94 | +3. View |
| 95 | + ```php |
| 96 | + … |
| 97 | + <?= $form->field($model, 'emailMain') ?> |
| 98 | + <?= $form->field($model, 'emailPrefix') ?> |
| 99 | + … |
| 100 | + ``` |
0 commit comments