Tricks

Pass data from page to widget

Aug 2, 2022
Andrew Peacock
Admin panel

You can assign custom data to a widget as follows.

Also, remember that the $record is already exposed to livewire.

<?php
namespace App\Filament\Widgets;
 
use Filament\Widgets\Widget;
 
class NewWidget extends Widget
{
public $widgetData;
 
protected static string $view = 'widgets.new-widget';
 
protected int | string | array $columnSpan = 12;
 
public function mount(): void
{
$this->widgetData = [
'custom_title' => "Your Title Here",
'custom_content' => "Your content here"
];
}
}

Then for the view:

<x-filament::widget>
<x-filament::card>
<x-slot name="heading">
{{ $widgetData["custom_title"] }}
</x-slot>
 
{{ $widgetData["custom_content"] }}
</x-filament::card>
</x-filament::widget>
avatar

Filament already have a method pass data to the view, no need to create a custom method for this. Simply add this to your widget:

protected function getViewData(): array
{
return [
'custom_title' => 'Your title here',
'custom_content' => 'Your content here'
];
}

then in the view, just:

<x-filament::widget>
<x-filament::card>
<x-slot name="heading">
{{ $custom_title }}
</x-slot>
 
{{ $custom_content }}
</x-filament::card>
</x-filament::widget>
avatar

but how to pass data from an edit page or view page to the widget other than the record?

avatar

Had the same question. Looking at the view-record page source code, $record is being exposed to the widget via this line

:widget-data="['record' => $record]"

Your can probably copy the the blade file into your own directory, add any data to the prop and overwrite the

protected static string $view = 'path-to-the-copied-view'

in either your Edit or View page.

avatar
Eugene van der Merwe

This is an incredibly useful tips for many reasons:

  1. It helped me understand I could just deploy a new widget based on an existing widget. From there I used the tip about public ?Model $record = null; and commented out getData() and getType() and viola, new widget based on existing widget but just linked to another record.
  2. The mount function is where the action is.

So I have this:

class NasWidget extends DiskIoChart { public ?Model $record = null; protected static ?string $heading = 'Chart';

public function mount(): void
{
$this->record = Server::find(6);
}

Thanks for the tips! Ps I really tried getting the code formatting right but I don't know how.