Spatie Media not saving in filament page
Hi, I am using filament custom page and try to saving data but Spatie Media is not saving automically. Do I need to save manually? of course, how can I control for showing old image?
class CreatePost extends Page implements HasForms
{
use InteractsWithForms;
protected string $view = 'filament.pages.create-post';
SpatieMediaLibraryFileUpload::make('banner')
->label('Banner Image')
->collection('banner')
->disk('public')
->image()
6 Replies
Without seeing the full code make sure your are calling ‘$this->form->fill()’ in the mount method of your custom page.
Make sure you follow the docs: https://filamentphp.com/docs/4.x/components/form#adding-the-form
You are responsible for loading and saving the data.
I am using with custom filament page
https://filamentphp.com/docs/4.x/resources/custom-pages
class CreatePost extends Page implements HasForms
{
use InteractsWithForms;
protected string $view = 'filament.pages.create-post';
/** @var array<string, mixed>|null */
public ?array $data = [];
public function mount(): void
{
$this->form->fill([]);
}
public function form(Schema $schema): Schema
{
return $schema
->components([
Section::make('Section')
->schema([
SpatieMediaLibraryFileUpload::make('banner')
->label('Banner Image')
->collection('banner')
->disk('public')
->image()
]),You need to define
->model(), FileUpload does not know what model/record you're trying to associate the media with, also in your save method you need to first create the record then call ->form->getState() to get the data which dehydrates the field and saves the media to database and saves the relationship as well. I had the same problem and this is how I solved it. Maybe there is a simpler way.Thanks. so, we need to save manually in save method for this case?
just like
public function submit() { $data = $this->form->getState(); $post ->addMedia($file->getRealPath())
->usingFileName($file->getClientOriginalName()) ->toMediaCollection('banner');
You need a
submit / save method to get the data from form and process it. But you don't actually need to explicitly use ->addMedia if you provide ->model($post) to SpatieMediaLibraryFileUpload, it will automatically save the relationship