| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
-
- namespace App\Filament\Resources\ProjectResource\Pages;
-
- use App\Filament\Resources\ProjectResource;
- use App\Models\Project;
- use Filament\Actions;
- use Filament\Resources\Pages\EditRecord;
-
- class EditProject extends EditRecord
- {
- protected static string $resource = ProjectResource::class;
-
- protected function getRedirectUrl(): string
- {
- return $this->getResource()::getUrl('index');
- }
-
- protected function mutateFormDataBeforeFill(array $data): array
- {
- $project = $this->record;
-
- $data['badgesTarget'] = \DB::table('badgeables')
- ->where('badgeable_id', $project->id)
- ->where('badgeable_type', Project::class)
- ->where('award_type', 1)
- ->get()
- ->map(fn ($item) => [
- 'badge_id' => $item->badge_id,
- 'award_type' => $item->award_type,
- ])->toArray();
-
- $data['badgesAward'] = \DB::table('badgeables')
- ->where('badgeable_id', $project->id)
- ->where('badgeable_type', Project::class)
- ->where('award_type', 2)
- ->get()
- ->map(fn ($item) => [
- 'badge_id' => $item->badge_id,
- 'award_date' => $item->award_date,
- 'award_type' => $item->award_type,
- ])->toArray();
- return $data;
- }
-
- protected function mutateFormDataBeforeSave(array $data): array
- {
- // 暫存標籤資料
- if (isset($data['badgesTarget'])) {
- $this->badgesTargetData = $data['badgesTarget'];
- unset($data['badgesTarget']);
- }
- // 暫存標籤資料
- if (isset($data['badgesAward'])) {
- $this->badgesAwardData = $data['badgesAward'];
- unset($data['badgesAward']);
- }
- return $data;
- }
-
- protected function afterSave(): void
- {
- $syncData = [];
- // ✅ 先刪除所有舊的標籤
- \DB::table('badgeables')
- ->where('badgeable_id', $this->record->id)
- ->where('badgeable_type', Project::class)
- ->delete();
-
- if (!empty($this->badgesTargetData)) {
- foreach ($this->badgesTargetData as $item) {
- $syncData[$item['badge_id'] . '_1'] = [
- 'badge_id' => $item['badge_id'],
- 'award_type' => 1,
- 'award_date' => null,
- ];
- }
- }
-
- if (!empty($this->badgesAwardData)) {
- foreach ($this->badgesAwardData as $item) {
- $syncData[$item['badge_id'] . '_2'] = [
- 'badge_id' => $item['badge_id'],
- 'award_type' => 2,
- 'award_date' => $item['award_date'] . "-01",
- ];
- }
- }
-
- foreach ($syncData as $data) {
- \DB::table('badgeables')->insert([
- 'badge_id' => $data['badge_id'],
- 'badgeable_id' => $this->record->id,
- 'badgeable_type' => Project::class,
- 'award_type' => $data['award_type'],
- 'award_date' => $data['award_date'],
- 'created_at' => now(),
- 'updated_at' => now(),
- ]);
- }
- }
- }
|