cube-agency/filament-template

Template field for Filament

v1.0.1 2024-03-12 16:08 UTC

This package is auto-updated.

Last update: 2024-04-12 16:25:52 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Template field for Filament, that gives an option to have different fields based on field value or type in one Resource.

Installation

You can install the package via composer:

composer require cube-agency/filament-template

You can publish the config file with:

php artisan vendor:publish --tag="filament-template-config"

Usage

Add "template" column to your Model/table

$table->string('template');

Create your template by using console command:

php artisan filament-template:create Blog

Add it to config

return [
    'templates' => [
        \App\Filament\Templates\BlogTemplate::class,
    ]
];

At this moment, this could be used by passing url parameter (query string) to create form

class CreatePage extends CreateRecord
{
    public $template;

    protected $queryString = ['template'];
}

and adding this in your Resource

public static function form(Form $form): Form
{
    return $form
        ->schema([
            // ...
            Hidden::make('template')
                ->default($this->getTemplate()),
            Template::make('content')
                ->template($this->resolveTemplate()),
        ]);
}

protected function resolveTemplate()
{
    return app($this->getTemplate());
}

protected function getTemplate()
{
    if (property_exists($this, 'template')) {
         return $this->template;
    }

    return $this->getRecord()->getAttribute('template');
}

Override create action to show modal with template select

public function getActions(): array
{
    return [
        Action::make('create')
            ->form($this->actionForm())
            ->action(function (array $data): void {
                $parameters = http_build_query($data);
    
                $this->redirect(static::$resource::getUrl('create') . '?' . $parameters);
            })
    ];
}

protected function getTemplates(): Collection
{
    return collect(config('filament-template.templates'))->mapWithKeys(function ($template) {
        $templateName = explode('\\', $template);
        return [$template => end($templateName)];
    });
}

protected function actionForm(): array
{
    return [
        Select::make('template')
            ->label('Template')
            ->options($this->getTemplates())
            ->required(),
    ];
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.