How to reuse a Form Field?

In using a DRY principle, I want to use Phone input that can be use in all forms. Currently, I've been copy-pasting them accross pages.
TextInput::make('phone')
->disableLabel()
->label('Phone Number')
->placeholder('Phone Number')
->validationAttribute('Phone Number')
->minLength(10)
->maxLength(14)
->mask('(999) 999-9999')
->stripCharacters(['(', ')', ' ', '-'])
->numeric()
->rules([ new PhoneNumberRule, 'doesnt_start_with:1'])
->required()
->validationMessages([
'doesnt_start_with' => 'Phone Number cannot begin with 1.',
]),
TextInput::make('phone')
->disableLabel()
->label('Phone Number')
->placeholder('Phone Number')
->validationAttribute('Phone Number')
->minLength(10)
->maxLength(14)
->mask('(999) 999-9999')
->stripCharacters(['(', ')', ' ', '-'])
->numeric()
->rules([ new PhoneNumberRule, 'doesnt_start_with:1'])
->required()
->validationMessages([
'doesnt_start_with' => 'Phone Number cannot begin with 1.',
]),
So instead of this, is there a way I can use PhoneInput::make('primary_phone') ?
2 Replies
vahnmarty
vahnmarty3mo ago
Well this one works:
<?php

namespace App\Forms\Components;

use App\Rules\PhoneNumberRule;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\TextInput;

class PhoneInput
{
public static function make($variable)
{
return TextInput::make($variable)
->minLength(10)
->maxLength(14)
->mask('(999) 999-9999')
->stripCharacters(['(', ')', ' ', '-'])
->numeric()
->rules([ new PhoneNumberRule, 'doesnt_start_with:1'])
->validationMessages([
'doesnt_start_with' => 'Phone Number cannot begin with 1.',
]);
}
}
<?php

namespace App\Forms\Components;

use App\Rules\PhoneNumberRule;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\TextInput;

class PhoneInput
{
public static function make($variable)
{
return TextInput::make($variable)
->minLength(10)
->maxLength(14)
->mask('(999) 999-9999')
->stripCharacters(['(', ')', ' ', '-'])
->numeric()
->rules([ new PhoneNumberRule, 'doesnt_start_with:1'])
->validationMessages([
'doesnt_start_with' => 'Phone Number cannot begin with 1.',
]);
}
}
Just wondering if this is the correct way?
trovster
trovster3mo ago
I've done this by extending the field you want (eg TextInput) and then use $this->minLength()->maxLength() etc inside that.
Want results from more Discord servers?
Add your server