Trauma Zombie
Trauma Zombie
Explore posts from servers
FFilament
Created by Trauma Zombie on 6/12/2024 in #❓┊help
Loading wrong model on infolist
Hey guys, I found some strange behavior in my app and I can't help it. I am trying to load all direct children and authenticated user here:
// UserResource.php
/** @return Builder<User> */
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->when(
auth()->user()->hasRole(UserRole::Broker),
fn (Builder $query) => $query
->where('parent_id', '=', auth()->id())
->orWhere('id', auth()->id()),
);
}
// UserResource.php
/** @return Builder<User> */
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->when(
auth()->user()->hasRole(UserRole::Broker),
fn (Builder $query) => $query
->where('parent_id', '=', auth()->id())
->orWhere('id', auth()->id()),
);
}
Inside my users table I see 3 users: Parent (auth one), Child 1 and Child 2. When I click on parent or child 1, I see infolist for these models, but when I click on child 2 it still give me infolist with child 1. Although I can see child id 2 in the url. I am using this package: https://github.com/staudenmeir/laravel-adjacency-list Can you help point me in the right direction?
2 replies
FFilament
Created by Trauma Zombie on 5/30/2024 in #❓┊help
Where to send notification after relationship created
Hi guys, I have two simple models: Task and User. There is belongsToMany relationship between these two. In my Task resource I have Select::multiple() and also UsersRelationManager. In User resource I have TasksRelationManager. I want to send notification each time new user is assigned to task. Where do you suggest to place this part? I tried it inside TaskObserver on created method, but Filament is saving relationships after first commit, so there is no $task->users on created method.
3 replies
FFilament
Created by Trauma Zombie on 5/14/2024 in #❓┊help
How to correctly typehint or set return types for IDE support and autocomplete?
Hi guys, I create small macro for all fields and entries:
// FilamentServiceProvider.php

ViewComponent::macro('warningHint', function (\Closure|bool|null $condition, \Closure|string|null $message): static {
return $this->hintIcon($condition ? 'heroicon-c-exclamation-triangle' : null)
->hintColor('yellow')
->hintIconTooltip($message);
});
// FilamentServiceProvider.php

