Skip to content

How to Add a Prefix to a Form Input Field in Filament #15249

Answered by leandrocfe
Parsa-Biazar asked this question in Help
Discussion options

You must be logged in to vote

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;
}

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by Parsa-Biazar
Comment options

You must be logged in to vote
1 reply
@leandrocfe
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants