Skip to content

Commit

Permalink
Merge pull request #11664 from SanderMuller/3.x
Browse files Browse the repository at this point in the history
Add getDefaultName for Columns
  • Loading branch information
danharrin authored Mar 4, 2024
2 parents 0f350f6 + c8726da commit 0322adc
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/tables/src/Columns/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,27 @@ final public function __construct(string $name)
$this->name($name);
}

public static function make(string $name): static
public static function make(?string $name = null): static
{
$static = app(static::class, ['name' => $name]);
$columnClass = static::class;

$name ??= static::getDefaultName();

if (blank($name)) {
throw new Exception("Column of class [$columnClass] must have a unique name, passed to the [make()] method.");
}

$static = app($columnClass, ['name' => $name]);
$static->configure();

return $static;
}

public static function getDefaultName(): ?string
{
return null;
}

public function getTable(): Table
{
return $this->table ?? $this->getGroup()?->getTable() ?? $this->getLayout()?->getTable() ?? throw new Exception("The column [{$this->getName()}] is not mounted to a table.");
Expand Down
7 changes: 7 additions & 0 deletions tests/src/Tables/ColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
->assertCanRenderTableColumn('author.name');
});

it('can render column with default name', function () {
Post::factory()->count(10)->create();

livewire(PostsTable::class)
->assertCanRenderTableColumn('created_at');
});

it('can sort records', function () {
$posts = Post::factory()->count(10)->create();

Expand Down
10 changes: 10 additions & 0 deletions tests/src/Tables/Fixtures/PostsTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Tests\Models\Post;
use Illuminate\Contracts\View\View;
Expand Down Expand Up @@ -87,6 +88,7 @@ public function table(Table $table): Table
->sortable()
->searchable()
->prefix(fn (Post $record): string => $record->is_published ? 'published' : 'unpublished'),
CreatedAtColumn::make(),
])
->filters([
Tables\Filters\Filter::make('is_published')
Expand Down Expand Up @@ -198,3 +200,11 @@ public function render(): View
return view('tables.fixtures.table');
}
}

class CreatedAtColumn extends TextColumn
{
public static function getDefaultName(): ?string
{
return 'created_at';
}
}

0 comments on commit 0322adc

Please sign in to comment.