DefaultVariantBehavior.php
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
namespace artbox\catalog\behaviors;
use artbox\catalog\models\Product;
use artbox\catalog\models\Variant;
use artbox\catalog\models\VariantLang;
use artbox\core\models\Language;
use yii\base\Behavior;
/**
* Class DefaultVariantBehavior
*
* @property Product $owner
* @see ProductVariant
*/
class DefaultVariantBehavior extends Behavior
{
/**
* @inheritdoc
*/
public function events()
{
return [
Product::EVENT_AFTER_INSERT => 'addDefaultVariant',
];
}
/**
* Creates new default product's variant
*/
public function addDefaultVariant()
{
$defaultVariant = new Variant();
$defaultVariant->product_id = $this->owner->id;
$defaultVariant->stock = 1;
$defaultVariant->sku = 'default';
$defaultVariant->save(false);
/**
* Saving languages
*/
$activeLanguageIds = Language::find()
->select('id')
->where(
[
'status' => true,
]
)
->asArray()
->column();
foreach ($activeLanguageIds as $languageId) {
$variantLanguage = new VariantLang();
$variantLanguage->language_id = $languageId;
$variantLanguage->variant_id = $defaultVariant->id;
$variantLanguage->title = 'default_' . $languageId;
$variantLanguage->save(false);
}
}
}