Load Schema / Reuse Schema
Hello All,
Is there any better / official way to load or reuse schema to avoid code duplication?
currently, I am doing it by storing it in a class inside App\Filament\Schema namespace.
<?php
namespace App\Filament\Schema;
use Closure;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Squire\Models\Timezone;
class EventTypeScheduleSchema
{
function getSchema() : array {
return [ //schema ];
}
}
and in actual form method
->createOptionForm($etschema->getSchema())
Could you please help with this? π
Thank you.
11 Replies
I don't know of an official way to do this, but I do the same thing you do. When I have a schema I need to use multiple times, I put it in a function and then call the function when I need it
I actually like your solution of creating
App/Filament/Schema
I'm going to start putting my functions in that namespacePut this in the resource class (like UserResource) as static function and reuse it anywhere by calling
UserResource::getSchema()
I don't think there is an "official" way, or even a recommended way. I've done something similar.
You could extend your Schema to some Abstract and add a static make().
Or make traits for common schema's (like person, which always has first name, last name, email etc)
Yep, that's what I do most of the time (static methods on the resource)
I've moved to a method of creating my own schema classes for sections of the forms and pulling them in as needed.
then hav Forms\Schemas\
Definitely cleaner if the schemas can be independent of the resources (ex. SeoSchema, or something like that)
Yep, exactly. I need it as the data is used throughout the application but we have the same forms give or take so need a single point of control and then have option params to pass in.
Yup, this is exactly what I do. I add a Resources/Schema namespace for each resource, and call Schema::makeForm(), Schema::makeTable(), Schema::makeFilters() etc from wherever I build those forms/tables.
In v3 the suggestion is to just re-use the form/table method from the resource, although I may stick to the way I do it.
https://beta.filamentphp.com/docs/3.x/panels/resources/relation-managers#sharing-a-resources-form-and-table-with-a-relation-manager
It's kind of nice that there isn't a "special" way of doing it. Just plain PHP... extract to methods, traits, classes, whatever fits your problem better.
Yup. Just functions that return arrays of things.
So the way I do it in v3 resources, where individual getThings() functions in resources are deprecated in favor of the single table() or form() method is ...
... with whatever makeThingSchema() I need.
Also makes the resource a lot cleaner, as I often have very large and complex schemas.
And I built a little artisan command to make:my-filament-schema from a stub.
Nice