Installation:
composer require creagia/filament-code-field
Ensure your project uses Filament 3 and Laravel 11+.
Publish Assets (if needed):
php artisan vendor:publish --provider="Creagia\FilamentCodeField\FilamentCodeFieldServiceProvider"
(Default assets are auto-loaded; publish only if customizing themes.)
First Usage: Add the field to a Filament form/resource:
use Creagia\FilamentCodeField\Fields\CodeField;
CodeField::make('code_content')
->language('javascript') // Defaults to 'text/x-markdown'
->rows(15)
Place this in a Form or TableColumn definition.
// In a Filament Resource Form
public static function form(Form $form): Form
{
return $form
->schema([
CodeField::make('markdown_content')
->label('Post Content')
->language('markdown')
->rows(20)
->columnSpanFull(),
]);
}
Result: A syntax-highlighted Markdown editor with live preview (if configured).
Dynamic Language Selection:
CodeField::make('config')
->language(function (string $context) {
return match ($context) {
'settings' => 'json',
'scripts' => 'javascript',
default => 'php',
};
})
->languageLabel('Language')
Useful for multi-purpose fields (e.g., config files with mixed syntax).
Read-Only Mode for Tables:
// In a TableColumn
CodeField::make('snippet')
->language('python')
->readOnly()
->extraAttributes(['class' => 'font-mono'])
Ideal for displaying code snippets in admin lists without edit access.
Integration with Filament Actions:
public static function getTableActions(): array
{
return [
Tables\Actions\EditAction::make()->form([
CodeField::make('custom_logic')
->language('php')
->rules(['required']),
]),
];
}
Custom Themes: Extend the default CodeMirror theme via published assets:
/* resources/css/filament-code-field.css */
.cm-s-creagia-dark .cm-line {
background: #1a1a1a;
}
Re-publish assets after changes.
Line Numbers & Gutter:
CodeField::make('sql_query')
->lineNumbers()
->gutter(true)
->height('300px')
Autocomplete Setup:
CodeField::make('api_endpoint')
->language('javascript')
->extraAttributes([
'data-autocomplete' => json_encode([
'hintOptions' => ['completeSingle' => false],
'sources' => [
{
'list': ['getUsers', 'fetchPosts', 'deleteItem'],
'match': '/\\b(get|fetch|delete)\\w*/',
},
],
]),
])
Requires codemirror-autocomplete (included by default).
Form Validation:
CodeField::make('validation_rules')
->language('yaml')
->rules([
'required',
function (string $attribute, $value, Closure $fail) {
if (str_contains($value, 'invalid_syntax')) {
$fail('Code contains invalid syntax.');
}
},
])
protected $casts = [
'code_content' => 'string',
];
<x-filament-code-field::code-field
wire:model="code"
language="typescript"
rows="10"
/>
Asset Loading Issues:
filament-code-field is after filament/support in resources/js/app.js:
import '@creagia/filament-code-field/dist/filament-code-field.js';
Uncaught ReferenceError: CodeMirror.Language Mismatch:
'text/x-custom' and manually configure:
->extraAttributes([
'data-language-config' => json_encode([
'name' => 'custom',
'mime' => 'text/x-custom',
]),
])
Performance with Large Files:
->debounce(300) to delay updates.Inspect the Field:
Add ->extraAttributes(['data-test-id' => 'debug-code-field']) to target the element in DevTools.
Log CodeMirror Events: Override the field’s JavaScript via a custom asset:
document.addEventListener('DOMContentLoaded', () => {
const editor = CodeMirror.fromTextArea(
document.querySelector('[data-test-id="debug-code-field"]'),
{ /* ... */ }
);
editor.on('change', (cm) => {
console.log('Changed:', cm.getValue());
});
});
Clear Cache: After publishing assets or updating the package:
php artisan view:clear
php artisan filament:cache:clear
Custom Modes: Extend CodeMirror modes by publishing the package’s assets and adding:
// resources/js/filament-code-field-extensions.js
CodeMirror.defineMode('custom-mode', function () { /* ... */ });
Register in filament-code-field.js:
window.FilamentCodeField = {
modes: {
'custom-mode': 'custom-mode',
},
};
Plugin Integration: Add CodeMirror plugins dynamically:
->extraAttributes([
'data-plugins' => json_encode([
'foldcode',
'comment',
]),
])
Server-Side Processing:
Use Filament’s afterStateUpdated to process code before saving:
CodeField::make('template')
->afterStateUpdated(function (string $state, Closure $set) {
$processed = preg_replace('/\s+/', ' ', $state);
$set('template', $processed);
})
->theme('dracula') for built-in dark themes (requires theme package).Collapsible:
Collapsible::make('Advanced Settings')
->schema([
CodeField::make('config')->language('json'),
])
->extraAttributes(['data-preserve-whitespace' => 'true']) for monospace-sensitive content (e.g., YAML).How can I help you explore Laravel packages today?