How to Add a Prefix to a Form Input Field in Filament #15249
-
PackageForm builder Package Versionv3.2.131 How can we help you?Hello Filament community, I’m encountering an issue when trying to dynamically add a prefix (e.g., a leading zero) to a TextInput field in a Filament form for display purposes while ensuring the value is stored without the prefix in the database. My setup is as follows: The database stores the value without the prefix (e.g., 91124563255).
i know that i have to use However, this solution does not work as expected. The field doesn’t properly format the value when the form is opened, and sometimes the changes are not reflected upon saving. I’ve referred to the documentation and GitHub discussions but couldn’t find a working solution for this specific case. Can someone provide guidance or suggest an alternative approach to achieve this functionality? Any help would be greatly appreciated. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
use a custom cast User.php protected function casts(): array
{
return [
'mobile' => PhoneNumber::class,
];
} PhoneNumber.php /**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
return str($value)->prepend('0')->toString();
}
/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
$newValue = str($value)
->when(str($value)->startsWith('0'), fn ($str) => $str->after('0'))
->toString();
return $newValue;
} |
Beta Was this translation helpful? Give feedback.
-
Thank you very much for your response! The issue is resolved now, and I really appreciate the help. However, I still don’t fully understand two things, and I would be grateful if you could clarify:
These are two of the most significant points of confusion for me in Filament. I would love to understand them better and improve my expertise in using Filament effectively. Thank you again for your support! |
Beta Was this translation helpful? Give feedback.
use a custom cast
User.php
PhoneNumber.php