Search code examples
phplaravelcallbackframeworkslaravel-filament

Filament PHP v3: Id does not get written in the database on disabled form-field


I am currently working on a Filament PHP app and I have a problem: I want to show the username of the creator of a note (in my case) and I want to make the field unmodifiable in Filament. So I have thought of this:

        Select::make('user_id')
                            ->options([
                                User::query()
                                    ->select([
                                        DB::raw("name as name"),
                                        'id',
                                    ])
                                    ->where('id', auth()->id())
                                    ->pluck('name', 'id')
                                    ->toArray()
                            ])
                            ->default(
                                auth()->id()
                            )->label(__('messages.created_by'))
                            ->disabled(),

If i disable the field nothing gets written to the database. I get basically null.

Is there a way to disable the Field and ensure that the user_id gets written into the database?


Solution

  • Disabled HTML inputs will not submit.

    The Boolean disabled attribute, when present, makes the element not mutable, focusable, or even submitted with the form.

    You can consider using readOnly with default, but it's not available on select, and it's reasonable since if it's a select, how can it be a readOnly field?

    You may want to use a text input with default values like below:

    Forms\Components\TextInput::make('user_id')
        ->default(
            auth()->id()
        )
        ->readOnly()
        ->label(__('messages.created_by')),
    

    Updated: If you want to show the user's name you can use two inputs as below:

    Forms\Components\Hidden::make('user_id')
        ->default(
            auth()->id()
        ),
    
    Forms\Components\TextInput::make('user_name')
        ->default(
            auth()->user()->name
        )
        ->label(__('messages.created_by'))
        ->disabled(),
    

    A hidden user id beside showing the user's name

    Update 2: You can use mutateFormDataBeforeCreate in your Create page and customize form data before creating the object. You will need that user's name field from the previous solution, and for the user's id, use the below solution. Here's an example:

    ...
    use Filament\Facades\Filament;
    
    
    class CreatePost extends CreateRecord
    {
        ...
        protected function mutateFormDataBeforeCreate(array $data): array
        {
            $data['user_id'] = Filament::auth()->id();;
            return $data;
        }
    }
    

    Saving sensitive data in this manner is more secure.