Tricks

Count how many characters left to type in the field

Oct 31, 2022
studiowizjo
Admin panel, Form builder

Want to see how many characters left to type in field?

Apply filter by clicking on value in column

Here are some copy & paste examples:

  1. Simple, based on field max length:
Textarea::make('content')
->hint(fn ($state, $component) => 'left: ' . $component->getMaxLength() - strlen($state) . ' characters')
->maxlength(10)
->lazy() //or: reactive() for instant update, but less efficient
  1. With ranges, as on screen above:
Textarea::make('sms_content')
->hint(function ($state) {
$singleSmsCharactersCount = 160;
$charactersCount = strlen($state);
$smsCount = 0;
 
if ($charactersCount > 0) {
$smsCount = ceil(strlen($state) / $singleSmsCharactersCount);
}
 
$leftCharacters = $singleSmsCharactersCount - ($charactersCount % $singleSmsCharactersCount);
 
return $smsCount . ' sms (left: ' . $leftCharacters . ' characters)';
})
->lazy()
avatar

I personally suggest change ->lazy() to ->live() to have the changes appear in real-time

Textarea::make('content') ->hint(fn ($state, $component) => 'left: ' . $component->getMaxLength() - strlen($state) . ' characters') ->maxlength(10) ->live()