ViewComponent::macro('warningHint', function (\Closure|bool|null $condition, \Closure|string|null $message): static {
return $this->hintIcon($condition ? 'heroicon-c-exclamation-triangle' : null)
->hintColor('yellow')
->hintIconTooltip($message);
});
But I still have these warnings: Method 'hintIcon' not found in FilamentServiceProvider|\Filament\Support\Components\ViewComponent Method 'warningHint' not found in \Filament\Forms\Components\Toggle
4 replies
FFilament
Created by Trauma Zombie on 5/13/2024 in #❓┊help
How to disable toggables on table?
Hi guys, I have multiple resuable columns, but on some tables I want to disable toggability of that table. I know, I can set $table->searchable(false) to disable searchbar, but how to disable button for toggling columns on table (not on separate columns)?
7 replies
FFilament
Created by Trauma Zombie on 4/23/2024 in #❓┊help
Notify user assigned or detached using Select
Hi guys, I have model Task and model User.
class Task extends Model
{
public function users(): Relations\BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('assigned_at')
->withCasts(['assigned_at' => 'datetime'])
->withTimestamps();
}
}
class Task extends Model
{
public function users(): Relations\BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('assigned_at')
->withCasts(['assigned_at' => 'datetime'])
->withTimestamps();
}
}
Then I have this select component inside TaskResource:
Forms\Components\Select::make('users')
->label('Users')
->relationship('users', 'name')
->searchable()
->preload()
->multiple(),
Forms\Components\Select::make('users')
->label('Users')
->relationship('users', 'name')
->searchable()
->preload()
->multiple(),
Is it even possible to notify only assigned or detached users using this Select? I probably know how to do that via relation manager and button Attach and Detach, but I want to do it via this Select.
4 replies
FFilament
Created by Trauma Zombie on 3/27/2024 in #❓┊help
Relationship not saved when using createOptionUsing on Select input
Hi guys, I am trying to create subject via select input with createOptionForm. Inside that form is another relationship (seller), that is not saved when I chain createOptionUsing method. When I remove that method seller relationship is saved correctly, but I also need to save broker_id (user) to that subject, thats why I use createOptionUsing method. Can you help me?
Forms\Components\Select::make('subject_id')
->label(__('Subject'))
->relationship('subject', 'name')
->createOptionForm(static::getSubjectFields())
->createOptionUsing(function (array $data, Forms\Get $get): int {
$user = User::find($get('broker_id')) ?? auth()->user();

return $user->subjects()->create($data)->getKey();
})
->saveRelationshipsUsing(function (Select $component, Model $record, $state) {
dump($component, $record, $state);
})
->saveRelationshipsBeforeChildrenUsing(function (Select $component, Model $record, $state) {
dump($component, $record, $state);
}),
Forms\Components\Select::make('subject_id')
->label(__('Subject'))
->relationship('subject', 'name')
->createOptionForm(static::getSubjectFields())
->createOptionUsing(function (array $data, Forms\Get $get): int {
$user = User::find($get('broker_id')) ?? auth()->user();

return $user->subjects()->create($data)->getKey();
})
->saveRelationshipsUsing(function (Select $component, Model $record, $state) {
dump($component, $record, $state);
})
->saveRelationshipsBeforeChildrenUsing(function (Select $component, Model $record, $state) {
dump($component, $record, $state);
}),
2 replies
FFilament
Created by Trauma Zombie on 3/26/2024 in #❓┊help
Stream PDF to response
Hi guys, can you help me stream PDF to response directly from action? Is it even possible? Should I save my PDF firstly?
Action::make('generateReport')
->form([
DatePicker::make('from')
->required(),

DatePicker::make('to')
->required(),
])
->action(fn (array $data) => app(GenerateReportAction::class)->execute($data['from'], $data['to']))
Action::make('generateReport')
->form([
DatePicker::make('from')
->required(),

DatePicker::make('to')
->required(),
])
->action(fn (array $data) => app(GenerateReportAction::class)->execute($data['from'], $data['to']))
class GenerateReportAction
{
public function execute(mixed $from, mixed $to)
{
return pdf()
->view('print.report')
->name('report.pdf');
}
}
class GenerateReportAction
{
public function execute(mixed $from, mixed $to)
{
return pdf()
->view('print.report')
->name('report.pdf');
}
}
I am using Spatie Laravel PDF: https://spatie.be/docs/laravel-pdf/v1/basic-usage/responding-with-pdfs
2 replies
FFilament
Created by Trauma Zombie on 3/20/2024 in #❓┊help
How to set value to createOptionForm from another field?
Hi guys, I need a little help from you. This is part of my contract form. I have two selects: broker and client. For client select I have createOptionForm for modal creation of client. When I set broker_id in first select I want to use it as broker_id in the createOptionForm. I dont know how. Right now, it will probably get value from the same hidden input. It is null on fill, so it gets null.
// ContractResource form()

Forms\Components\Select::make('broker_id') // this is broker_id on contract model
->label(__('Broker'))
->options(User::pluck('name', 'id'))
->default(auth()->id())
->dehydrated()
->live(),

Forms\Components\Select::make('client_id')
->label(__('Client'))
->relationship('client')
->createOptionForm([
Forms\Components\Hidden::make('broker_id') // this is broker_id on client model
->dehydrateStateUsing(fn (null $state, Forms\Get $get) => $get('broker_id')),

Forms\Components\Group::make()
->schema([
PhoneInput::make()
->required(),

EmailInput::make()
->required(),
]),
])
->createOptionModalHeading(__('Create new client')),
// ContractResource form()

