PHP code example of blacksesion / yii2-eav
1. Go to this page and download the library: Download blacksesion/yii2-eav 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/ */
blacksesion / yii2-eav example snippets
$attr = new blacksesion\eav\models\EavAttribute();
$attr->attributes = [
'entityId' => 1, // Category ID
'name' => 'AttrCategory1', // service name field
'label' => 'Attr1', // label text for form
'defaultValue' => 'attr1', // default value
'entityModel' => SampleModel::className(), // work model
'
$modules = [
...,
'eav' => [
'class' => 'blacksesion\eav\Module',
],
];
php composer.phar
sh
php ./yii migrate/up -p=@blacksesion/eav/migrations
sh
php ./yii migrate/up -p=@vendor/blacksesion/yii2-eav/src/migrations
php
class Product extends \yii\db\ActiveRecord
{
/**
*
*
*/
public function rules()
{
return [
[['name'], 'string', 'max' => 255], // Product field
[['c1'], 'function behaviors()
{
return [
'eav' => [
'class' => \blacksesion\eav\EavBehavior::className(),
'valueClass' => \blacksesion\eav\models\EavAttributeValue::className(),
]
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEavAttributes()
{
return \blacksesion\eav\models\EavAttribute::find()
->joinWith('entity')
->where([
'categoryId' => $this->categories[0]->id,
'entityModel' => $this::className()
]);
}
}
php
class Product extends \yii\db\ActiveRecord
{
/**
*
*
*/
public function rules()
{
return [
[['name'], 'string', 'max' => 255], // Product field
[['c1'], 'tion behaviors()
{
return [
'eav' => [
'class' => \blacksesion\eav\EavBehavior::className(),
'valueClass' => \blacksesion\eav\models\EavAttributeValue::className(),
]
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEavAttributes($attributes = [])
{
return \blacksesion\eav\models\EavAttribute::find()
->joinWith('entity')
->where([
//'categoryId' => $entityId,
'entityModel' => $this::className()
])->andWhere($attributes);
}
}
### View
Insert this code for create widget or load all EAV inputs fields for model
### Form edit
fo load selected field
foreach($model->getEavAttributes()->all() as $attr){
echo $form->field($model, $attr->name, ['class' => '\blacksesion\eav\widgets\ActiveField'])->eavInput();
}
foreach($model->getEavAttributes()->orderBy(['order' => SORT_ASC])->all() as $attr){
echo $form->field($model, $attr->name, ['class' => '\blacksesion\eav\widgets\ActiveField'])->eavInput();
}
foreach($model->getEavAttributes(['entityId' => 8, 'typeId' => 3])->all() as $attr){
echo $form->field($model, $attr->name, ['class' => '\blacksesion\eav\widgets\ActiveField'])->eavInput();
}
foreach($model->getEavAttributes()->all() as $attr){
print_r($model[$attr->name]['value']);
}
foreach($model->getEavAttributes()->all() as $attr){
echo $model[$attr->name];
}