pxlrbt / filament-excel

Excel Export for Filament Admin Resources
MIT License
323 stars 68 forks source link

[Question] What's the best way to format a boolean to 'Yes' or 'No' #173

Closed ceesvanegmond closed 6 months ago

ceesvanegmond commented 6 months ago

Having a bunch of fields which are boolean fields. Using this package; what is the best (or easiest) way to convert those 0 and 1's to 'No' and 'Yes' in the export? Should be that difficult? Should I use a custom formatter?


class Municipality extends Model
{
    protected $casts = [
        'is_awesome' => 'boolean',
        'is_big' => 'boolean',
    ];

Right now when using this:

///
         ->headerActions([
                ExportAction::make()->exports([ExcelExport::make('form')->fromForm()]),
            ])
///

The excel gets filled it 0 and 1 instead of Yes/No

ceesvanegmond commented 6 months ago

I already got an solution :-)

<?php

namespace App\Helpers;

use Illuminate\Database\Eloquent\Model;
use pxlrbt\FilamentExcel\Actions\Tables\ExportAction;
use pxlrbt\FilamentExcel\Columns\Column;
use pxlrbt\FilamentExcel\Exports\ExcelExport;

class ExportHelper
{
    public static function exportBooleansToStrings(Model $model): ExportAction
    {
        return ExportAction::make()->exports([ExcelExport::make('form')
            ->withColumns(function () use ($model) {
                return collect($model->getCasts())
                    ->filter(fn ($type) => $type === 'boolean')
                    ->map(fn ($item, $key) => Column::make($key)->formatStateUsing(fn ($state) => $state ? 'Yes' : 'No'));
            })
            ->fromForm()]);
    }
}