9

Is there a way to display the first 25 chars of a Laravel\Nova\Fields\Textarea on the index of a Resource?

5 Answers5

13

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;
})
Citizen
  • 12,430
  • 26
  • 76
  • 117
12

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.

Macolson
  • 121
  • 2
2

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

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),
    ];
}
Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70
0

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);}),
        ];
    }
Ryan M
  • 139
  • 3
  • 10