Skip to content

Filament v4 Custom Field Plugins: Wrapping Third-Party JS Libraries Cleanly

Learn how to wrap any third-party JavaScript library into a reusable Filament v4 custom field plugin, with proper Alpine.js wiring, Livewire state sync, and asset registration.

Published · Updated · 3 min read

Filament v4 Custom Field Plugins: Wrapping Third-Party JS Libraries Cleanly

Why Custom Field Plugins Deserve a Proper Architecture

Dropping a <script> tag into a Blade view and calling it a Filament field is a trap. You end up with state that Livewire can't track, assets that load on every page, and a component that breaks the moment someone nests it inside a repeater. Filament v4's schema-based architecture gives you clean extension points — use them.

This article walks through wrapping a hypothetical FancyPicker JS library into a first-class Filament v4 field plugin.


Step 1: Scaffold the Field Class

Extend Filament\Forms\Components\Field and declare your configuration API:

namespace App\Forms\Components;

use Filament\Forms\Components\Field;

class FancyPickerField extends Field
{
    protected string $view = 'forms.components.fancy-picker';

    protected bool $allowMultiple = false;

    public function allowMultiple(bool $condition = true): static
    {
        $this->allowMultiple = $condition;
        return $this;
    }

    public function getAllowMultiple(): bool
    {
        return $this->allowMultiple;
    }
}

Keep configuration fluent and immutable-friendly. Avoid storing mutable JS state in PHP — that belongs in Alpine.


Step 2: The Blade View with Alpine.js Wiring

Filament v4 passes the component instance into the view. Use $getStatePath() and $getState() to bind correctly:

@php
    $statePath = $getStatePath();
    $state     = $getState();
    $multiple  = $getAllowMultiple();
@endphp

<x-dynamic-component
    :component="$getFieldWrapperView()"
    :field="$field"
>
    <div
        x-data="fancyPicker({
            state: $wire.entangle('{{ $statePath }}').live,
            multiple: {{ $multiple ? 'true' : 'false' }}
        })"
        x-init="init()"
    >
        <div x-ref="picker"></div>
    </div>
</x-dynamic-component>

$wire.entangle(...).live is the critical line — it creates a two-way binding between Alpine's reactive data and Livewire's component state without any manual event dispatching.


Step 3: The Alpine Component

Register your Alpine component in a dedicated JS file so it's tree-shakeable:

// resources/js/fancy-picker.js
import FancyPickerLib from 'fancy-picker-lib';

export default function fancyPicker({ state, multiple }) {
    return {
        state,
        multiple,
        picker: null,

        init() {
            this.picker = new FancyPickerLib(this.$refs.picker, {
                multiple: this.multiple,
                defaultValue: this.state,
                onChange: (value) => {
                    this.state = value; // entangle pushes this to Livewire
                },
            });

            this.$watch('state', (value) => {
                // Sync external changes (e.g., form reset) back into the lib
                if (this.picker.getValue() !== value) {
                    this.picker.setValue(value);
                }
            });
        },
    };
}

The $watch in the opposite direction handles programmatic state changes — form fill(), wizard navigation, or reset() calls.


Step 4: Asset Registration via a Service Provider

Never enqueue assets globally. Use Filament's asset system so they only load when the field is rendered:

use Filament\Support\Assets\Js;
use Filament\Support\Facades\FilamentAsset;

public function boot(): void
{
    FilamentAsset::register([
        Js::make('fancy-picker', __DIR__ . '/../../dist/fancy-picker.js')
            ->loadedOnRequest(),
    ], package: 'my-org/fancy-picker');
}

Then in your field class, declare the asset dependency:

public function getExtraAlpineAttributes(): array
{
    FilamentAsset::getScriptSrc('fancy-picker', package: 'my-org/fancy-picker');
    return [];
}

Actually, the idiomatic v4 approach is to call FilamentAsset::getScriptSrc() inside the view or override setUp() to register a $livewire->js() call — check your Filament version's asset API for the exact hook, as it evolved between v4 minor releases.


Step 5: Repeater Compatibility

Repeaters clone DOM nodes. Your Alpine component must reinitialise on clone. Add a unique key:

<div
    x-data="fancyPicker({ ... })"
    x-init="init()"
    wire:key="fancy-picker-{{ $statePath }}"
>

wire:key forces Livewire to treat each repeater row as a distinct DOM subtree, preventing stale Alpine instances.


Takeaways

  • Use $wire.entangle(...).live for bidirectional state sync; avoid manual $dispatch.
  • Register assets with loadedOnRequest() to keep panel payloads lean.
  • Always $watch the entangled state to handle programmatic form changes.
  • Set wire:key on the root element to survive repeater cloning.
  • Keep PHP configuration fluent; keep mutable UI state in Alpine only.

Frequently asked questions

Can I use `$wire.entangle` without `.live` for performance?

Yes — omitting `.live` defers the Livewire sync to the next network request (e.g., form submission). Use `.live` only when the server needs to react immediately to field changes, such as for dependent field visibility. For most pickers, deferring is fine and reduces round-trips.

How do I handle server-side validation errors in a custom field?

Filament's field wrapper component automatically reads `$errors->get($statePath)` and renders them below the field. As long as your Blade view uses `<x-dynamic-component :component="$getFieldWrapperView()" :field="$field">`, validation messages appear without any extra work on your part.

Should the JS asset be compiled into the Filament panel's Vite build or shipped separately?

Ship it separately via `FilamentAsset::register()` with `loadedOnRequest()`. Compiling into the panel build creates a tight coupling between your plugin and the consuming application's build pipeline, which breaks for teams using the pre-built Filament CSS/JS.

Mohamed Said

About the author

Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

About GitHub LinkedIn WhatsApp Email Address My CV

Have a technical challenge?

Tell me what you’re building. I reply within two working days.

Discuss your project