From bc120ea74a363f8c8647a94901044b22f1e71f83 Mon Sep 17 00:00:00 2001 From: Majstor <76176291+wmdhosting@users.noreply.github.com> Date: Fri, 12 May 2023 14:15:36 +0300 Subject: [PATCH] Add logic to select section by part of handle --- src/fields/SectionField.php | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/fields/SectionField.php b/src/fields/SectionField.php index 4e8eee7..95cea4c 100644 --- a/src/fields/SectionField.php +++ b/src/fields/SectionField.php @@ -32,6 +32,11 @@ class SectionField extends Field implements PreviewableFieldInterface */ public array $excludedSections = []; + /** + * @var string Part of handle for selected section by this part + */ + public string $partOfHandle = ''; + /** * @inheritdoc */ @@ -89,6 +94,25 @@ private function getSections() return $sections; } + + /** + * Return all sections handles. + * + * @return array + */ + private function getSectionsHandles() + { + $sections = []; + $editableSections = Craft::$app->getSections()->getEditableSections(); + + if (!empty($editableSections)) { + foreach ($editableSections as $section) { + $sections[$section->id] = $section->handle; + } + } + + return $sections; + } /** * @inheritdoc @@ -178,6 +202,7 @@ public function getSettingsHtml(): ?string 'field' => $this, 'sections' => $this->getSections(), 'selectAll' => $this->selectAll, + 'partOfHandle' => $this->partOfHandle, ] ); } @@ -187,7 +212,9 @@ public function getSettingsHtml(): ?string */ public function getInputHtml($value, ElementInterface $element = null): string { - if (empty($this->allowedSections) && empty($this->selectAll)) return 'You have not selected any section for selection, select in the field settings.'; + if (empty($this->allowedSections) && empty($this->selectAll) && empty($this->partOfHandle)) { + return 'You have not selected any section for selection, select in the field settings.'; + } $sections = $this->getSections(); $allowSectionsConfig = $this->allowedSections; @@ -199,6 +226,14 @@ public function getInputHtml($value, ElementInterface $element = null): string } } $allowSectionsConfig = array_keys($sections); + } else if(!empty($this->partOfHandle)) { + foreach ($this->getSectionsHandles() as $id => $handle) { + if (stripos($handle, $this->partOfHandle) !== false + && !in_array($id, $allowSectionsConfig) + && !in_array($id, $this->excludedSections)) { + $allowSectionsConfig[] = $id; + } + } } $allowSections = array_flip($allowSectionsConfig);