Skip to content

Commit

Permalink
Select relations are set to null when empty, resolve #45
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlos Morales committed Jan 30, 2017
1 parent 2410635 commit d034acd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Abstractor/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ public function persist(Request $request)


$fields = $this->getEditFields(true);
$foreignFields = array_diff_key($fields['main'], $this->getEditFields(false)['main']);
if (empty($fields['main']) && $this->getRelations()->isEmpty()) {
return;
}
Expand All @@ -412,6 +413,10 @@ public function persist(Request $request)
$fieldName = $field->getName();
$requestValue = $request->input("main.{$fieldName}");

if (! empty($foreignFields) && (! empty($foreignFields[$fieldName])) && (empty($requestValue))) {
$requestValue = null;
}

if (get_class($field->getFormField()) === \FormManager\Fields\Checkbox::class) {
if (empty($requestValue)) {
// Unchecked checkboxes are not sent, so we force setting them to false
Expand Down Expand Up @@ -439,7 +444,10 @@ public function persist(Request $request)
continue;
}

if (! empty($requestValue) || (empty($requestValue) && ! empty($item->getAttribute($fieldName)))) {
if (! empty($requestValue)
|| (empty($requestValue) && !empty($item->getAttribute($fieldName)))
|| (! empty($foreignFields) && (! empty($foreignFields[$fieldName])) && (empty($requestValue)))
) {
$item->setAttribute(
$fieldName,
$field->applyFunctions($requestValue)
Expand Down
8 changes: 8 additions & 0 deletions tests/Abstractor/Eloquent/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,14 @@ public function test_persist()
$fieldMock,
]
]);
$this->sut->shouldReceive('getEditFields')->times(1)->with(false)->andReturn([
'main' => [
$fieldMock,
$fieldMock,
$fieldMock,
$fieldMock,
]
]);

$this->sut->shouldReceive('getRelations')->andReturn(collect(['group' => $relationMock = $this->mock('\Anavel\Crud\Abstractor\Eloquent\Relation\Relation')]));

Expand Down

0 comments on commit d034acd

Please sign in to comment.