1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sco\Admin\Form\Elements; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
7
|
|
|
use Illuminate\Http\Request; |
8
|
|
|
|
9
|
|
|
class MultiSelect extends Select |
10
|
|
|
{ |
11
|
|
|
protected $defaultValue = []; |
12
|
|
|
|
13
|
|
View Code Duplication |
public function getValue() |
|
|
|
|
14
|
|
|
{ |
15
|
|
|
$value = $this->getValueFromModel(); |
16
|
|
|
if (empty($value)) { |
17
|
|
|
return $value; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
if ($this->isOptionsModel() && $this->isRelation()) { |
21
|
|
|
$model = $this->getOptionsModel(); |
22
|
|
|
$key = $this->getOptionsValueAttribute() ?: $model->getKeyName(); |
23
|
|
|
|
24
|
|
|
$value = $value->pluck($key)->map(function ($item) { |
25
|
|
|
return (string)$item; |
26
|
|
|
}); |
27
|
|
|
} |
28
|
|
|
return $value; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
protected function isOptionsModel() |
32
|
|
|
{ |
33
|
|
|
return is_string($this->options) || $this->options instanceof Model; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
protected function isRelation() |
37
|
|
|
{ |
38
|
|
|
return method_exists($this->getModel(), $this->getName()); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function save() |
42
|
|
|
{ |
43
|
|
|
if (!($this->isOptionsModel() && $this->isRelation())) { |
44
|
|
|
parent::save(); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
protected function prepareValue($value) |
49
|
|
|
{ |
50
|
|
|
if (!is_array($value)) { |
51
|
|
|
return $value; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return implode(',', $value); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function finishSave() |
58
|
|
|
{ |
59
|
|
|
if (!($this->isOptionsModel() && $this->isRelation())) { |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
$attribute = $this->getName(); |
63
|
|
|
$values = $this->getValueFromRequest(); |
64
|
|
|
|
65
|
|
|
$relation = $this->getModel()->{$attribute}(); |
66
|
|
|
if ($relation instanceof BelongsToMany) { |
67
|
|
|
$relation->sync($values); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function toArray() |
72
|
|
|
{ |
73
|
|
|
return parent::toArray() + [ |
74
|
|
|
'multiple' => true, |
75
|
|
|
]; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.