Spatie Tags always creates new tag in form
I have a form for a model resource, where I use this Input:
My problem is that it not only doesn't suggest anything (this can be solved with adding
->suggestions(Tag::where('type', 'teacherTag')->pluck('name')->toArray())
) but it always creates a new tag which completly defies the idea of tags.
My top priority is not to create tags in the form but to attach existing ones.
How could that be done?3 Replies
I'm interested in this as well, but it seems the idea behind tags is to let users create new ones. I'm esploring using the Select component, but it needs work apparently...
I'm also looking for display suggestions when user Typing.
This is not working for me...
I solved with a (ugly) workaround
in a service I've added
public static function tagsSchema($name, $type, $label, bool $required = false, bool $multiple = true, bool $searchable = false)
{
$tagName = $name . '_tags';
return [ // these two fields goes together
Select::make($name)
->label($label)
->multiple($multiple)
->preload()
->searchable($searchable)
->afterStateUpdated(function (\Filament\Forms\Set $set, $state) use ($tagName, $multiple) {
$tagsNames = [];
if ($multiple){
foreach ($state as $tagId) {
$tagsNames[] = Tag::find($tagId)->name;
}
} else {
$tagsNames []= Tag::find($state)->name;
}
$set($tagName, $tagsNames);
})
->relationship(name: 'tags', titleAttribute: 'name', modifyQueryUsing: function (Builder $query) use ($type) {
return $query->where('type', $type);
})
->saveRelationshipsUsing(fn () => true)
->options(fn () => Tag::getWithType($type)->pluck('name', 'id'))
->dehydrated(false)
->required($required)
->live(debounce: 500),
Fieldset::make('')
->schema([
SpatieTagsInput::make($tagName)
->type($type)
->label('')
->id('tagsinput-'.$tagName)
->required($required)
])
->extraAttributes(['style' => 'display:none !important; visibility: hidden !important'])
];
}
and
public static function tagsGrid($name, $type, $label, bool $required = false, bool $multiple = true, bool $searchable = false, $hintIcon = null, $hintTooltip = null)
{
$grid=Grid::make(1)->schema(
self::tagsSchema($name, $type, $label, $required, $multiple, $searchable),
)->id('tagsgrid-'.$name)->columns(1)->columnSpan(1);
if ($hintIcon != null) {
$children = $grid->getChildComponents();
foreach ($children as $id => $child){
if (get_class($child) == Select::class){
$child->hintIcon(icon: $hintIcon, tooltip: $hintTooltip);
}
}
$grid->childComponents($children);
}
return $grid;
}
I use the second method to add them in the forms
so basically the SpatieTagsInput is hidden, and a normal select is shown instead, but the SpatieTagsInput is filled with the element selected from the Select, and only the SpatieTagsInput is actually sent to database (the Select has ->dehydrated(false))