Seeding a grid field type
Created 7 years ago by dominiqueI've made a module which has "types" to which you can assign multiple fields. For example an image or title. Seeding that isn't that difficult:
Fields migration for types:
'title' => [
'type' => 'anomaly.field_type.text',
'locked' => 0,
],
'image' => [
'type' => 'anomaly.field_type.file',
'locked' => 0,
'config' => [
'image' => true
]
],
Seeder:
public function run()
{
$this->types->truncate();
/* @var TypeModel $type */
$type = $this->types
->create(
[
'name' => 'Example type',
'description' => 'Just an example type.',
'slug' => 'no_text',
'layout' => '<h1> Example </h1>'
]
);
$this->addTitleAndImageToType($type, false);
}
private function addTitleAndImageToType($type, $withTitle = true)
{
$stream = $type->getEntryStream();
if ($withTitle) {
$this->assignments->create(
[
'stream' => $stream,
'field' => $this->fields->findBySlugAndNamespace('title', 'portfolio')
]
);
}
$this->assignments->create(
[
'stream' => $stream,
'field' => $this->fields->findBySlugAndNamespace('image', 'portfolio')
]
);
}
This works great but now I want to have some types which have grids assigned to them. How would I go about seeding a new grid field type?
In my fields migration I added this:
'column_grid' => [
'type' => 'anomaly.field_type.grid',
'locked' => 0, // used with seeded blocks
]
And in my seeder now looks like this:
public function run()
{
$this->deleteStreamIfExsits('columns_blocks');
$this->types->truncate();
/* @var TypeModel $type */
$type = $this->types
->create(
[
'name' => 'Columns',
'description' => 'A row of columns containing images, videos or text.',
'slug' => 'columns',
'layout' => 'TO DO',
]
);
$this->addGridToType($type);
}
public function addGridToType($type){
$stream = $type->getEntryStream($type);
$grid = $this->assignments->create(
[
'stream' => $stream,
'field' => $this->fields->findBySlugAndNamespace('column_grid', 'portfolio')
]
);
$grid->column_grid()->create(
new GridModel([
'entry' => new GridsExampleEntryModel($attributes),
'related' => $entry
])
);
}
which gives me this error
Call to undefined method Illuminate\Database\Query\Builder::column_grid()
What am I doing wrong here?
Do you have eager loading or something setup somewhere? Looks like column_grid
is being eager loaded as that instead of the relation method which is columnGrid
.
Check out the actual model classes you're referencing - the relation methods will be listed. It's normal Eloquent. See if you can dig in and find what you need - I've put you on the right track 😊
Seeding a Grid relationship isn't a whole lot different than seeding any other relationship.
If your field is called
grids
then you would still do$entry->grids()->create($grid);
The
$grid
model is an instance ofAnomaly\GridFieldType\Grid\GridModel
which has a polymorphic relation that holds the actual row data.Not tested but something like this: