1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sco\Admin\Form\Elements; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
6
|
|
|
use Sco\Admin\Traits\HasSelectOptions; |
7
|
|
|
|
8
|
|
|
class MultiSelect extends NamedElement |
9
|
|
|
{ |
10
|
|
|
use HasSelectOptions; |
11
|
|
|
|
12
|
|
|
protected $type = 'select'; |
13
|
|
|
|
14
|
|
|
protected $defaultValue = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* |
18
|
|
|
* @param string $name |
19
|
|
|
* @param string $title |
20
|
|
|
* @param array|Model $options |
21
|
|
|
*/ |
22
|
|
|
public function __construct(string $name, string $title, $options = null) |
23
|
|
|
{ |
24
|
|
|
parent::__construct($name, $title); |
25
|
|
|
|
26
|
|
|
if (! is_null($options)) { |
27
|
|
|
$this->setOptions($options); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if (! ($this->isOptionsModel() && $this->isRelation())) { |
31
|
|
|
$this->setCast('json'); |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function getValue() |
36
|
|
|
{ |
37
|
|
|
$value = parent::getValue(); |
38
|
|
|
|
39
|
|
|
if ($this->isOptionsModel() && $this->isRelation()) { |
40
|
|
|
$model = $this->getOptionsModel(); |
41
|
|
|
$key = $this->getOptionsValueAttribute() ?: $model->getKeyName(); |
42
|
|
|
|
43
|
|
|
return collect($value)->pluck($key)->map(function ($item) { |
44
|
|
|
return (string) $item; |
45
|
|
|
}); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return (array) $value; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function save() |
52
|
|
|
{ |
53
|
|
|
if (! ($this->isOptionsModel() && $this->isRelation())) { |
54
|
|
|
parent::save(); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
View Code Duplication |
public function finishSave() |
|
|
|
|
59
|
|
|
{ |
60
|
|
|
if (! ($this->isOptionsModel() && $this->isRelation())) { |
61
|
|
|
return; |
62
|
|
|
} |
63
|
|
|
$attribute = $this->getName(); |
64
|
|
|
$values = $this->getValueFromRequest(); |
65
|
|
|
|
66
|
|
|
$relation = $this->getModel()->{$attribute}(); |
67
|
|
|
if ($relation instanceof BelongsToMany) { |
68
|
|
|
$relation->sync($values); |
|
|
|
|
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected function isRelation() |
73
|
|
|
{ |
74
|
|
|
return method_exists($this->getModel(), $this->getName()); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
public function toArray() |
78
|
|
|
{ |
79
|
|
|
return parent::toArray() + [ |
80
|
|
|
'options' => $this->getOptions(), |
81
|
|
|
'multiple' => true, |
82
|
|
|
]; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
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.