1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sco\Admin\Form\Elements; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
6
|
|
|
|
7
|
|
|
class MultiSelect extends Select |
8
|
|
|
{ |
9
|
|
|
protected $defaultValue = []; |
10
|
|
|
|
11
|
|
|
public function getValue() |
12
|
|
|
{ |
13
|
|
|
$value = $this->getValueFromModel(); |
14
|
|
|
if (empty($value)) { |
15
|
|
|
return []; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
if ($this->isOptionsModel() && $this->isRelation()) { |
19
|
|
|
$model = $this->getOptionsModel(); |
20
|
|
|
$key = $this->getOptionsValueAttribute() ?: $model->getKeyName(); |
21
|
|
|
|
22
|
|
|
return $value->pluck($key)->map(function ($item) { |
23
|
|
|
return (string)$item; |
24
|
|
|
}); |
25
|
|
|
} elseif (is_string($value)) { |
26
|
|
|
if (strpos($value, ',') !== false) { |
27
|
|
|
return explode(',', $value); |
28
|
|
|
} |
29
|
|
|
return (array)$value; |
30
|
|
|
} |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function save() |
34
|
|
|
{ |
35
|
|
|
if (!($this->isOptionsModel() && $this->isRelation())) { |
36
|
|
|
parent::save(); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
View Code Duplication |
public function finishSave() |
|
|
|
|
41
|
|
|
{ |
42
|
|
|
if (!($this->isOptionsModel() && $this->isRelation())) { |
43
|
|
|
return; |
44
|
|
|
} |
45
|
|
|
$attribute = $this->getName(); |
46
|
|
|
$values = $this->getValueFromRequest(); |
47
|
|
|
|
48
|
|
|
$relation = $this->getModel()->{$attribute}(); |
49
|
|
|
if ($relation instanceof BelongsToMany) { |
50
|
|
|
$relation->sync($values); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
protected function isOptionsModel() |
55
|
|
|
{ |
56
|
|
|
return is_string($this->options) || $this->options instanceof Model; |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
protected function isRelation() |
60
|
|
|
{ |
61
|
|
|
return method_exists($this->getModel(), $this->getName()); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function toArray() |
65
|
|
|
{ |
66
|
|
|
return parent::toArray() + [ |
67
|
|
|
'multiple' => true, |
68
|
|
|
]; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
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.