Forms\Components\Select::make('broker_id') // this is broker_id on contract model
->label(__('Broker'))
->options(User::pluck('name', 'id'))
->default(auth()->id())
->dehydrated()
->live(),

Forms\Components\Select::make('client_id')
->label(__('Client'))
->relationship('client')
->createOptionForm([
Forms\Components\Hidden::make('broker_id') // this is broker_id on client model
->dehydrateStateUsing(fn (null $state, Forms\Get $get) => $get('broker_id')),

Forms\Components\Group::make()
->schema([
PhoneInput::make()
->required(),

EmailInput::make()
->required(),
]),
])
->createOptionModalHeading(__('Create new client')),
2 replies
FFilament
Created by Trauma Zombie on 3/6/2024 in #❓┊help
Reusable sections
Hi, I was wondering how you usually create reusable parts for example e.g. infolists or forms? For example I create my own AddressEntry that I am using on multiple resources. The problem comes when I need to access the Address model. This is my demo custom entry:
<?php

namespace App\Filament\Components\Infolists\Entries;

class AddressEntry
{
public static function make(string $name = 'address'): Entry
{
return TextEntry::make($name)
->label(__('Address'))
->hintAction(
Action::make('openMaps')
->url(fn (Model $record) => match (true) {
$record instanceof User => 'https://google.com/maps/place/'.$record->address->street,
$record instanceof Client => 'https://google.com/maps/place/'.$record->user->address->street,
default => 'https://google.com/maps/place/'.$record->street,
})
->openUrlInNewTab(),
);
}
}
<?php

namespace App\Filament\Components\Infolists\Entries;

class AddressEntry
{
public static function make(string $name = 'address'): Entry
{
return TextEntry::make($name)
->label(__('Address'))
->hintAction(
Action::make('openMaps')
->url(fn (Model $record) => match (true) {
$record instanceof User => 'https://google.com/maps/place/'.$record->address->street,
$record instanceof Client => 'https://google.com/maps/place/'.$record->user->address->street,
default => 'https://google.com/maps/place/'.$record->street,
})
->openUrlInNewTab(),
);
}
}
Model in my closure in url method is taken from resource, when I use it on UserResource, it is User etc. It kinda works, but I don't like this implementation. Do you know better way?
27 replies
FFilament
Created by Trauma Zombie on 3/6/2024 in #❓┊help
Nested relation form
Hi guys, is it possible to create form with nested relations?
// ClientResource.php

Forms\Components\Section::make()
->relationship('entity')
->schema([
// Fields on the entity model

Forms\Components\Section::make()
->relationship('address')
->schema([
// Fields on the address model
])
]),
// ClientResource.php

Forms\Components\Section::make()
->relationship('entity')
->schema([
// Fields on the entity model

Forms\Components\Section::make()
->relationship('address')
->schema([
// Fields on the address model
])
]),
On my ClientResource I have form like this. My entity model is created, but address model is not. I am not sure, if it is even possible.
19 replies
FFilament
Created by Trauma Zombie on 2/27/2024 in #❓┊help
How to pass record to table row action?
Hi guys, I am trying dynamically create actions for my table rows:
public function table(Table $table): Table
{
return parent::table($table)
->columns([...])
->actions([
Tables\Actions\ActionGroup::make([
[...$this->getContractStatusActions(fn (Contract $record) => $record)],
]),
]);
}

private function getContractStatusActions(\Closure $closure): array
{
/** @var Contract $contract */
$contract = $closure();

$nextState = $contract->status->getNextState();

return collect($nextState)
->map(function (ContractStatus $state) use ($contract) {
return Tables\Actions\Action::make('updateStatus')
->label($state->getLabel())
->action(fn () => $contract->update(['status' => $state]));
})
->toArray();
}
public function table(Table $table): Table
{
return parent::table($table)
->columns([...])
->actions([
Tables\Actions\ActionGroup::make([
[...$this->getContractStatusActions(fn (Contract $record) => $record)],
]),
]);
}

