rappasoft / laravel-livewire-tables

A dynamic table component for Laravel Livewire
https://rappasoft.com/docs/laravel-livewire-tables/v2/introduction
MIT License
1.78k stars 337 forks source link

[Bug]: Error secondaryHeader #1899

Open Lindomar-Paulo opened 2 months ago

Lindomar-Paulo commented 2 months ago

What happened?

when upgrading to version 3.4.15. Columns with secondaryHeader are experiencing a fatal error: Rappasoft\LaravelLivewireTables\Views\Column::getSecondaryHeaderContents(): Return value must be of type Illuminate\Contracts\Foundation\Application|Illuminate\View\Factory|Illuminate\View\View|Illuminate\Support\HtmlString|string, null returned. The same application running in version v3.4.9 works normally.

How to reproduce the bug

<?php

namespace App\Livewire;

ini_set('default_charset', 'UTF-8');

use Rappasoft\LaravelLivewireTables\DataTableComponent; use Rappasoft\LaravelLivewireTables\Views\Column; use App\Models\Relint\Relint; use App\Models\Relint\RelintStatus; use App\Models\Unidade; use Illuminate\Database\Eloquent\Builder; use Rappasoft\LaravelLivewireTables\Views\Columns\DateColumn; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\DB; use Rappasoft\LaravelLivewireTables\Views\Filters\DateFilter; use Rappasoft\LaravelLivewireTables\Views\Filters\MultiSelectFilter; use Rappasoft\LaravelLivewireTables\Views\Filters\TextFilter;

class TableRilint extends DataTableComponent { public $myParam = 'Default';

public string $tableName = 'relints';

public array $relints = [];
protected $model = Relint::class;

public function builder(): Builder
{

    if (auth()->user()->hasRole('delta')) {
        $relint = Relint::query()
            ->whereRaw(
            '((`user_id` = ? AND `relint`.`status` = ?)
             OR (`relint`.`unidade_id` = ? AND `relint`.`status` IN (?, ?, ?)))',
             [auth()->user()->id, 1, auth()->user()->unidade_id, 2, 3, 4]
            );
        // $relint->delta(auth()->user());

        return $relint->with('local', 'difusao');
    }
    $relint = Relint::query()->where('user_id', auth()->user()->id)->where('relint.unidade_id',auth()->user()->unidade_id);
    //   $relint->when($this->columnSearch['titulo'] ?? null, fn ($query, $name) => $query->where('rellint.titulo', 'like', '%' . $name . '%'))
    return $relint->with('local', 'difusao');
}

public function configure(): void
{
    App::setLocale('pt_BR');
 //  // $this->setDebugStatus(false)->setDebugEnabled();
    $this->setPaginationStatus(true);

    $this->setQueryStringStatus(false)->setDefaultSort('created_at', 'desc')

        ->setEmptyMessage('Nenhum resultado encontrado')->setPrimaryKey('id')

        ->setFooterStatus(true)->setConfigurableAreas([
            'toolbar-left-start' => ['components.includes.areas.toolbar-left-start', ['link' => 'cadastro',]],
        ])
        ->setSearchFieldAttributes([
            'default' => true,
            'class' => 'shadow-none'
        ])
        ->setTableAttributes([
            'default' => true,
            'id' => 'my-id-table-relint',
            'class' => 'table-striped table-hover table-sm',
        ])
        ->setTheadAttributes([
            'id' => 'my-id-table-relint-thead',
            'class' => 'table-dark',
        ])->setSecondaryHeaderTrAttributes(function ($rows) {
            return ['class' => 'bg-gray-100'];
        });
    $this->setPerPageAccepted([5, 10, 25, 50, 100])->setPaginationMethod('standard')
        ->setPerPage(5)
        ->setDefaultPerPage(5)
        ->getPerPageDisplayedItemIds();
        $this->setPerPageFieldAttributes([
            'class' => 'border-red-300 focus:border-indigo-300 focus:ring-indigo-200 dark:bg-red-700 dark:text-white dark:border-red-600', // Add these classes to the dropdown
            'default-colors' => false, // Do not output the default colors
            'default-styles' => true, // Output the default styling
        ]);
          $this->setRefreshTime(60000);

}

