From 47b992fd599c153601768dcca30fa5fc637eac7c Mon Sep 17 00:00:00 2001 From: Jeremy Layson Date: Mon, 8 Apr 2024 21:30:05 +0800 Subject: [PATCH] Tested new slug mechanism --- src/FilaCms.php | 1 - .../Pages/CreateAbstractContentResource.php | 27 ++++++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/FilaCms.php b/src/FilaCms.php index 16d5b0c3..0c3cc870 100644 --- a/src/FilaCms.php +++ b/src/FilaCms.php @@ -46,7 +46,6 @@ public function systemUser() public function getModelFromResource($resource) { - dd([$resource, self::$contentModels]); return array_search($resource, self::$contentModels); } diff --git a/src/Filament/Resources/AbstractContentResource/Pages/CreateAbstractContentResource.php b/src/Filament/Resources/AbstractContentResource/Pages/CreateAbstractContentResource.php index 4c902df7..b49923b6 100644 --- a/src/Filament/Resources/AbstractContentResource/Pages/CreateAbstractContentResource.php +++ b/src/Filament/Resources/AbstractContentResource/Pages/CreateAbstractContentResource.php @@ -13,10 +13,11 @@ class CreateAbstractContentResource extends CreateRecord protected function mutateFormDataBeforeCreate(array $data): array { - $class = parent::static; + $class = get_class($this); $parent = new $class(); + $resource = $parent::getResource(); + $model = FilaCms::getModelFromResource($resource); - FilaCms::getModelFromResource($parent->resource); if (is_null($data['slug'])) { // auto-generate then check $data['slug'] = Str::slug($data['title']); @@ -24,11 +25,31 @@ protected function mutateFormDataBeforeCreate(array $data): array $data['slug'] = Str::slug($data['slug']); } + if ($this->checkIfSlugExists($data['slug'], $model)) { + $increment = 1; + + while (true) { + $slug = $data['slug'] . '-' . $increment; + if ($this->checkIfSlugExists($slug, $model) === FALSE) { + $data['slug'] = $slug; + break; + } + $increment++; + } + } + return $data; } - protected function checkIfSlugExists($slug) + protected function checkIfSlugExists($slug, $modelName) { + $model = new $modelName; + $data = $model->where('slug', $slug)->first(); + + if (is_null($data)) { + return FALSE; + } + return TRUE; } }