private function getContractStatusActions(\Closure $closure): array
{
/** @var Contract $contract */
$contract = $closure();

$nextState = $contract->status->getNextState();

return collect($nextState)
->map(function (ContractStatus $state) use ($contract) {
return Tables\Actions\Action::make('updateStatus')
->label($state->getLabel())
->action(fn () => $contract->update(['status' => $state]));
})
->toArray();
}
I am still getting this error: Too few arguments to function App\Filament\Resources\ContractResource\Pages\ListContracts::App\Filament\Resources\ContractResource\Pages\{closure}(), 0 passed in /Users/me/Developer/Sites/leasing/app/Filament/Resources/ContractResource/Pages/ListContracts.php on line 91 and exactly 1 expected
5 replies
FFilament
Created by Trauma Zombie on 2/26/2024 in #❓┊help
Conditional steps on wizard
Hi guys, is it possible to make conditional steps on wizard? Right now I have this wizard on my CreateClient component:
protected function getSteps(): array
{
return [
Forms\Components\Wizard\Step::make(__('General'))
->schema([
Forms\Components\ToggleButtons::make('type')
->label(__('Type'))
->options(ClientType::class)
->required()
->inline()
->columnSpan(4),
]),

Forms\Components\Wizard\Step::make(__('Individual'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'individual'),

Forms\Components\Wizard\Step::make(__('Self-employed'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'self-employed'),

Forms\Components\Wizard\Step::make(__('Company'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'company'),

Forms\Components\Wizard\Step::make(__('Representative'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'company'),

Forms\Components\Wizard\Step::make(__('Attachments'))
->schema([]),

Forms\Components\Wizard\Step::make(__('Address'))
->schema(Address::make()),
];
}
protected function getSteps(): array
{
return [
Forms\Components\Wizard\Step::make(__('General'))
->schema([
Forms\Components\ToggleButtons::make('type')
->label(__('Type'))
->options(ClientType::class)
->required()
->inline()
->columnSpan(4),
]),

Forms\Components\Wizard\Step::make(__('Individual'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'individual'),

Forms\Components\Wizard\Step::make(__('Self-employed'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'self-employed'),

Forms\Components\Wizard\Step::make(__('Company'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'company'),

Forms\Components\Wizard\Step::make(__('Representative'))
->schema([])
->visible(fn (Forms\Get $get) => $get('type') === 'company'),

Forms\Components\Wizard\Step::make(__('Attachments'))
->schema([]),

Forms\Components\Wizard\Step::make(__('Address'))
->schema(Address::make()),
];
}
Problem is, when I select company as a type in general step, after clicking next button it will jump to Attachments step and skips steps Company and Representative.
2 replies
FFilament
Created by Trauma Zombie on 2/20/2024 in #❓┊help
Sub navigation only on ViewRecord
Hi guys, is it possible to use subNavigation only on ViewRecord and not use it also for EditRecord?
1 replies
FFilament
Created by Trauma Zombie on 2/19/2024 in #❓┊help
Toggle without mass assignement
Hi guys, I want to add toggle to my UserResource and use value from it in afterCreate hook to generate and send password via email. But I dont want to have this value from toggle saved on model.
// UserResource.php
Forms\Components\Toggle::make('send_credentials')
->label(__('Send user email with credentials'))
->visibleOn('create'),
// UserResource.php
Forms\Components\Toggle::make('send_credentials')
->label(__('Send user email with credentials'))
->visibleOn('create'),
// CreateUser.php
public function afterCreate(): void
{
ray($this->send_credentials);
}
// CreateUser.php
public function afterCreate(): void
{
ray($this->send_credentials);
}
How can I prevent this error: Add fillable property [send_credentials] to allow mass assignment on [App\Models\User]. and access that property on afterCreate hook?
11 replies
FFilament
Created by Trauma Zombie on 2/16/2024 in #❓┊help
Is it possible to make searchable column on relation?
Hi guys, is it possible to search on table on relation?
Tables\Columns\TextColumn::make('clientable.name')
->label(__('Name'))
->icon(fn (Client $record) => match($record->clientable->getMorphClass()) {
'person' => 'heroicon-o-user',
'company' => 'heroicon-o-building-library',
})
->searchable(['clientable.name']),
Tables\Columns\TextColumn::make('clientable.name')
->label(__('Name'))
->icon(fn (Client $record) => match($record->clientable->getMorphClass()) {
'person' => 'heroicon-o-user',
'company' => 'heroicon-o-building-library',
})
->searchable(['clientable.name']),
3 replies
FFilament
Created by Trauma Zombie on 2/15/2024 in #❓┊help
Separate policies for Filament?
Hi guys, is it possible to create in Laravel or Filament separate policies for administration? I am using policies on frontend, but I want different ones for administration.
1 replies
FFilament
Created by Trauma Zombie on 1/10/2024 in #❓┊help
How to show simple array on view page?
Hey guys, in my model I have simple array attribute answers in this format:
[
"Gender" => "male",
"Age" => "24",
...
]
[
"Gender" => "male",
"Age" => "24",
...
]
I want to display it in my resource view page:
Infolists\Components\Section::make(__('Answers'))
->icon('heroicon-o-question-mark-circle')
->schema([
Infolists\Components\RepeatableEntry::make('answers')
->hiddenLabel()
->schema([
Infolists\Components\TextEntry::make('0')
->label(__('Question')),

Infolists\Components\TextEntry::make('1')
->label(__('Answer')),
]),
])
->collapsible(),
Infolists\Components\Section::make(__('Answers'))
->icon('heroicon-o-question-mark-circle')
->schema([
Infolists\Components\RepeatableEntry::make('answers')
->hiddenLabel()
->schema([
Infolists\Components\TextEntry::make('0')
->label(__('Question')),

Infolists\Components\TextEntry::make('1')
->label(__('Answer')),
]),
])
->collapsible(),
Can you help me, how to do it correctly?
6 replies
FFilament
Created by Trauma Zombie on 8/11/2023 in #❓┊help
How to use AttachAction with Translatable resource?
Hey guys, I have resource Diagnosis that has SymptomsRelationManager. Symptoms are translatable via Spatie Translatable. I have AttachAction, but it returs to me objects as records. How can I set it tu currently activeLocale?
class SymptomsRelationManager extends RelationManager
{
use Translatable;

#[Reactive]
public ?string $activeLocale = null;

public function table(Table $table): Table
{
return $table
->headerActions([
Tables\Actions\AttachAction::make()
->preloadRecordSelect(),
...
]);
}
class SymptomsRelationManager extends RelationManager
{
use Translatable;

#[Reactive]
public ?string $activeLocale = null;

public function table(Table $table): Table
{
return $table
->headerActions([
Tables\Actions\AttachAction::make()
->preloadRecordSelect(),
...
]);
}
2 replies
FFilament
Created by Trauma Zombie on 8/1/2023 in #❓┊help
Update product fires 3 saved events
Hi guys, when I save product that belongs to category and manufacturer, it fires three times saved event on model Product? What am I doing wrong?
Forms\Components\Card::make()
->schema([
Forms\Components\Select::make('category_id')
->label(__('Category'))
->relationship('category', 'name'),

Forms\Components\Select::make('manufacturer_id')
->label(__('Manufacturer'))
->relationship('manufacturer', 'name'),
]),
Forms\Components\Card::make()
->schema([
Forms\Components\Select::make('category_id')
->label(__('Category'))
->relationship('category', 'name'),

Forms\Components\Select::make('manufacturer_id')
->label(__('Manufacturer'))
->relationship('manufacturer', 'name'),
]),
6 replies
FFilament
Created by Trauma Zombie on 7/27/2023 in #❓┊help
Separate methods
Hi, guys, is it possible to separate infolist and table to View and List page? I have really long resources will all of these in one place.
14 replies