https://github.com/eluhr/yii2-json-attribute-behavior
Automatically convert values to array before validation
https://github.com/eluhr/yii2-json-attribute-behavior
behavior json yii2
Last synced: 5 months ago
JSON representation
Automatically convert values to array before validation
- Host: GitHub
- URL: https://github.com/eluhr/yii2-json-attribute-behavior
- Owner: eluhr
- Created: 2023-12-22T13:54:22.000Z (about 2 years ago)
- Default Branch: master
- Last Pushed: 2024-01-01T00:37:50.000Z (about 2 years ago)
- Last Synced: 2025-08-25T22:26:17.770Z (6 months ago)
- Topics: behavior, json, yii2
- Language: PHP
- Homepage:
- Size: 15.6 KB
- Stars: 2
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
Yii2 JSON Attribute Behavior
============================
This behavior automatically decodes attributes from JSON to arrays before validation, handling errors and re-encoding if validation fails.
With this a "real" json string can be further processed.

Installation
------------
The preferred way to install this extension is through [composer](https://getcomposer.org/download/).
Either run
```
composer require --prefer-dist eluhr/yii2-json-attribute-behavior "*"
```
or add
```
"eluhr/yii2-json-attribute-behavior": "*"
```
to the `require` section of your `composer.json` file.
Usage
-----
In a `yii\base\Model` or a derivation thereof, the behavior can be used as follows:
```php
public function behaviors(): array
{
$behaviors = parent::behaviors();
$behaviors['json-attribute'] = [
'class' => eluhr\jsonAttributeBehavior\JsonAttributeBehavior::class,
'attributes' => [
'data_json'
]
];
return $behaviors;
}
```
By using this behavior it does not matter if the attribute is a string or an array.
The behavior will always ensure, that the attribute is an array before saving the data to the database and yii will handle the rest.
This behavior supports [i18n](https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n). By adding the `json-attribute-behavior` category in your config you can overwrite the default error messages.
Testing
-------
After installing dependencies via composer you can run the tests with:
```bash
make test
```