public function columns(): array
{
    return [

        Column::make("Id", "unidade_id")
            ->sortable()->hideIf(true),
        Column::make("#", "id")
            ->sortable(),
        Column::make('Documento','doc_name')->sortable()->searchable(),
        Column::make("Difusao")
            ->sortable()
            ->eagerLoadRelations()
            ->searchable(function (Builder $query, $term) {
                //    dump($row);
                return $query->whereHas('difusao', function ($query) use ($term) {
                    $query->where('unidades.descricao', 'like', '%' . trim($term) . '%');
                });
            })
            ->label(function ($row, $text = '') {
                try {
                    //  dump($row);
                    $row->text = "<ul>";
                    if ($row->difusao) {

                        foreach ($row->difusao as $difusao) {

                            if ($difusao->level == 3)
                                $row->text .= "<li>{$difusao->nodeUp->nodeUp->descricao}/{$difusao->nodeUp->descricao}/{$difusao->descricao};</li>";
                        }
                    }
                    $row->text .= "</ul>";
                    return $row->text;
                } catch (\Exception $e) {
                    $row->text = "Erro ao Carregar";
                    return $row->text;
                }
            })
            ->sortable()->eagerLoadRelations()->collapseOnTablet()->html(),

        Column::make("Titulo", "titulo")->sortable()
            ->searchable()->secondaryHeader($this->getFilterByKey('titulo')),
        Column::make("Autor", "user.name")->searchable()
            ->sortable()->collapseOnTablet(),
        Column::make("Unidade", "local.descricao")->searchable(function (Builder $query, $term) {

            return $query->orWhere('local.descricao', 'like', '%' . trim($term) . '%');
        })->sortable()->eagerLoadRelations()->format(function (
            $value,
            $column,
            $customer
        ) {
            return $column->local->descricao;
        }),

        Column::make("Conteudo", 'conteudo.content')
            ->searchable()->hideIf(false)->format(
                fn ($value, $row, Column $column) => str_limit_words_strip_tags($value, 30)
            )->collapseAlways(),
        DateColumn::make("Criado", "created_at")->outputFormat('d-m-Y H:i:s')
            ->sortable()->searchable()->collapseOnTablet(),
        Column::make("Status", 'situacao.descricao')
            ->sortable()->searchable()->collapseOnTablet(),
        Column::make('Action')
            ->label(
                fn ($row, Column $column) => view('components.action-column')->with([
                    'rdi' => $row,
                    'model' => "relint"
                ])
            )->html(),

    ];
}
public function filters(): array
{
    return [
        TextFilter::make('titulo')
            ->config([
                'maxlength' => 10,
                'placeholder' => 'Pesquisa por Titulo',
                'id' => 'titulo'
            ])
            ->filter(function (Builder $builder, string $value) {
                $builder->where('relint.titulo', 'like', '%' . $value . '%');
            })->hiddenFromMenus(),

        TextFilter::make('Difusao')
            ->config([
                'maxlength' => 10,
                'placeholder' => 'Pesquisa por Unidade',
            ])
            ->filter(function (Builder $builder, string $value) {
                $str = '';
                $unidade = Unidade::query()->with('nodeDown')->where('descricao', 'like', '%' . $value . '%')
                    ->orderBy('id')->get();

                if ($unidade) {
                    foreach ($unidade as $unidade) {

                        if ($unidade->level === 1) {
                            $node = $unidade->nodeDown;
                            if ($node) {
                                foreach ($node as $n) {
                                    $n1 = $n->nodeDown;
                                    if ($n1) {
                                        foreach ($n1 as $u1) {
                                            $str .= "`unidades`.`descricao` like  '{$u1->descricao}' and `unidades`.`id` = {$u1->id} or ";
                                        }
                                    }
                                }
                            }
                        }
                        if ($unidade->level === 2) {
                            $node = $unidade->nodeDown;
                            if ($node) {

                                foreach ($node as $n) {
                                    $str .= "`unidades`.`descricao` like  '{$n->descricao}' and `unidades`.`id` = {$n->id} or ";
                                }
                            }
                        }
                        if ($unidade->level === 3) {

                            $str .= "`unidades`.`descricao` like  '{$unidade->descricao}' and `unidades`.`id` = {$unidade->id} or";
                        }
                    }
                    $str = rtrim($str, 'or ');
                    //   $builder->whereRaw($str);

                    if (!empty($str)) {
                        $builder->where(function($builder) use($str){
                            $builder->whereHas('difusao', function ($query) use ($str) {
                                $query->whereRaw("($str)");
                            });
                        });

                    }
                }
            }),
        /*
        MultiSelectFilter::make('Tags')
            ->options(
                Tag::query()
                    ->orderBy('name')
                    ->get()
                    ->keyBy('id')
                    ->map(fn($tag) => $tag->name)
                    ->toArray()
            )->filter(function(Builder $builder, array $values) {
                $builder->whereHas('tags', fn($query) => $query->whereIn('tags.id', $values));
            })
            ->setFilterPillValues([
                '3' => 'Tag 1',
            ]),
        SelectFilter::make('E-mail Verified', 'email_verified_at')
            ->setFilterPillTitle('Verified')
            ->options([
                ''    => 'Any',
                'yes' => 'Yes',
                'no'  => 'No',
            ])
            ->filter(function(Builder $builder, string $value) {
                if ($value === 'yes') {
                    $builder->whereNotNull('email_verified_at');
                } elseif ($value === 'no') {
                    $builder->whereNull('email_verified_at');
                }
            }),
        SelectFilter::make('Active')
            ->setFilterPillTitle('User Status')
            ->setFilterPillValues([
                '1' => 'Active',
                '0' => 'Inactive',
            ])
            ->options([
                '' => 'All',
                '1' => 'Yes',
                '0' => 'No',
            ])
            ->filter(function(Builder $builder, string $value) {
                if ($value === '1') {
                    $builder->where('active', true);
                } elseif ($value === '0') {
                    $builder->where('active', false);
                }
            }), */
        MultiSelectFilter::make('Tags')
            ->options(
                RelintStatus::query()
                    ->orderBy('id')
                    ->get()
                    ->keyBy('id')
                    ->map(fn ($status) => $status->descricao)
                    ->toArray()
            )->filter(function (Builder $builder, array $values) {
                $builder->whereHas('situacao', fn ($query) => $query->whereIn('relint_status.id', $values));
            })
            ->setFilterPillValues([
                '1' => 'Criado',
            ]),
        DateFilter::make('Data Inicial')

            ->filter(function (Builder $builder, string $value) {
                $builder->whereDate('relint.created_at', '>=', $value);
            }),
        DateFilter::make('Data Final')
            ->filter(function (Builder $builder, string $value) {
                $builder->whereDate('relint.created_at', '<=', $value);
            }),
    ];
}

}

Package Version

3.4.15

PHP Version

8.1.x

Laravel Version

No response

Alpine Version

No response

Theme

Bootstrap 5.x

Notes

I don't know if it can affect it. The application where no error occurs is running with APACHE web server, and the one that is giving error is in DOCKER with NGNIX

Error Message

Rappasoft\LaravelLivewireTables\Views\Column::getSecondaryHeaderContents(): Return value must be of type Illuminate\Contracts\Foundation\Application|Illuminate\View\Factory|Illuminate\View\View|Illuminate\Support\HtmlString|string, null returned.

lrljoe commented 2 months ago

It looks like you have published the views in your project.

The recommendation is NOT to do so.

There have been several significant changes in recent versions, which I think are causing this issue.

When sharing code, please wrap it in three ` marks either side, so that it formats, otherwise there's zero chance of reading it!

stale[bot] commented 1 month ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.