Is there a way to display the first 25 chars of a Laravel\Nova\Fields\Textarea on the index of a Resource?
Laravel Nova - How to display partial textarea text on index
Asked Answered
Just to expand on the answers above, here's the function I'm using that only uses the ellipsis when it cuts something off:
Text::make('Description')->rules('max:255')->displayUsing(function ($text) {
if (strlen($text) > 30) {
return substr($text, 0, 30) . '...';
}
return $text;
})
I would suggest using return Str::limit($text, 30); instead of the if. –
Burgener
The comment from @Burgener about using the Laravel
Str
helper is correct, it saves using that entire if block. –
Kulturkampf It could be even shorter with arrow functions:
Text::make('Description', 'name')->displayUsing(fn($id) => Str::limit($id, 20))->onlyOnIndex()
–
Hypogeum We had the same problem and we solved it like this
Text::make('Text *', 'text')
->rules('required')
->hideFromIndex(),
Text::make('Text','text')
->displayUsing(function($id) {
$part = strip_tags(substr($id, 0, 25));
return $part . " ...";
})->onlyOnIndex(),
hope this helps.
Yes, it is possible.
Starting from Nova v2, you can add ->showOnIndex(true)
to the Textarea
field, and then use the ->displayUsing()
to extract a part of your text.
Textarea::make('Description')
->showOnIndex(true)
->displayUsing(function($description) {
return strip_tags(substr($description, 0, 50));
})
I have created a nova package called ellipsis-textarea for fun, which you can use.
Install - composer require saumini/ellipsis-textarea
Usage -
use Saumini\EllipsisTextarea\EllipsisTextarea;
public function fields(Request $request)
{
return [
EllipsisTextarea::make('Copy')
->displayLength(25),
];
}
Here are two different ways I ended up accomplishing this without adding additional composer requirements using Macolson and ndee's answers:
use Illuminate\Support\Str;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\BelongsTo;
public function fields(Request $request)
{
return [
ID::make(__('ID'), 'id')->sortable(),
Text::make('Label')
->sortable()
->rules('required', 'max:255')
->displayUsing(function($text) {
return Str::limit($text, 30);}),
BelongsTo::make('Survey Field', 'field', \App\Nova\SurveyField::class)
// ->hideFromIndex()
->rules('required')
->displayUsing(function($object) {
$text = $object->title;
return Str::limit($text, 30);}),
];
}
© 2022 - 2024 — McMap. All rights reserved.