In this guide, we will explore how we can add custom blocks on filament rich editor.
Use RichEditor
First, we will use the filament rich editor on our filament form schemas.
RichEditor::make('content')
->label(__('resource.post.fields.content'))
->required()
->placeholder('Write your content here...')
You can read more about filament rich editor and its implementation here.
Create Custom block
Now to create a custom block on filament rich editor, first copy the below command on your terminal.
php artisan make:filament-rich-content-custom-block YOURBLOCKNAME // eg LatestPost
The above block will generate 3 files:
- YourBlockName.php – a php class that extends the RichContentCustomBlock
- a preview blade file – content of this part is rendered inside the rich editor
- an index blade file – this is the final content which is rendered outside in blade file or any infolist or other components.
Register custom blocks on filament rich editor
After we create a custom block, we need to add this on our RichEditor Schema.
RichEditor::make('content')
->label(__('resource.post.fields.content'))
->required()
->placeholder('Write your content here...')
->customBlocks([
LatestPost::class
]),
Exploring custom block class
Now lets explore the custom block class, we have 4 methods:
- getId() : methods to define a unique id of custom block class.
- getLabel() : method to define the label of the custom block class.
- configureEditorAction() : a modal to collect additional information when the block is inserted.
- toPreviewHtml() : a string that is returned inside the rich editor.
- toHtml() : This return the final HTML that should be rendered for that block.
Read filament tips and tricks
How you can access form input?
You can easily access the data that are defined in your configureEditorAction(), the input are stored in your $config variable. So you can easily pass that to your toPreviewHtml() and toHtml().
public static function toPreviewHtml(array $config): string
{
return view('filament.forms.components.rich-editor.rich-content-custom-blocks.latest-post.preview', [
'posts' => Post::post()->published()->take(5)->get(),
'heading' => $config['heading'] ?? null
])->render();
}
public static function toHtml(array $config, array $data): string
{
return view('filament.forms.components.rich-editor.rich-content-custom-blocks.latest-post.index', [
'posts' => Post::post()->published()->take(5)->get(),
'heading' => $config['heading'] ?? null
])->render();
}
How to render content?
Finally, to render the content of rich editor, if you are using filament text input or text entry, filament will auto render the content. But if you want to show it on blade file you can use:
{{ \Filament\Forms\Components\RichEditor\RichContentRenderer::make($record->content) }}

