|
16 | 16 | use Filament\Tables\Columns\TextColumn; |
17 | 17 | use Filament\Tables\Table; |
18 | 18 | use Illuminate\Database\Eloquent\Model; |
| 19 | +use Illuminate\Support\Facades\Schema as DatabaseSchema; |
19 | 20 | use Moox\Address\Support\AddressRelationConfig; |
20 | 21 | use Override; |
21 | 22 |
|
@@ -45,7 +46,12 @@ public function form(Schema $schema): Schema |
45 | 46 | ->label(__('address::fields.owner')) |
46 | 47 | ->types( |
47 | 48 | collect($ownerTypes) |
48 | | - ->map(fn (string $label, string $class): Type => Type::make($class)->label($label)) |
| 49 | + ->map(fn (string $label, string $class): Type => Type::make($class) |
| 50 | + ->label($label) |
| 51 | + ->titleAttribute($this->resolveTitleAttributeForMorphType($class)) |
| 52 | + ->getOptionLabelFromRecordUsing( |
| 53 | + fn (Model $record): string => $this->resolveOptionLabel($record) |
| 54 | + )) |
49 | 55 | ->values() |
50 | 56 | ->all() |
51 | 57 | ) |
@@ -108,4 +114,42 @@ public function table(Table $table): Table |
108 | 114 | DeleteAction::make(), |
109 | 115 | ]); |
110 | 116 | } |
| 117 | + |
| 118 | + private function resolveTitleAttributeForMorphType(string $class): string |
| 119 | + { |
| 120 | + $configured = AddressRelationConfig::titleAttributeForOwnerType($class); |
| 121 | + |
| 122 | + if ($configured !== null) { |
| 123 | + return $configured; |
| 124 | + } |
| 125 | + |
| 126 | + $model = app($class); |
| 127 | + $table = $model->getTable(); |
| 128 | + $schema = DatabaseSchema::connection($model->getConnectionName()); |
| 129 | + |
| 130 | + foreach (['display_name', 'name', 'title'] as $column) { |
| 131 | + if ($schema->hasColumn($table, $column)) { |
| 132 | + return $column; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + return $model->getKeyName(); |
| 137 | + } |
| 138 | + |
| 139 | + private function resolveOptionLabel(Model $record): string |
| 140 | + { |
| 141 | + if (method_exists($record, 'displayLabel')) { |
| 142 | + return (string) $record->displayLabel(); |
| 143 | + } |
| 144 | + |
| 145 | + foreach (['display_name', 'name', 'title'] as $attribute) { |
| 146 | + $value = $record->getAttribute($attribute); |
| 147 | + |
| 148 | + if (is_string($value) && $value !== '') { |
| 149 | + return $value; |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + return (string) $record->getKey(); |
| 154 | + } |
111 | 155 | } |
0 commit comments