Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

always try to return a real makeNewEmptyModel #682

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/Kris/LaravelFormBuilder/Fields/CollectionType.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Kris\LaravelFormBuilder\Fields;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Collection;

class CollectionType extends ParentType
Expand Down Expand Up @@ -178,7 +179,34 @@ protected function makeEmptyRowValue()

protected function makeNewEmptyModel()
{
return value($this->getOption('empty_model'));
if ($empty = $this->getOption('empty_model')) {
return value($empty);
}

$parent = $this->getParent()->getModel();
if ($parent instanceof Model) {
if (method_exists($parent, $this->name)) {
$relation = call_user_func([$parent, $this->name]);
if ($relation instanceof Relation) {
$model = $relation->getRelated()->newInstance()->setAttribute(
$relation->getForeignKeyName(),
$parent->{$relation->getLocalKeyName()}
);
return $model;
}
}
}

if (($data = $this->getOption('data')) && count($data)) {
foreach ($data as $model) {
if ($model instanceof Model) {
return new $model;
}
break;
}
}

return null;
}

protected function formatInputIntoModels(array $input, array $originalData = [])
Expand Down