0

I'm doing a dashboard using FilamentPhp. I have a resource for authors and a resource for elements created by those authors. In the elements resource I have:

Forms\Components\Select::make('author_id')->relationship('author', 'name')

Now I want to be able to create an author without leaving the element create/edit form. I found that the component has a createOptionForm method that allows to do what I want but it recives a new form schema. Are there any way to call the one already existing in the authors resource?

I have tried sending this funcion the resource, the action, the url, but I can't get it to work withou copying the whole form. I don't like this solution because it doubles the maintenance time of the authors section and I have some more cases like that.

Branpg
  • 3
  • 2

1 Answers1

0

You can do it this way:

    $authorForm = new Form;

    $authorForm = AuthorResource::form($authorForm);

    return $form
        ->schema([

            Forms\Components\Select::make('author_id')
                ->label('Author')
                ->relationship('author', 'name')
                ->createOptionForm($authorForm->getSchema()),
        ]);

This way you first instanciate a form from your resource, then on your select use the schema for this resource by 'getSchema' method.

Edit:

No longer working on Filament V3.0. New walkaround I found is:

Create a controller AuthorForm. On it, create a "getForm()" static method. It should return form array like this:

        class AuthorForm extends Controller
        {
                static function getForm() : array {
                        return [
                                Forms\Components\TextInput::make("name"),
                                Forms\Components\TextInput::make("last_name"),
                                /*...*/
                        ];
                }
        }

Then, just call that method whenever you need the form:


        return $form
        ->schema([

            Forms\Components\Select::make('author_id')
                ->label('Author')
                ->relationship('author', 'name')
                ->createOptionForm(AuthorForm::getForm()),
        ]);

This works also for repeaters or in relationship managers.

Of course, you should use it on the main resource as well, so you only need to do maintenance of form in one place:


class AuthorResource extends Resource
{

    public static function form(Form $form): Form
    {
        return $form
            ->schema(AuthorForm::getForm());
    }

    /*...*/
}

Sergio RC
  • 16
  • 2