1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SleepingOwl\Admin\Form\Related\Forms; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use SleepingOwl\Admin\Form\Related\Elements; |
7
|
|
|
|
8
|
|
|
class HasMany extends Elements |
9
|
|
|
{ |
10
|
|
|
public function initialize() |
11
|
|
|
{ |
12
|
|
|
parent::initialize(); |
13
|
|
|
|
14
|
|
|
$this->modifyQuery(function ($query) { |
15
|
|
|
$query->orderBy($this->getEmptyRelation()->getRelated()->getKeyName()); |
16
|
|
|
}); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
protected function proceedSave(\Illuminate\Http\Request $request) |
20
|
|
|
{ |
21
|
|
|
$relation = $this->getRelation(); |
22
|
|
|
|
23
|
|
|
// First we need to remove all entities |
24
|
|
|
if (! $this->toRemove->isEmpty()) { |
25
|
|
|
$class = get_class($relation->getRelated()); |
26
|
|
|
$class::destroy($this->toRemove->all()); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$relation->saveMany($this->relatedValues); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function prepareRelatedValues(array $data) |
33
|
|
|
{ |
34
|
|
|
$elements = $this->flatNamedElements($this->getNewElements()); |
35
|
|
|
foreach ($data as $relatedId => $attributes) { |
36
|
|
|
$related = $this->addOrGetRelated($relatedId); |
37
|
|
|
|
38
|
|
|
foreach ($elements as $element) { |
39
|
|
|
$attribute = $element->getModelAttributeKey(); |
40
|
|
|
$value = $element->prepareValue(array_get($attributes, $attribute)); |
41
|
|
|
$related->setAttribute($attribute, $value); |
42
|
|
|
$element->setModel($related); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function retrieveRelationValuesFromQuery($query) |
48
|
|
|
{ |
49
|
|
|
return $query->get()->keyBy($this->getRelation()->getRelated()->getKeyName()); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function getModelForElements() |
53
|
|
|
{ |
54
|
|
|
return $this->getEmptyRelation()->getRelated(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Returns fresh instance of model for each element in form. |
59
|
|
|
* |
60
|
|
|
* @return \Illuminate\Database\Eloquent\Model |
61
|
|
|
*/ |
62
|
|
|
protected function getFreshModelForElements() |
63
|
|
|
{ |
64
|
|
|
$class = get_class($this->getEmptyRelation()->getRelated()); |
65
|
|
|
|
66
|
|
|
return new $class(); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|