Hello.
How can I set a default value (or set of values) for an “entries” field in a Tailor blueprint?
I tried to use the ID number of an entry, but it is not working.
I found the answer by myself, so I share here, in case someone needs it.
The “entries” fields don’t support a default value defined in the blueprint. Instead, you need to set the value programmatically, for instance, in the “boot” method of your custom plugin. Sample code:
// Set default value for 'included_territory' (entries field) when the form is loaded
Event::listen('backend.form.extendFields', function (Form $widget) {
// Only apply to any Tailor content type
if ($widget->model instanceof EntryRecord) {
// Check if this is a new record (not yet saved)
if (!$widget->model->exists) {
// Ensure that the model has the 'included_territory' relation
if ($widget->model->hasRelation('included_territory')) {
// Retrieve the default territory by title
$defaultTerritory = EntryRecord::inSection('Content\Territory')
->where('title', 'World')
->first();
if ($defaultTerritory) {
// Pre-fill the 'included_territory' field with the default value
$widget->model->included_territory = [$defaultTerritory->id];
}
}
}
}
});
Don’t forget to use some traits:
use Tailor\Models\EntryRecord;
use Backend\Widgets\Form;