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.