### Install TipTap Highlight Extension Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Install the TipTap highlight extension using npm. This is a prerequisite for using the highlight functionality. ```bash npm install @tiptap/extension-highlight --save-dev ``` -------------------------------- ### Install esbuild for Compilation Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Install esbuild as a development dependency to compile your JavaScript extensions. ```bash npm install esbuild --save-dev ``` -------------------------------- ### Install TipTap Packages for esbuild Plugin Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Installs the necessary TipTap core and ProseMirror packages as development dependencies for use with the esbuild plugin. ```bash npm install --save-dev @tiptap/core @tiptap/pm ``` -------------------------------- ### Inject Multiple Utilities Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Combine multiple utility parameters like `Get` and `Set` dynamically using reflection. Order does not matter. ```php use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Components\Utilities\Set; use Livewire\Component as Livewire; function (Livewire $livewire, Get $get, Set $set) { // ... } ``` -------------------------------- ### Create TipTap JavaScript Extension Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Define a custom TipTap JavaScript extension by importing and configuring it. This example configures the highlight extension with multicolor support. ```javascript import Highlight from '@tiptap/extension-highlight' export default Highlight.configure({ multicolor: true, }) ``` -------------------------------- ### Align Content to Start After Field Label Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md To align content to the start of the container when using `afterLabel()`, wrap the content in `Schema::start()`. ```php use Filament\Forms\Components\TextInput; use Filament\Schemas\Components\Icon; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; TextInput::make('name') ->afterLabel(Schema::start([ Icon::make(Heroicon::Star), 'This is the content after the field\'s label' ])) ``` -------------------------------- ### Create a Text Input Source: https://github.com/filamentphp/forms/blob/5.x/docs/02-text-input.md Basic creation of a text input field. This is the starting point for configuring text inputs. ```php use Filament\Forms\Components\TextInput; TextInput::make('name') ``` -------------------------------- ### Define Builder with Multiple Blocks Source: https://github.com/filamentphp/forms/blob/5.x/docs/13-builder.md This example demonstrates how to define a Builder component with three distinct blocks: 'heading', 'paragraph', and 'image'. Each block has its own schema defined. ```php use Filament\Forms\Components\Builder; use Filament\Forms\Components\Builder\Block; use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; Builder::make('content') ->blocks([ Block::make('heading') ->schema([ TextInput::make('content') ->label('Heading') ->required(), Select::make('level') ->options([ 'h1' => 'Heading 1', 'h2' => 'Heading 2', 'h3' => 'Heading 3', 'h4' => 'Heading 4', 'h5' => 'Heading 5', 'h6' => 'Heading 6', ]) ->required(), ]) ->columns(2), Block::make('paragraph') ->schema([ Textarea::make('content') ->label('Paragraph') ->required(), ]), Block::make('image') ->schema([ FileUpload::make('url') ->label('Image') ->image() ->required(), TextInput::make('alt') ->label('Alt text') ->required(), ]), ]) ``` -------------------------------- ### Create a Custom Rich Content Plugin Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Implement the `RichContentPlugin` interface to define custom TipTap extensions, JavaScript files, and editor tools for the rich editor. This example shows how to add a 'highlight' feature. ```php use Filament\Actions\Action; use Filament\Forms\Components\ColorPicker; use Filament\Forms\Components\RichEditor; use Filament\Forms\Components\RichEditor\EditorCommand; use Filament\Forms\Components\RichEditor\Plugins\Contracts\RichContentPlugin; use Filament\Forms\Components\RichEditor\RichEditorTool; use Filament\Support\Enums\Width; use Filament\Support\Facades\FilamentAsset; use Filament\Support\Icons\Heroicon; use Tiptap\Core\Extension; use Tiptap\Marks\Highlight; class HighlightRichContentPlugin implements RichContentPlugin { public static function make(): static { return app(static::class); } /** * @return array */ public function getTipTapPhpExtensions(): array { // This method should return an array of PHP TipTap extension objects. // See: https://github.com/ueberdosis/tiptap-php return [ app(Highlight::class, [ 'options' => ['multicolor' => true], ]), ]; } /** * @return array */ public function getTipTapJsExtensions(): array { // This method should return an array of URLs to JavaScript files containing // TipTap extensions that should be asynchronously loaded into the editor // when the plugin is used. return [ FilamentAsset::getScriptSrc('rich-content-plugins/highlight'), ]; } /** * @return array */ public function getEditorTools(): array { // This method should return an array of `RichEditorTool` objects, which can then be // used in the `toolbarButtons()` of the editor. // The `jsHandler()` method allows you to access the TipTap editor instance // through `$getEditor()`, and `chain()` any TipTap commands to it. // See: https://tiptap.dev/docs/editor/api/commands // The `action()` method allows you to run an action (registered in the `getEditorActions()` // method) when the toolbar button is clicked. This allows you to open a modal to // collect additional information from the user before running a command. return [ RichEditorTool::make('highlight') ->jsHandler('$getEditor()?.chain().focus().toggleHighlight().run()') ->icon(Heroicon::CursorArrowRays), RichEditorTool::make('highlightWithCustomColor') ->action(arguments: '{ color: $getEditor().getAttributes(\'highlight\')?.[\'data-color\'] }') ->icon(Heroicon::CursorArrowRipple), ]; } /** * @return array */ public function getEditorActions(): array { // This method should return an array of `Action` objects, which can be used by the tools // registered in the `getEditorTools()` method. The name of the action should match // the name of the tool that uses it. // The `runCommands()` method allows you to run TipTap commands on the editor instance. // It accepts an array of `EditorCommand` objects that define the command to run, // as well as any arguments to pass to the command. You should also pass in the // `editorSelection` argument, which is the current selection in the editor // to apply the commands to. return [ Action::make('highlightWithCustomColor') ->modalWidth(Width::Large) ->fillForm(fn (array $arguments): array => [ 'color' => $arguments['color'] ?? null, ]) ->schema([ ColorPicker::make('color'), ]) ->action(function (array $arguments, array $data, RichEditor $component): void { $component->runCommands( [ EditorCommand::make( 'toggleHighlight', arguments: [[ 'color' => $data['color'], ]], ), ], editorSelection: $arguments['editorSelection'], ); }), ]; } } ``` -------------------------------- ### Field Validation: Starts With Source: https://github.com/filamentphp/forms/blob/5.x/docs/23-validation.md Ensures the field value begins with one of the specified strings. Requires an array of possible starting strings. ```php Field::make('name')->startsWith(['a']) ``` -------------------------------- ### Global Checkbox Configuration Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Configure form fields globally using `configureUsing()` in a service provider or middleware. This example makes all checkboxes `inline(false)` by default. ```php use Filament\Forms\Components\Checkbox; Checkbox::configureUsing(function (Checkbox $checkbox): void { $checkbox->inline(false); }); ``` -------------------------------- ### Create Non-linear Slider Track Source: https://github.com/filamentphp/forms/blob/5.x/docs/19-slider.md Use `nonLinearPoints()` to define custom percentage points for a non-linear track. This example also includes pips for visual demonstration. ```php use Filament\Forms\Components\Slider; Slider::make('slider') ->range(minValue: 0, maxValue: 100) ->nonLinearPoints(['20%' => 50, '50%' => 75]) ->pips() ``` -------------------------------- ### Simple Repeater Data Structure Example Source: https://github.com/filamentphp/forms/blob/5.x/docs/12-repeater.md Illustrates the flat array data structure used by simple repeaters, where values are stored directly instead of nested arrays. ```php [ 'invitations' => [ 'dan@filamentphp.com', 'ryan@filamentphp.com', ], ] ``` -------------------------------- ### Return TipTap Extension Path Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md In your Filament plugin, implement `getTipTapJsExtensions()` to return the path to your registered JavaScript extension. Use `FilamentAsset::getScriptSrc()` to get the correct URL. ```php use Filament\Support\Facades\FilamentAsset; /** * @return array */ public function getTipTapJsExtensions(): array { return [ FilamentAsset::getScriptSrc('rich-content-plugins/highlight'), ]; } ``` -------------------------------- ### Access Parent Field Value in Repeater Source: https://github.com/filamentphp/forms/blob/5.x/docs/12-repeater.md Use `../` syntax with `$get()` to access parent field values from within a repeater's schema. For example, `$get('../../client_id')` accesses a field two levels up. ```php use Filament\Forms\Components\TextInput; TextInput::make('service_id') ->default(fn (array $state): ?string => $state['service_id'] ?? \Filament\Support\Facades\Filament::getRecord()->client_id ?? null) ``` -------------------------------- ### Configure esbuild Compilation Script Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Set up an esbuild script to bundle and minify your TipTap JavaScript extension. Ensure the entry points and output paths are correctly configured. ```javascript import * as esbuild from 'esbuild' async function compile(options) { const context = await esbuild.context(options) await context.rebuild() await context.dispose() } compile({ define: { 'process.env.NODE_ENV': `'production'`, }, bundle: true, mainFields: ['module', 'main'], platform: 'neutral', sourcemap: false, sourcesContent: false, treeShaking: true, target: ['es2020'], minify: true, entryPoints: ['./resources/js/filament/rich-content-plugins/highlight.js'], outfile: './resources/js/dist/filament/rich-content-plugins/highlight.js', }) ``` -------------------------------- ### Configure Storage Disk, Directory, and Visibility Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Customize where uploaded files are stored and their visibility. Use `disk()` for the storage disk, `directory()` for the path, and `visibility()` for access control (e.g., 'public' or 'private'). ```php use Filament\Forms\Components\FileUpload; FileUpload::make('attachment') ->disk('s3') ->directory('form-attachments') ->visibility('public') ``` -------------------------------- ### Configure Time Input Intervals Source: https://github.com/filamentphp/forms/blob/5.x/docs/08-date-time-picker.md Customize the step intervals for hours, minutes, and seconds using `hoursStep()`, `minutesStep()`, and `secondsStep()`. This allows for finer control over time selection. ```php use Filament\Forms\Components\DateTimePicker; DateTimePicker::make('published_at') ->native(false) ->hoursStep(2) ->minutesStep(15) ->secondsStep(10) ``` -------------------------------- ### Add Doesn't Start With Validation Rule Source: https://github.com/filamentphp/forms/blob/5.x/docs/23-validation.md Use the `doesntStartWith()` method to prevent the field value from starting with specified strings. Check Laravel documentation for more. ```php Field::make('name')->doesntStartWith(['admin']) ``` -------------------------------- ### Set Default Focused Date for DatePicker Source: https://github.com/filamentphp/forms/blob/5.x/docs/08-date-time-picker.md Configure the `defaultFocusedDate()` method to specify which date the calendar panel should open to when the field has no state. This is useful for setting a specific starting point, like the start of the current month. ```php use Filament\Forms\Components\DatePicker; DatePicker::make('custom_starts_at') ->native(false) ->placeholder(now()->startOfMonth()) ->defaultFocusedDate(now()->startOfMonth()) ``` -------------------------------- ### Pips on Steps with Custom Density Source: https://github.com/filamentphp/forms/blob/5.x/docs/19-slider.md Combine displaying pips on steps with a custom density for non-step pips. ```php use Filament\Forms\Components\Slider; use Filament\Forms\Components\Slider\Enums\PipsMode; Slider::make('slider') ->range(minValue: 0, maxValue: 100) ->step(10) ->pips(PipsMode::Steps, density: 5) ``` -------------------------------- ### Enable Prose Styling for Custom Block Previews Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Implement the `shouldApplyProseStylingToPreview()` static method in your custom block class to enable prose styling for its preview. This method should return `true` to apply typography styles. ```php use Filament\Forms\Components\RichEditor\RichContentCustomBlock; class HeadingBlock extends RichContentCustomBlock { // ... /** * @param array $config */ public static function shouldApplyProseStylingToPreview(array $config): bool { return true; } } ``` -------------------------------- ### Retrieve State of Another Field using $get Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Retrieve the state (value) of another field from within a callback using the `$get` parameter. This enables cross-field validation or dynamic configuration based on other field values. ```php use Filament\Schemas\Components\Utilities\Get; function (Get $get) { $email = $get('email'); // Store the value of the `email` field in the `$email` variable. //... } ``` -------------------------------- ### Initialize Code Editor Source: https://github.com/filamentphp/forms/blob/5.x/docs/20-code-editor.md Basic initialization of the code editor component. No syntax highlighting is applied by default. ```php use Filament\Forms\Components\CodeEditor; CodeEditor::make('code') ``` -------------------------------- ### Customize Slider Tooltip Formatting Source: https://github.com/filamentphp/forms/blob/5.x/docs/19-slider.md Use JavaScript with `RawJs` to format the tooltip display, for example, to show two decimal places. ```php use Filament\Forms\Components\Slider; use Filament\Support\RawJs; Slider::make('slider') ->range(minValue: 0, maxValue: 100) ->tooltips(RawJs::make(<<<'JS' `$${$value.toFixed(2)}` JS)) ``` -------------------------------- ### Custom Search Prompt for CheckboxList Source: https://github.com/filamentphp/forms/blob/5.x/docs/06-checkbox-list.md Customize the placeholder text for the search input in a searchable CheckboxList with the `searchPrompt()` method. This guides users on what to search for. ```php use Filament\Forms\Components\CheckboxList; CheckboxList::make('technologies') ->options([ // ... ]) ->searchable() ->searchPrompt('Search for a technology') ``` -------------------------------- ### Use Icons as Affixes for Text Input Source: https://github.com/filamentphp/forms/blob/5.x/docs/02-text-input.md Employ `prefixIcon()` and `suffixIcon()` methods to display icons before or after the input. Ensure the icon class is correctly imported. ```php use Filament\Forms\Components\TextInput; use Filament\Support\Icons\Heroicon; TextInput::make('domain') ->url() ->suffixIcon(Heroicon::GlobeAlt) ``` -------------------------------- ### Configure Minimum and Maximum Files for Upload Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Use `minFiles()` and `maxFiles()` to set the allowed number of uploaded files. These methods accept static integers or functions for dynamic calculation. ```php use Filament\Forms\Components\FileUpload; FileUpload::make('attachments') ->multiple() ->minFiles(2) ->maxFiles(5) ``` -------------------------------- ### Access Another Component's State Source: https://github.com/filamentphp/forms/blob/5.x/docs/22-custom-fields.md Demonstrates how to access the state of another form component within a Blade view using the `$get()` function. ```blade {{ $get('email') }} ``` -------------------------------- ### Get Enabled Checkbox Options for Validation Source: https://github.com/filamentphp/forms/blob/5.x/docs/06-checkbox-list.md Retrieve only the options that are not disabled using `getEnabledOptions()`. This is useful for validation purposes, ensuring only valid selections are considered. ```php use Filament\Forms\Components\CheckboxList; CheckboxList::make('technologies') ->options([ 'tailwind' => 'Tailwind CSS', 'alpine' => 'Alpine.js', 'laravel' => 'Laravel', 'livewire' => 'Laravel Livewire', 'heroicons' => 'SVG icons', ]) ->disableOptionWhen(fn (string $value): bool => $value === 'heroicons') ->in(fn (CheckboxList $component): array => array_keys($component->getEnabledOptions())) ``` -------------------------------- ### Display Files in a Grid Layout Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Use the Filepond `grid` layout by setting the `panelLayout()` to 'grid'. This method accepts a static value or a function for dynamic calculation. ```php use Filament\Forms\Components\FileUpload; FileUpload::make('attachments') ->multiple() ->panelLayout('grid') ``` -------------------------------- ### Basic Color Picker Source: https://github.com/filamentphp/forms/blob/5.x/docs/17-color-picker.md Initialize a color picker field. Defaults to HEX format. ```php use Filament\Forms\Components\ColorPicker; ColorPicker::make('color') ``` -------------------------------- ### Basic Date, Time, and Date-Time Pickers Source: https://github.com/filamentphp/forms/blob/5.x/docs/08-date-time-picker.md Use `DateTimePicker`, `DatePicker`, and `TimePicker` for selecting date and/or time values. These components require importing the respective classes. ```php use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DateTimePicker; use Filament\Forms\Components\TimePicker; DateTimePicker::make('published_at') DatePicker::make('date_of_birth') TimePicker::make('alarm_at') ``` -------------------------------- ### Conditionally Enable Password Reveal Source: https://github.com/filamentphp/forms/blob/5.x/docs/02-text-input.md Control password revealability dynamically by passing a boolean condition to the `revealable()` method. This example uses a feature flag. ```php use Filament\Forms\Components\TextInput; TextInput::make('password') ->password() ->revealable(FeatureFlag::active()) ``` -------------------------------- ### Enable File Downloads Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Use the `downloadable()` method to add a download button for each uploaded file. This is useful for providing direct access to the files. ```php use Filament\Forms\Components\FileUpload; FileUpload::make('attachments') ->multiple() ->downloadable() ``` -------------------------------- ### Customize Field Dehydration with dehydrateStateUsing Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Use `dehydrateStateUsing()` to transform a field's state just before it is retrieved (e.g., when a form is submitted). This example capitalizes the 'name' field. ```php use Filament\Forms\Components\TextInput; TextInput::make('name') ->required() ->dehydrateStateUsing(fn (string $state): string => ucwords($state)) ``` -------------------------------- ### Basic Select Component Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Use this to create a basic select field with a static list of options. The options are provided as a key-value array. ```php use Filament\Forms\Components\Select; Select::make('status') ->options([ 'draft' => 'Draft', 'reviewing' => 'Reviewing', 'published' => 'Published', ]) ``` -------------------------------- ### Enable Opening Files in New Tab Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Add a button to open each file in a new tab using the `openable()` method. Optionally, pass a boolean to control this behavior. ```php use Filament\Forms\Components\FileUpload; FileUpload::make('attachments') ->multiple() ->openable() ``` ```php use Filament\Forms\Components\FileUpload; FileUpload::make('attachments') ->multiple() ->openable(FeatureFlag::active()) ``` -------------------------------- ### Customize Field Hydration with afterStateHydrated Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Use `afterStateHydrated()` to modify a field's state immediately after it's populated with data. This example capitalizes the 'name' field. ```php use Closure; use Filament\Forms\Components\TextInput; TextInput::make('name') ->required() ->afterStateHydrated(function (TextInput $component, string $state) { $component->state(ucwords($state)); }) ``` -------------------------------- ### Basic Textarea Usage Source: https://github.com/filamentphp/forms/blob/5.x/docs/15-textarea.md Initialize a simple textarea field for a multi-line string input. ```php use Filament\Forms\Components\Textarea; Textarea::make('description') ``` -------------------------------- ### Customizing New Option Creation Logic Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Customize the logic for creating new options using the `createOptionUsing()` method. This method should return the primary key of the newly created record, allowing for custom saving procedures, such as associating the new record with a specific user or team. ```php use Filament\Forms\Components\Select; Select::make('author_id') ->relationship(name: 'author', titleAttribute: 'name') ->createOptionForm([ // ... ]) ->createOptionUsing(function (array $data): int { return auth()->user()->team->members()->create($data)->getKey(); }), ``` -------------------------------- ### Basic Toggle Buttons Source: https://github.com/filamentphp/forms/blob/5.x/docs/18-toggle-buttons.md Create a basic toggle button group with predefined options. The `options()` method accepts a static array or a function to dynamically calculate options. ```php use Filament\Forms\Components\ToggleButtons; ToggleButtons::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published' ]) ``` -------------------------------- ### Set Image Editor Aspect Ratio Options Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Configure specific aspect ratios for image cropping. Accepts an array of strings representing ratios or null for free cropping. ```php use Filament\Forms\Components\FileUpload; FileUpload::make('image') ->image() ->imageEditor() ->imageEditorAspectRatioOptions([ '16:9', '4:3', '1:1', ]) ``` ```php use Filament\Forms\Components\FileUpload; FileUpload::make('image') ->image() ->imageEditor() ->imageEditorAspectRatioOptions([ null, '16:9', '4:3', '1:1', ]) ``` -------------------------------- ### Determine Text Content with JavaScript Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Use `JsContent` to dynamically calculate text content for methods like `label()` using JavaScript. Available utilities include `$state` and `$get`. ```php use Filament\Forms\Components\TextInput; use Filament\Schemas\JsContent; TextInput::make('greetingResponse') ->label(JsContent::make(<<<'JS' ($get('name') === 'John Doe') ? 'Hello, John!' : 'Hello, stranger!' JS )) ``` -------------------------------- ### Inject Utilities into Closure Validation Rule Source: https://github.com/filamentphp/forms/blob/5.x/docs/23-validation.md Inject utilities like `$get` into closure rules by wrapping the closure in another function that accepts the utility and uses `use` to pass it. ```php use Filament\Schemas\Components\Utilities\Get; use Closure; TextInput::make('slug')->rules([ fn (Get $get): Closure => function (string $attribute, $value, Closure $fail) use ($get) { if ($get('other_field') === 'foo' && $value !== 'bar') { $fail("The {$attribute} is invalid."); } }, ]) ``` -------------------------------- ### Configure Image Uploads Source: https://github.com/filamentphp/forms/blob/5.x/docs/11-markdown-editor.md Customize the storage disk and directory for images uploaded to the Markdown Editor using `fileAttachmentsDisk()` and `fileAttachmentsDirectory()`. ```php use Filament\Forms\Components\MarkdownEditor; MarkdownEditor::make('content') ->fileAttachmentsDisk('s3') ->fileAttachmentsDirectory('attachments') ``` -------------------------------- ### Customize Morph Select Toggle Buttons Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Customize the toggle buttons used for the type selector in a morph select component. This example groups the toggle buttons using `grouped()`. ```php use Filament\Forms\Components\MorphToSelect; use Filament\Forms\Components\ToggleButtons; MorphToSelect::make('commentable') ->typeSelectToggleButtons() ->types([ MorphToSelect\Type::make(Product::class) ->titleAttribute('name'), MorphToSelect\Type::make(Post::class) ->titleAttribute('title'), ]) ->modifyTypeSelectUsing(fn (ToggleButtons $toggleButtons): ToggleButtons => $toggleButtons->grouped()) ``` -------------------------------- ### Compile JavaScript Extension Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Execute the esbuild script to compile your JavaScript extension into the specified output directory. ```bash node bin/build.js ``` -------------------------------- ### Customize Morph Select Type Field Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Modify the 'type' select field for a morph select component using `modifyTypeSelectUsing()`. This example sets the select to use native rendering. ```php use Filament\Forms\Components\MorphToSelect; use Filament\Forms\Components\Select; MorphToSelect::make('commentable') ->types([ MorphToSelect\Type::make(Product::class) ->titleAttribute('name'), MorphToSelect\Type::make(Post::class) ->titleAttribute('title'), ]) ->modifyTypeSelectUsing(fn (Select $select): Select => $select->native()) ``` -------------------------------- ### Add Actions as Affixes to Text Input Source: https://github.com/filamentphp/forms/blob/5.x/docs/02-text-input.md Integrate interactive actions before or after the input using `prefixAction()` and `suffixAction()`. Define the action's icon and behavior. ```php use Filament\Actions\Action; use Filament\Forms\Components\TextInput; use Filament\Support\Icons\Heroicon; TextInput::make('cost') ->prefix('€') ->suffixAction( Action::make('copyCostToPrice') ->icon(Heroicon::Clipboard), ) ``` -------------------------------- ### Customize All Morph Select Key Fields Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Customize the 'key' select field for all morph types by applying `modifyKeySelectUsing()` to the `MorphToSelect` component itself. This example uses native select rendering. ```php use Filament\Forms\Components\MorphToSelect; use Filament\Forms\Components\Select; MorphToSelect::make('commentable') ->types([ MorphToSelect\Type::make(Product::class) ->titleAttribute('name'), MorphToSelect\Type::make(Post::class) ->titleAttribute('title'), ]) ->modifyKeySelectUsing(fn (Select $select): Select => $select->native()) ``` -------------------------------- ### Configure First Day of the Week Source: https://github.com/filamentphp/forms/blob/5.x/docs/08-date-time-picker.md Set the first day of the week using `firstDayOfWeek()`, accepting values from 0 to 7. Alternatively, use semantic helpers like `weekStartsOnMonday()` or `weekStartsOnSunday()`. ```php use Filament\Forms\Components\DateTimePicker; DateTimePicker::make('published_at') ->native(false) ->firstDayOfWeek(7) ``` ```php use Filament\Forms\Components\DateTimePicker; DateTimePicker::make('published_at') ->native(false) ->weekStartsOnMonday() ``` ```php use Filament\Forms\Components\DateTimePicker; DateTimePicker::make('published_at') ->native(false) ->weekStartsOnSunday() ``` -------------------------------- ### Allow Multiple Image Aspect Ratios Source: https://github.com/filamentphp/forms/blob/5.x/docs/09-file-upload.md Configure the `imageAspectRatio()` method to accept an array of aspect ratios, allowing uploads that match any of the specified ratios. ```php use Filament\Forms\Components\FileUpload; FileUpload::make('banner') ->image() ->imageAspectRatio(['16:9', '4:3', '1:1']) ``` -------------------------------- ### Customizing Relationship Query for Checkbox List Options Source: https://github.com/filamentphp/forms/blob/5.x/docs/06-checkbox-list.md Use `modifyOptionsQueryUsing` within the `relationship()` method to customize the database query for fetching options, for example, to include soft-deleted records. ```php use Filament\Forms\Components\CheckboxList; use Illuminate\Database\Eloquent\Builder; CheckboxList::make('technologies') ->relationship( titleAttribute: 'name', modifyQueryUsing: fn (Builder $query) => $query->withTrashed(), ) ``` -------------------------------- ### Set Minimum and Maximum Items for Builder Source: https://github.com/filamentphp/forms/blob/5.x/docs/13-builder.md Use `minItems()` and `maxItems()` to define the allowed number of items in a builder. These methods can also accept a function for dynamic calculation. ```php use Filament\Forms\Components\Builder; Builder::make('content') ->blocks([ // ... ]) ->minItems(1) ->maxItems(5) ``` -------------------------------- ### Override Plugin Toolbar Button Settings Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Users can override the toolbar button configurations set by plugins. This example shows how to disable the 'highlightWithCustomColor' button, even if the plugin intended to enable it. ```php RichEditor::make('content') ->plugins([ HighlightRichContentPlugin::make(), ]) ->disableToolbarButtons(['highlightWithCustomColor']) ``` -------------------------------- ### Set Separate Range Padding for Slider Source: https://github.com/filamentphp/forms/blob/5.x/docs/19-slider.md Control padding on each side of the slider track separately by passing an array of two values to `rangePadding()`. The first value applies to the start, and the second to the end. ```php use Filament\Forms\Components\Slider; Slider::make('slider') ->range(minValue: 0, maxValue: 100) ->rangePadding([10, 20]) ``` -------------------------------- ### Conditionally Show Field with `visible()` Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md The `visible()` method provides an inverse logic to `hidden()`. Use it with a callback to show a field only when a condition is met, based on other fields' values accessed via `$get()`. ```php use Filament\Schemas\Components\Utilities\Get; use Filament\Forms\Components\Checkbox; use Filament\Forms\Components\TextInput; Checkbox::make('is_company') ->live() TextInput::make('company_name') ->visible(fn (Get $get): bool => $get('is_company')) ``` -------------------------------- ### Checkbox List with Option Descriptions Source: https://github.com/filamentphp/forms/blob/5.x/docs/06-checkbox-list.md Enhance options with descriptions using the `descriptions()` method. Ensure keys in the descriptions array match the option keys. Supports plain text, HtmlString, or markdown. ```php use Filament\Forms\Components\CheckboxList; use Illuminate\Support\HtmlString; CheckboxList::make('technologies') ->options([ 'tailwind' => 'Tailwind CSS', 'alpine' => 'Alpine.js', 'laravel' => 'Laravel', 'livewire' => 'Laravel Livewire', ]) ->descriptions([ 'tailwind' => 'A utility-first CSS framework for rapidly building modern websites without ever leaving your HTML.', 'alpine' => new HtmlString('A rugged, minimal tool for composing behavior directly in your markup.'), 'laravel' => str('A **web application** framework with expressive, elegant syntax.')->inlineMarkdown()->toHtmlString(), 'livewire' => 'A full-stack framework for Laravel building dynamic interfaces simple, without leaving the comfort of Laravel.', ]) ``` -------------------------------- ### Preload Relationship Options on Page Load Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Use the `preload()` method to populate searchable options from the database when the page loads, rather than waiting for user interaction. This can improve perceived performance for searchable selects. ```php use Filament\Forms\Components\Select; Select::make('author_id') ->relationship(name: 'author', titleAttribute: 'name') ->searchable() ->preload() ``` -------------------------------- ### Manipulate Repeater State Source: https://github.com/filamentphp/forms/blob/5.x/docs/12-repeater.md Get the raw state of a repeater using `$component->getState()` and set it using `$component->state($state)`. This allows for programmatic addition, removal, or modification of repeater items. ```php use Illuminate\Support\Str; // Get the raw data for the entire repeater $state = $component->getState(); // Add an item, with a random UUID as the key $state[Str::uuid()] = [ 'email' => auth()->user()->email, ]; // Set the new data for the repeater $component->state($state); ``` -------------------------------- ### Get Enabled Toggle Button Options for Validation Source: https://github.com/filamentphp/forms/blob/5.x/docs/18-toggle-buttons.md Retrieve a list of options that are not disabled using `getEnabledOptions()`. This is useful for validation purposes, such as ensuring a selected value is within the available enabled options. ```php use Filament\Forms\Components\ToggleButtons; ToggleButtons::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published', ]) ->disableOptionWhen(fn (string $value): bool => $value === 'published') ->in(fn (ToggleButtons $component): array => array_keys($component->getEnabledOptions())) ``` -------------------------------- ### Basic Radio Input Source: https://github.com/filamentphp/forms/blob/5.x/docs/07-radio.md Create a basic radio button group with static options. The `options()` method accepts an array where keys are values and values are labels. ```php use Filament\Forms\Components\Radio; Radio::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published' ]) ``` -------------------------------- ### Render Rich Content with Plugins Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Render rich content from a record using custom plugins. ```php RichContentRenderer::make($record->content) ->plugins([ HighlightRichContentPlugin::make(), ]) ``` -------------------------------- ### Access Block Data in Preview View Source: https://github.com/filamentphp/forms/blob/5.x/docs/13-builder.md In the preview Blade view, block data is accessible via a variable with the same name as the block. This example shows how to access the 'text' field from the 'heading' block. ```blade

