Creating Grids Programmatically
- Posted February 14, 2017
- Addon Tutorials
- PRO
- Advanced
Introduction
Grids are simply streams. Therefore creating a grid programmatically is very much the same as creating any other stream programmatically.
Where do I put this?
It is common to place the following code in seeders or migrations but can be done the same anywhere. It really depends on what your application demands are.
Required Repositories
We will need to access the streams, fields, and assignment repositories. For this tutorial we will simply resolve them out of Laravel's service container and set them to as a few variables:
$fields = app(\Anomaly\Streams\Platform\Field\Contract\FieldRepositoryInterface::class);
$streams = app(\Anomaly\Streams\Platform\Stream\Contract\StreamRepositoryInterface::class);
$assignments = app(\Anomaly\Streams\Platform\Assignment\Contract\AssignmentRepositoryInterface::class);
Creating a Grid Stream
Creating a stream for grid is no different than creating any other stream with the StreamRepositoryInterface
. All you need to do is specify grid
as the stream namespace
:
$books = $streams->create(
[
'en' => [
'name' => 'Books',
'description' => 'A grid stream of my favorite books!',
],
'namespace' => 'grid',
'translatable' => true,
]
);
Creating Grid Fields
Creating fields for the Grid namespace is also the same procedure using the FieldRepositoryInterface
. Let's add a couple fields to the grid
namespace:
$title = $fields->create(
[
'en' => [
'name' => 'Title',
'instructions' => 'Specify the title of the book.',
],
'locked' => false,
'namespace' => 'grid',
'slug' => 'title',
'type' => 'anomaly.field_type.text',
]
);
$author = $fields->create(
[
'en' => [
'name' => 'Author',
'instructions' => 'Specify the author of the book.',
],
'locked' => false,
'namespace' => 'grid',
'slug' => 'author',
'type' => 'anomaly.field_type.text',
]
);
Assigning Grid Fields
Now that we have a stream in the grid namespace as well as some fields we need to assign the fields to our stream:
$assignments->create(
[
'stream' => $books,
'field' => $title,
'unique' => true,
'required' => true,
'translatable' => true,
]
);
$assignments->create(
[
'stream' => $books,
'field' => $author,
'required' => true,
]
);
What's next?
Now that we have a grid stream, fields, and have assigned those fields to the stream we can seed grid data. The grid and its fields are also available now for control panel use. Cool!