Your approach to creating a custom field component for Filament to display a link to the parent model is a reasonable solution. However, there are a few improvements and suggestions that can be made to ensure that your code is clean and follows best practices.
Firstly, it's important to ensure that your custom field component is reusable and flexible. Your current implementation seems to be on the right track, but let's refine it a bit.
Here's an improved version of your Link class:
namespace App\Forms\Components;
use Filament\Forms\Components\Field;
class Link extends Field
{
protected string $view = 'forms.components.link';
protected string|\Closure|null $url = null;
protected string|\Closure|null $text = null;
public function url(string|\Closure|null $url): static
{
$this->url = $url;
return $this;
}
public function text(string|\Closure|null $text): static
{
$this->text = $text;
return $this;
}
public function getUrl(): ?string
{
return $this->evaluate($this->url);
}
public function getText(): ?string
{
return $this->evaluate($this->text);
}
}
And the link.blade.php view:
@props([
'field',
])
<div x-data="{ state: $wire.entangle('{{ $field->getStatePath() }}') }">
<a href="{{ $field->getUrl() }}" class="text-indigo-600 hover:text-indigo-900">
{{ $field->getText() }}
</a>
</div>
When using the Link component in your form, you can do something like this:
use App\Forms\Components\Link;
use App\Filament\Resources\LocalidadeResource;
Link::make('parentLink')
->text(fn (?Model $record): string => $record ? $record->nome : '')
->url(fn (?Model $record): string => $record ? LocalidadeResource::getUrl('view', ['record' => $record]) : '#')
->dehydrated(false) // Prevents the field from being included in the form submission
->disabled(true) // Makes the field non-interactive
->visible(fn (?Model $record): bool => $record !== null); // Only show the link if there is a record
This code snippet creates a Link field that will display a link to the parent model if it exists. The dehydrated(false) method call ensures that the field is not included in the form submission, and disabled(true) makes it non-interactive. The visible method is used to conditionally display the link only if there is a parent record.
Remember to replace Model with the actual model class you are using and adjust the LocalidadeResource and nome to match your actual resource and field names.
This solution should provide a clean and reusable way to include links to parent models in your Filament forms.