Typed property Filament\Forms\Components\Component::$container must not be accessed before initialization #21

Open
opened 2023-09-05 04:28:18 +00:00 by rtolinggi · 21 comments
rtolinggi commented 2023-09-05 04:28:18 +00:00 (Migrated from github.com)

I encountered the error "Typed property Filament\Forms\Components\Component::$container must not be accessed before initialization"
while using Filament v3.0-stable and PHP 8.1.

I encountered the error "Typed property Filament\Forms\Components\Component::$container must not be accessed before initialization" while using Filament v3.0-stable and PHP 8.1.
pxlrbt commented 2023-09-05 05:11:46 +00:00 (Migrated from github.com)

Sorry, it's impossible to debug this without any code. What's the form schema for this?

Sorry, it's impossible to debug this without any code. What's the form schema for this?
rtolinggi commented 2023-09-05 05:27:03 +00:00 (Migrated from github.com)

image

![image](https://github.com/pxlrbt/filament-activity-log/assets/86676841/2c49b5a9-d4d3-4974-b352-20d7984104a4)
rtolinggi commented 2023-09-05 05:29:30 +00:00 (Migrated from github.com)
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles, LogsActivity;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    public bool $logFillable = true;
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults();
    }
}

in file UserResource\Pages

<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use pxlrbt\FilamentActivityLog\Pages\ListActivities;

class ListUserActivites extends ListActivities
{
    protected static string $resource = UserResource::class;
}


``` class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable, HasRoles, LogsActivity; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; public bool $logFillable = true; public function getActivitylogOptions(): LogOptions { return LogOptions::defaults(); } } in file UserResource\Pages <?php namespace App\Filament\Resources\UserResource\Pages; use App\Filament\Resources\UserResource; use pxlrbt\FilamentActivityLog\Pages\ListActivities; class ListUserActivites extends ListActivities { protected static string $resource = UserResource::class; } ```
pxlrbt commented 2023-09-05 05:57:24 +00:00 (Migrated from github.com)

That's the User model. Can you please share the form of your UserResource?

That's the User model. Can you please share the form of your UserResource?
rtolinggi commented 2023-09-05 06:02:51 +00:00 (Migrated from github.com)

class UserResource extends Resource
{
protected static ?string $model = User::class;

protected static ?string $navigationIcon = 'heroicon-m-users';

protected static ?string $navigationGroup = 'Pengaturan Pengguna';

protected static ?string $pluralLabel = 'Pengguna';

protected static ?string $label = 'Pengguna';

protected static ?string $modelLabel = 'Pengguna';

protected static ?string $recordTitleAttribute = 'email';

protected static ?int $navigationSort = 100;

public static function form(Form $form): Form
{
    $select = null;
    $roles = auth()->user()->getRoleNames();
    $exclude = ['super_admin', 'Admin Relawan'];
    if ($roles[0] === 'super_admin') {
        $select = Select::make('roles')
            ->label('Peran')
            ->required()
            ->native(false)
            ->preload()
            ->relationship('roles', 'name');
    } else {
        $select = Select::make('roles')
            ->label('Peran')
            ->required()
            ->native(false)
            ->preload()
            ->relationship('roles', 'name', modifyQueryUsing: fn (Builder $query) => $query->whereNotIn('name', $exclude));
    }

    return $form
        ->schema([
            Section::make('Pengguna')
                ->collapsible()
                ->schema([
                    TextInput::make('name')
                        ->label('Nama')
                        ->required(),
                    TextInput::make('email')
                        ->label('Email')
                        ->unique(ignoreRecord: true)
                        ->email()
                        ->required(),
                    TextInput::make('password')
                        ->label(static fn (Page $livewire): string => ($livewire instanceof EditUser) ? 'Kata Sandi Baru' : 'Kata Sandi')
                        ->password()
                        ->minLength(8)
                        ->dehydrateStateUsing(static fn (null|string $state): null|string => filled($state) ? Hash::make($state) : null)
                        ->required(static fn (Page $livewire): string => $livewire instanceof CreateUser)
                        ->maxLength(255)
                        ->dehydrated(static fn (null|string $state): bool => filled($state)),
                    $select,
                ])->columns(2)
        ]);
}

public static function table(Table $table): Table
{
    return $table
        ->columns([
            TextColumn::make('No')->rowIndex()->searchable(isGlobal: false),
            TextColumn::make('name')
                ->label('Nama'),
            TextColumn::make('email')
                ->badge()
                ->color('primary')
                ->label('Email'),
            TextColumn::make('roles.name')
                ->badge()
                ->color('success')
                ->label('Peran')
        ])
        ->filters([
            //
        ])
        ->actions([
            Action::make('activities')->url(fn ($record) => UserResource::getUrl('activities', ['record' => $record])),
            ActionGroup::make([
                ViewAction::make(),
                EditAction::make(),
                DeleteAction::make(),
            ]),
        ])
        ->bulkActions([
            Tables\Actions\BulkActionGroup::make([
                Tables\Actions\DeleteBulkAction::make(),
            ]),
        ])
        ->emptyStateActions([
            Tables\Actions\CreateAction::make(),
        ])
        ->headerActions([
            CreateAction::make()
                ->label('Tambah')
                ->icon('heroicon-m-plus-circle'),
        ]);
}

public static function getRelations(): array
{
    return [
        //
    ];
}

public static function getPages(): array
{
    return [
        'index' => Pages\ListUsers::route('/'),
        'create' => Pages\CreateUser::route('/create'),
        'activities' => Pages\ListUserActivites::route('/{record}/activities'),
        'edit' => Pages\EditUser::route('/{record}/edit'),
    ];
}

// public static function getEloquentQuery(): Builder
// {
//     return parent::getEloquentQuery();
// }

}

