Field grouping

Twill supports grouping fields in the database using a json column.

Examples:

  • An address section existing out of a street, city and postal code field
  • An external link with Label, url and target
  • ...

Each set of grouped fields requires a column in the database. The grouped fields can be translatable or not.

Migration and Model setup

The migration for adding a grouped field can look like this (using external link as example):

Translatable

1## Add a migration
2Schema::table('blog_translations', function (Blueprint $table) {
3 $table->json('external_link')->nullable();
4});
5 
6## Update your models fillable
7class Blog extends Model {
8 public $translatedAttributes = [
9 ...
10 'external_link'
11 ];
12 
13 protected $fillable = [
14 ...
15 'external_link'
16 ];
17}
18 
19## Update your Translation model and add the cast
20public $casts = [
21 'external_link' => 'array',
22];

Non translatable

1## Add a migration
2Schema::table('blogs', function (Blueprint $table) {
3 $table->json('external_link')->nullable();
4});
5 
6## Update your models fillable
7class Blog extends Model {
8 protected $fillable = [
9 ...
10 'external_link'
11 ];
12}

Field setup

To store the fields you want into the json we have to update the repository:

1protected array $fieldsGroups = [
2 'external_link' => [
3 'link_target',
4 'link_url',
5 'link_label',
6 ],
7];
8 
9# The below can be setup optionally, documented below.
10public bool $fieldsGroupsFormFieldNamesAutoPrefix = false;
11public string $fieldsGroupsFormFieldNameSeparator = '_';

Finally in our model form we can add the fields:

1<x-twill::input
2 name="link_target"
3 label="Link target"
4 :translated="true"
5/>
6 
7<x-twill::input
8 name="link_url"
9 label="Link url"
10 :translated="true"
11/>
12 
13<x-twill::input
14 name="link_label"
15 label="Link label"
16 :translated="true"
17/>

Using the field name separator

In the repository file you can setup the following parameters:

1public bool $fieldsGroupsFormFieldNamesAutoPrefix = true;
2public string $fieldsGroupsFormFieldNameSeparator = '.'; // Default is _

This will automatically group/ungroup these fields based on the separator:

1<x-twill::input
2 name="external_link.link_target"
3 label="Link target"
4 :translated="true"
5/>
6 
7<x-twill::input
8 name="external_link.link_url"
9 label="Link url"
10 :translated="true"
11/>
12 
13<x-twill::input
14 name="external_link.link_label"
15 label="Link label"
16 :translated="true"
17/>