/
ProductPrice.php
60 lines (53 loc) · 1.39 KB
/
ProductPrice.php
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
<?php
namespace app\models\master;
use app\models\master\Price;
/**
* ProductPrice
*
* @author Misbahul D Munir <misbahuldmunir@gmail.com>
* @since 1.0
*/
class ProductPrice extends \yii\base\Model
{
public $id;
public $name;
public $category;
public $price;
public $prices = [];
public function rules()
{
return[
[['id'], 'required'],
[['prices'], 'checkPrices'],
];
}
public function checkPrices()
{
foreach ($this->prices as $key => $value) {
$value = trim($value);
if (empty($value)) {
unset($this->prices[$key]);
continue;
}
if (!is_numeric($value) || $value < 0) {
$this->addError('prices', 'Price must numeric great than zero');
break;
}
}
}
public function save($validate = true)
{
if ($validate && !$this->validate()) {
return false;
}
foreach ($this->prices as $ct_id => $value) {
$model = Price::findOne(['product_id' => $this->id, 'price_category_id' => $ct_id]);
$model = $model ? : new Price(['product_id' => $this->id, 'price_category_id' => $ct_id]);
$model->price = $value;
if (!$model->save()) {
return false;
}
}
return true;
}
}