class UserResource extends Resource { protected static ?string $model = User::class; protected static ?string $navigationIcon = 'heroicon-m-users'; protected static ?string $navigationGroup = 'Pengaturan Pengguna'; protected static ?string $pluralLabel = 'Pengguna'; protected static ?string $label = 'Pengguna'; protected static ?string $modelLabel = 'Pengguna'; protected static ?string $recordTitleAttribute = 'email'; protected static ?int $navigationSort = 100; public static function form(Form $form): Form { $select = null; $roles = auth()->user()->getRoleNames(); $exclude = ['super_admin', 'Admin Relawan']; if ($roles[0] === 'super_admin') { $select = Select::make('roles') ->label('Peran') ->required() ->native(false) ->preload() ->relationship('roles', 'name'); } else { $select = Select::make('roles') ->label('Peran') ->required() ->native(false) ->preload() ->relationship('roles', 'name', modifyQueryUsing: fn (Builder $query) => $query->whereNotIn('name', $exclude)); } return $form ->schema([ Section::make('Pengguna') ->collapsible() ->schema([ TextInput::make('name') ->label('Nama') ->required(), TextInput::make('email') ->label('Email') ->unique(ignoreRecord: true) ->email() ->required(), TextInput::make('password') ->label(static fn (Page $livewire): string => ($livewire instanceof EditUser) ? 'Kata Sandi Baru' : 'Kata Sandi') ->password() ->minLength(8) ->dehydrateStateUsing(static fn (null|string $state): null|string => filled($state) ? Hash::make($state) : null) ->required(static fn (Page $livewire): string => $livewire instanceof CreateUser) ->maxLength(255) ->dehydrated(static fn (null|string $state): bool => filled($state)), $select, ])->columns(2) ]); } public static function table(Table $table): Table { return $table ->columns([ TextColumn::make('No')->rowIndex()->searchable(isGlobal: false), TextColumn::make('name') ->label('Nama'), TextColumn::make('email') ->badge() ->color('primary') ->label('Email'), TextColumn::make('roles.name') ->badge() ->color('success') ->label('Peran') ]) ->filters([ // ]) ->actions([ Action::make('activities')->url(fn ($record) => UserResource::getUrl('activities', ['record' => $record])), ActionGroup::make([ ViewAction::make(), EditAction::make(), DeleteAction::make(), ]), ]) ->bulkActions([ Tables\Actions\BulkActionGroup::make([ Tables\Actions\DeleteBulkAction::make(), ]), ]) ->emptyStateActions([ Tables\Actions\CreateAction::make(), ]) ->headerActions([ CreateAction::make() ->label('Tambah') ->icon('heroicon-m-plus-circle'), ]); } public static function getRelations(): array { return [ // ]; } public static function getPages(): array { return [ 'index' => Pages\ListUsers::route('/'), 'create' => Pages\CreateUser::route('/create'), 'activities' => Pages\ListUserActivites::route('/{record}/activities'), 'edit' => Pages\EditUser::route('/{record}/edit'), ]; } // public static function getEloquentQuery(): Builder // { // return parent::getEloquentQuery(); // } }
xcalabuig commented 2023-09-06 14:50:23 +00:00 (Migrated from github.com)

same here, using filament v2

same here, using filament v2
zach2825 commented 2023-09-08 00:33:34 +00:00 (Migrated from github.com)

I'm getting that same error; it only happens when the data on the change is an object. If it's an empty array, the page loads.

The top one fails, and the page loads with the bottom one
image

I'm getting that same error; it only happens when the data on the change is an object. If it's an empty array, the page loads. The top one fails, and the page loads with the bottom one ![image](https://github.com/pxlrbt/filament-activity-log/assets/4049321/d467ce2e-5f72-49cc-9994-5f752f0414f0)
pxlrbt commented 2023-09-08 05:46:51 +00:00 (Migrated from github.com)

It's not related to the data but to the form structure. It tries to get the name from the components and fails while accessing one of them. I guess it's a Section or Repeater or similar

It's not related to the data but to the form structure. It tries to get the name from the components and fails while accessing one of them. I guess it's a Section or Repeater or similar
fcno commented 2023-12-22 01:44:34 +00:00 (Migrated from github.com)

Hey @pxlrbt .

I also have the same problem and I can share a very minimalist sequence of steps to reproduce the problem.

Let's assume a UserResource with at least 2 textinput ( 'email' and 'name') and ListUserActivities are in place.

  1. The form that works.
return $form
    ->schema([
        Forms\Components\TextInput::make('email')
            ->live(),

        Forms\Components\Group::make()
            ->schema(function (Forms\Get $get): array {
                return $get('email')
                ? [
                    Forms\Components\TextInput::make('name'),
                ]
                : [];
            }),
    ]);
  1. The form that DONT works. Just surround the form in a Section and $get('email'), will throw the error.
return $form
    ->schema([
    Forms\Components\Section::make(__('User'))
                    ->schema([

            Forms\Components\TextInput::make('email')
                ->live(),

            Forms\Components\Group::make()
                ->schema(function (Forms\Get $get): array {  // throw error
                    return $get('email')
                    ? [
                        Forms\Components\TextInput::make('name'),
                    ]
                    : [];
                }),
          ]),
    ]);
  1. Access the user activities page and you will see the error below caused by $get~
Typed property Filament\Forms\Components\Component::$container must not be accessed before initialization

I hope this helps in resolving the issue, or at least pointing out steps for accurately reproducing the error.

Hey @pxlrbt . I also have the same problem and I can share a very minimalist sequence of steps to reproduce the problem. Let's assume a UserResource with at least 2 textinput ( 'email' and 'name') and ListUserActivities are in place. 1. The form that works. ```php return $form ->schema([ Forms\Components\TextInput::make('email') ->live(), Forms\Components\Group::make() ->schema(function (Forms\Get $get): array { return $get('email') ? [ Forms\Components\TextInput::make('name'), ] : []; }), ]); ``` 2. The form that DONT works. Just surround the form in a Section and $get('email'), will throw the error. ```php return $form ->schema([ Forms\Components\Section::make(__('User')) ->schema([ Forms\Components\TextInput::make('email') ->live(), Forms\Components\Group::make() ->schema(function (Forms\Get $get): array { // throw error return $get('email') ? [ Forms\Components\TextInput::make('name'), ] : []; }), ]), ]); ``` 3. Access the user activities page and you will see the error below caused by $get~ ``` Typed property Filament\Forms\Components\Component::$container must not be accessed before initialization ``` I hope this helps in resolving the issue, or at least pointing out steps for accurately reproducing the error.
edeoliv commented 2024-01-09 00:06:43 +00:00 (Migrated from github.com)

I have the same error in v3

I have the same error in v3
jcaeon commented 2024-01-18 12:45:06 +00:00 (Migrated from github.com)

Hi, I was checking the @fcno theory, then I made a test, I'm using the plugin https://filamentphp.com/plugins/bezhansalleh-shield for roles, so I've changed CheckboxList component to Select component, then it works.

So maybe the problem is in the Form components configuration or construction.

Hi, I was checking the @fcno theory, then I made a test, I'm using the plugin https://filamentphp.com/plugins/bezhansalleh-shield for roles, so I've changed ``CheckboxList`` component to ``Select`` component, then it works. So maybe the problem is in the Form components configuration or construction.
Ray-vV commented 2024-01-29 11:49:28 +00:00 (Migrated from github.com)

Same problem here, I've got a Section in my form and some dependent fields. Doesn't work at all.

Same problem here, I've got a Section in my form and some dependent fields. Doesn't work at all.
fcno commented 2024-01-30 22:05:55 +00:00 (Migrated from github.com)

@pxlrbt It seems that this problem has gone away. I think that some update to the filament core ended up reflexively correcting the problem here.

I'm currently using version 3.2.17 of filament.

As this part of my code was commented out for a long time, I can't say which version of the filament ended up correcting the problem.

@Ray-vV Can u share your code and the filament version? try to use the latest version to see if the problem is gone.

@pxlrbt It seems that this problem has gone away. I think that some update to the filament core ended up reflexively correcting the problem here. I'm currently using version 3.2.17 of filament. As this part of my code was commented out for a long time, I can't say which version of the filament ended up correcting the problem. @Ray-vV Can u share your code and the filament version? try to use the latest version to see if the problem is gone.
pxlrbt commented 2024-01-31 11:24:36 +00:00 (Migrated from github.com)

@pxlrbt It seems that this problem has gone away. I think that some update to the filament core ended up reflexively correcting the problem here.

Hm, interesting. I think there might still be issues with Sections or other Layout fields 🤔

> @pxlrbt It seems that this problem has gone away. I think that some update to the filament core ended up reflexively correcting the problem here. Hm, interesting. I think there might still be issues with Sections or other Layout fields 🤔
Ray-vV commented 2024-02-02 12:44:55 +00:00 (Migrated from github.com)

@pxlrbt It seems that this problem has gone away. I think that some update to the filament core ended up reflexively correcting the problem here.

I'm currently using version 3.2.17 of filament.

As this part of my code was commented out for a long time, I can't say which version of the filament ended up correcting the problem.

@Ray-vV Can u share your code and the filament version? try to use the latest version to see if the problem is gone.

Thanks for the suggestion, I decided to switch to the z3d0x/filament-logger for now. Not necesarrily due to this error however. But it turned out the z3d0x package was already more in the direction of what I wanted to implement into my project.
I could do some testing on a seperate branch with this package if that aids you guys in any way.

> @pxlrbt It seems that this problem has gone away. I think that some update to the filament core ended up reflexively correcting the problem here. > > I'm currently using version 3.2.17 of filament. > > As this part of my code was commented out for a long time, I can't say which version of the filament ended up correcting the problem. > > @Ray-vV Can u share your code and the filament version? try to use the latest version to see if the problem is gone. Thanks for the suggestion, I decided to switch to the z3d0x/filament-logger for now. Not necesarrily due to this error however. But it turned out the z3d0x package was already more in the direction of what I wanted to implement into my project. I could do some testing on a seperate branch with this package if that aids you guys in any way.
nikosid commented 2024-02-03 20:10:30 +00:00 (Migrated from github.com)

Unfortunately the problem is still here. And yes, changing CheckboxList to Select solves the problem.

Unfortunately the problem is still here. And yes, changing CheckboxList to Select solves the problem.
AlexisSerneels commented 2024-04-21 06:06:54 +00:00 (Migrated from github.com)

Same. Sorry.

Same. Sorry.
GORGDEVELOPER commented 2024-09-27 16:11:33 +00:00 (Migrated from github.com)

I had similar problem, so i fixed it by this code (I overwrite createFieldLabelMap method):

protected function createFieldLabelMap(): Collection
   {
       $form = static::getResource()::form(new Form($this));
       $record = $this->getRecord();

       $form->statePath('data');
       $form->fill($record->attributesToArray());
       $form->model($record);

       $components = collect($form->getComponents());
       $extracted = collect();

       while (($component = $components->shift()) !== null) {
           if ($component instanceof Field || $component instanceof MorphToSelect) {
               $extracted->push($component);

               continue;
           }

           $children = $component->getChildComponents();

           if (count($children) > 0) {
               $components = $components->merge($children);

               continue;
           }

           $extracted->push($component);
       }

       return $extracted
           ->filter(fn ($field) => $field instanceof Field)
           ->mapWithKeys(fn (Field $field) => [
               $field->getName() => $field->getLabel(),
           ]);
   }
I had similar problem, so i fixed it by this code (I overwrite createFieldLabelMap method): ``` protected function createFieldLabelMap(): Collection { $form = static::getResource()::form(new Form($this)); $record = $this->getRecord(); $form->statePath('data'); $form->fill($record->attributesToArray()); $form->model($record); $components = collect($form->getComponents()); $extracted = collect(); while (($component = $components->shift()) !== null) { if ($component instanceof Field || $component instanceof MorphToSelect) { $extracted->push($component); continue; } $children = $component->getChildComponents(); if (count($children) > 0) { $components = $components->merge($children); continue; } $extracted->push($component); } return $extracted ->filter(fn ($field) => $field instanceof Field) ->mapWithKeys(fn (Field $field) => [ $field->getName() => $field->getLabel(), ]); } ```
medaminebt commented 2025-07-18 09:53:55 +00:00 (Migrated from github.com)

Same issue, I had to change to CheckboxList to Select, this solves it. thanks @nikosid for the tip !

Same issue, I had to change to CheckboxList to Select, this solves it. thanks @nikosid for the tip !
pxlrbt commented 2025-07-18 10:22:21 +00:00 (Migrated from github.com)

@medaminebt Can you check whether the code from GORGDEVELOPER fixes it, too?

@medaminebt Can you check whether the code from GORGDEVELOPER fixes it, too?
pxlrbt commented 2026-04-28 12:28:30 +00:00 (Migrated from github.com)

I just tried this with a CheckboxList and didn't have any issues. Is this still a problem? Filament v5 and v3.1 of the plugin.

I just tried this with a CheckboxList and didn't have any issues. Is this still a problem? Filament v5 and v3.1 of the plugin.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
pxlrbt/filament-activity-log#21
No description provided.