{{ $text ?? 'Default heading' }}

``` -------------------------------- ### Set Min/Max Date for Date Picker Source: https://github.com/filamentphp/forms/blob/5.x/docs/08-date-time-picker.md Restrict the selectable date range using `minDate()` and `maxDate()`. These methods accept a `DateTime` instance or a string. This example uses the JavaScript date picker. ```php use Filament\Forms\Components\DatePicker; DatePicker::make('date_of_birth') ->native(false) ->minDate(now()->subYears(150)) ->maxDate(now()) ``` -------------------------------- ### Conditionally Make Field Required with `required()` Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Make a field conditionally required by passing a callback to the `required()` method. This is useful when a field should only be mandatory if another field has a value, checked using `$get()` and `filled()`. ```php use Filament\Schemas\Components\Utilities\Get; use Filament\Forms\Components\TextInput; TextInput::make('company_name') ->live(onBlur: true) TextInput::make('vat_number') ->required(fn (Get $get): bool => filled($get('company_name'))) ``` -------------------------------- ### Enable Live Schema Re-rendering Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Use the `live()` method on a field to enable schema re-rendering after user interaction. This is useful for dynamic form updates. ```php use Filament\Forms\Components\Select; Select::make('status') ->options([ 'draft' => 'Draft', 'reviewing' => 'Reviewing', 'published' => 'Published', ]) ->live() ``` -------------------------------- ### Shortcut for Hydration Formatting with formatStateUsing Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md The `formatStateUsing()` method provides a concise way to format a field's state during hydration, similar to `afterStateHydrated()` but often simpler for direct transformations. ```php use Closure; use Filament\Forms\Components\TextInput; TextInput::make('name') ->formatStateUsing(fn (string $state): string => ucwords($state)) ``` -------------------------------- ### Type-Safe Retrieval of Another Field's State Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Use type-safe methods on the `Get` utility to retrieve the state of another field with a specific expected type. You can also specify if the return type should be nullable. ```php use Filament\Schemas\Components\Utilities\Get; $get->string('email'); $get->integer('age'); $get->float('price'); $get->boolean('is_admin'); $get->array('tags'); $get->date('published_at'); $get->enum('status', StatusEnum::class); $get->filled('email'); // Returns the result of the `filled()` helper for the field. $get->blank('email'); // Returns the result of the `blank()` helper for the field. $get->string('email', isNullable: true); ``` -------------------------------- ### Instantiate Custom Field with Configuration Source: https://github.com/filamentphp/forms/blob/5.x/docs/22-custom-fields.md Pass configuration values to a custom field instance using its public configuration methods when creating the field. ```php use App\Filament\Forms\Components\LocationPicker; LocationPicker::make('location') ->zoom(0.5) ``` -------------------------------- ### Dynamic Select Options from Eloquent Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Load select field options dynamically from an Eloquent model based on the value of another field. This example uses `pluck` to retrieve names and IDs for categories and subcategories. ```php use Filament\Schemas\Components\Utilities\Get; use Filament\Forms\Components\Select; use Illuminate\Support\Collection; Select::make('category') ->options(Category::query()->pluck('name', 'id')) ->live() Select::make('sub_category') ->options(fn (Get $get): Collection => SubCategory::query() ->where('category', $get('category')) ->pluck('name', 'id')) ``` -------------------------------- ### Live Re-rendering on Blur Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Configure `live(onBlur: true)` to re-render the schema only when a field loses focus, optimizing performance for text-based inputs. ```php use Filament\Forms\Components\TextInput; TextInput::make('username') ->live(onBlur: true) ``` -------------------------------- ### Dynamically Allow HTML in Select Options Source: https://github.com/filamentphp/forms/blob/5.x/docs/03-select.md Conditionally allow HTML in select option labels by passing a boolean value or a callable to the `allowHtml()` method. This example uses a feature flag to determine if HTML should be allowed. ```php use Filament\Forms\Components\Select; Select::make('technology') ->options([ 'tailwind' => 'Tailwind', 'alpine' => 'Alpine', 'laravel' => 'Laravel', 'livewire' => 'Livewire', ]) ->searchable() ->allowHtml(FeatureFlag::active()) ``` -------------------------------- ### Expose TipTap/ProseMirror Modules Globally Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Assigns bundled TipTap and ProseMirror modules to `window.FilamentRichEditor.tiptap` for global access. This is done when the rich editor bundle loads. ```javascript window.FilamentRichEditor.tiptap = { core, pmState, pmView, pmModel, } ``` -------------------------------- ### Render Rich Content HTML from Model Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Use the `renderRichContent()` method on the model to easily render the rich content HTML, passing the attribute name. Alternatively, use `getRichContentAttribute()` to get an `Htmlable` object for unescaped rendering. ```blade {!! $record->renderRichContent('content') !!} ``` ```blade {{ $record->getRichContentAttribute('content') }} ``` -------------------------------- ### Reference Shared TipTap Modules in Extension Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Imports core TipTap and ProseMirror modules directly from the globally exposed `window.FilamentRichEditor.tiptap` object. Ensure the rich editor has loaded before using this. ```javascript const { Node, mergeAttributes } = window.FilamentRichEditor.tiptap.core const { Plugin, PluginKey } = window.FilamentRichEditor.tiptap.pmState export default Node.create({ name: 'myExtension', // ... }) ``` -------------------------------- ### Render Custom Block Preview HTML Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Implement `toPreviewHtml()` to generate an HTML preview of the custom block within the editor. Access block configuration via the `$config` array. ```php use Filament\Forms\Components\RichEditor\RichContentCustomBlock; class HeroBlock extends RichContentCustomBlock { // ... /** * @param array $config */ public static function toPreviewHtml(array $config): string { return view('filament.forms.components.rich-editor.rich-content-custom-blocks.hero.preview', [ 'heading' => $config['heading'], 'subheading' => $config['subheading'] ?? 'Default subheading', ])->render(); } } ``` -------------------------------- ### Hide a Field Based on Another Field's Value (JavaScript) Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Hide a field dynamically using JavaScript with the `hiddenJs()` method. This is more performant for client-side interactions as it avoids network requests. The `$get()` utility is available in the JavaScript context. ```php use Filament\Forms\Components\Select; use Filament\Forms\Components\Toggle; Select::make('role') ->options([ 'user' => 'User', 'staff' => 'Staff', ]) Toggle::make('is_admin') ->hiddenJs(<<<'JS' $get('role') !== 'staff' JS) ``` -------------------------------- ### Conditionally Hide Field with `hidden()` Source: https://github.com/filamentphp/forms/blob/5.x/docs/01-overview.md Use the `hidden()` method with a callback to hide a field based on another field's value. The `$get()` utility allows accessing other field states. Ensure the field controlling visibility is `live()` for immediate updates. ```php use Filament\Schemas\Components\Utilities\Get; use Filament\Forms\Components\Checkbox; use Filament\Forms\Components\TextInput; Checkbox::make('is_company') ->live() TextInput::make('company_name') ->hidden(fn (Get $get): bool => ! $get('is_company')) ``` -------------------------------- ### Add Pips to Set Values with Custom Density Source: https://github.com/filamentphp/forms/blob/5.x/docs/19-slider.md Configure pips at specific values while also adjusting their spacing using the `density` option. The range must be set using `range()`. ```php use Filament\Forms\Components\Slider; use Filament\Forms\Components\Slider\Enums\PipsMode; Slider::make('slider') ->range(minValue: 0, maxValue: 100) ->pips(PipsMode::Values, density: 5) ->pipsValues([5, 15, 25, 35, 45, 55, 65, 75, 85, 95]) ``` -------------------------------- ### Globally Configure Text Inputs to Trim Whitespace Source: https://github.com/filamentphp/forms/blob/5.x/docs/02-text-input.md Enable whitespace trimming for all text input components globally by configuring them in a service provider using `configureUsing()`. ```php use Filament\Forms\Components\TextInput; TextInput::configureUsing(function (TextInput $component): void { $component->trim(); }); ``` -------------------------------- ### Radio Input with Option Descriptions Source: https://github.com/filamentphp/forms/blob/5.x/docs/07-radio.md Add descriptive text to each radio option using the `descriptions()` method. Ensure keys in the descriptions array match the option keys. ```php use Filament\Forms\Components\Radio; Radio::make('status') ->options([ 'draft' => 'Draft', 'scheduled' => 'Scheduled', 'published' => 'Published' ]) ->descriptions([ 'draft' => 'Is not visible.', 'scheduled' => 'Will be visible.', 'published' => 'Is visible.' ]) ``` -------------------------------- ### Register Multiple Mention Providers Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Configure multiple mention providers with different trigger characters to allow users to reference various types of records. ```php use Filament\Forms\Components\RichEditor; use Filament\Forms\Components\RichEditor\MentionProvider; RichEditor::make('content') ->mentions([ MentionProvider::make('@') ->items([ 1 => 'Jane Doe', 2 => 'John Smith', ]), MentionProvider::make('#') ->items([ 'bug' => 'Bug', 'feature' => 'Feature', ]), ]) ``` -------------------------------- ### Configure All Rich Editors to Prevent Path Tampering Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Apply `preventFileAttachmentPathTampering()` to all Rich Editor instances globally by calling `configureUsing()` in a service provider's `boot()` method. Individual fields can opt out using `preventFileAttachmentPathTampering(false)`. ```php use Filament\Forms\Components\RichEditor; RichEditor::configureUsing(function (RichEditor $component): void { $component->preventFileAttachmentPathTampering(); }); ``` -------------------------------- ### Create Boolean Toggle Buttons Source: https://github.com/filamentphp/forms/blob/5.x/docs/18-toggle-buttons.md Use the `boolean()` method for simple 'Yes'/'No' toggle buttons. Colors and icons are set automatically but can be customized. ```php use Filament\Forms\Components\ToggleButtons; ToggleButtons::make('feedback') ->label('Like this post?') ->boolean() ``` -------------------------------- ### Publish Filament Assets Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Run the `filament:assets` Artisan command to publish your registered JavaScript files to the `/public` directory, making them accessible for serving. ```bash php artisan filament:assets ``` -------------------------------- ### esbuild Plugin to Resolve TipTap Imports Source: https://github.com/filamentphp/forms/blob/5.x/docs/10-rich-editor.md Configures esbuild to intercept imports of specific TipTap/ProseMirror modules and resolve them from the global `window.FilamentRichEditor.tiptap` instance at runtime. Keep local TipTap versions roughly in sync with Filament's bundled version. ```javascript // bin/build.js import * as esbuild from 'esbuild' const tiptapSharedPlugin = { name: 'tiptap-shared', setup(build) { const keys = { '@tiptap/core': 'core', '@tiptap/pm/state': 'pmState', '@tiptap/pm/view': 'pmView', '@tiptap/pm/model': 'pmModel', } build.onResolve({ filter: /^@tiptap\\(core|pm\/(state|view|model))$/ }, (args) => ({ path: args.path, namespace: 'tiptap-shared', })) build.onLoad({ filter: /.*/, namespace: 'tiptap-shared' }, async (args) => { const realModule = await import(args.path) const namedExports = Object.keys(realModule).filter( (key) => key !== '__esModule' && key !== 'default', ) const key = keys[args.path] let code = `const __module = window.FilamentRichEditor.tiptap.${key};\n` if (namedExports.length) { code += `export const { ${namedExports.join(', ')} } = __module;\n` } code += `export default __module?.default ?? __module;\n` return { contents: code, loader: 'js' } }) }, } esbuild.build({ // ... plugins: [tiptapSharedPlugin], entryPoints: ['./resources/js/filament/rich-content-plugins/my-extension.js'], outfile: './resources/js/dist/filament/rich-content-plugins/my-extension.js', }) ``` -------------------------------- ### Basic Builder Block Definition Source: https://github.com/filamentphp/forms/blob/5.x/docs/13-builder.md Illustrates the fundamental structure for defining a single block within a Builder component, specifying its name and schema. ```php use Filament\Forms\Components\Builder; use Filament\Forms\Components\Builder\Block; use Filament\Forms\Components\TextInput; Builder::make('content') ->blocks([ Block::make('heading') ->schema([ TextInput::make('content')->required(), // ... ]), // ... ]) ```