CreateProject.php 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Filament\Resources\ProjectResource\Pages;
  3. use App\Filament\Resources\ProjectResource;
  4. use App\Models\Project;
  5. use Filament\Resources\Pages\CreateRecord;
  6. use Illuminate\Support\Facades\DB;
  7. class CreateProject extends CreateRecord
  8. {
  9. protected static string $resource = ProjectResource::class;
  10. protected array $badgesTargetData = [];
  11. protected array $badgesAwardData = [];
  12. protected function getRedirectUrl(): string
  13. {
  14. return $this->getResource()::getUrl('index');
  15. }
  16. protected function mutateFormDataBeforeCreate(array $data): array
  17. {
  18. // 暫存永續目標資料
  19. if (isset($data['badgesTarget']) && is_array($data['badgesTarget'])) {
  20. $this->badgesTargetData = $data['badgesTarget'];
  21. unset($data['badgesTarget']);
  22. }
  23. // 暫存取得標章資料
  24. if (isset($data['badgesAward']) && is_array($data['badgesAward'])) {
  25. $this->badgesAwardData = $data['badgesAward'];
  26. unset($data['badgesAward']);
  27. }
  28. return $data;
  29. }
  30. protected function afterCreate(): void
  31. {
  32. // 儲存永續目標
  33. if (! empty($this->badgesTargetData)) {
  34. foreach ($this->badgesTargetData as $index => $item) {
  35. if (isset($item['badge_id'])) {
  36. DB::table('badgeables')->insert([
  37. 'badge_id' => $item['badge_id'],
  38. 'badgeable_id' => $this->record->id,
  39. 'badgeable_type' => Project::class,
  40. 'award_type' => 1,
  41. 'award_date' => null,
  42. 'sort_order' => $index,
  43. 'created_at' => now(),
  44. 'updated_at' => now(),
  45. ]);
  46. }
  47. }
  48. }
  49. // 儲存取得標章
  50. if (! empty($this->badgesAwardData)) {
  51. foreach ($this->badgesAwardData as $index => $item) {
  52. if (isset($item['badge_id'])) {
  53. $awardDate = null;
  54. if (isset($item['award_date']) && ! empty($item['award_date'])) {
  55. // 處理日期格式:如果是 Y-m 格式,加上 -01
  56. $awardDate = $item['award_date'];
  57. if (strlen($awardDate) === 7) { // Y-m format
  58. $awardDate .= '-01';
  59. }
  60. }
  61. DB::table('badgeables')->insert([
  62. 'badge_id' => $item['badge_id'],
  63. 'badgeable_id' => $this->record->id,
  64. 'badgeable_type' => Project::class,
  65. 'award_type' => 2,
  66. 'award_date' => $awardDate,
  67. 'sort_order' => $index,
  68. 'created_at' => now(),
  69. 'updated_at' => now(),
  70. ]);
  71. }
  72. }
  73. }
  74. }
  75. }