From ca344c838d5a6a22b38cfab9918ef823d1cd0827 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 11 Nov 2022 14:04:56 -0500 Subject: [PATCH] Update $templates->delete($template) method to also delete fieldgroup (when not used elsewhere) --- wire/core/Templates.php | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/wire/core/Templates.php b/wire/core/Templates.php index 0511a255..c2052cd9 100644 --- a/wire/core/Templates.php +++ b/wire/core/Templates.php @@ -341,17 +341,35 @@ class Templates extends WireSaveableItems { */ public function ___delete(Saveable $item) { + $name = $item->name; + $id = $item->id; + if($item->flags & Template::flagSystem) { - throw new WireException("Can't delete template '{$item->name}' because it is a system template."); + throw new WireException("Can't delete template '$name' because it is a system template."); } $cnt = $item->getNumPages(); if($cnt > 0) { - throw new WireException("Can't delete template '{$item->name}' because it is used by $cnt pages."); + throw new WireException("Can't delete template '$name' because it is used by $cnt pages."); } $return = parent::___delete($item); + + if($return) { + $fieldgroups = $this->wire()->fieldgroups; + $fieldgroup = $fieldgroups->get($name); + if($fieldgroup) { + // also delete fieldgroup, if not used by any other templates + $cnt = 0; + foreach($this as $t) { + /** @var Template $t */ + if($t->id != $id && $t->fieldgroup->id == $fieldgroup->id) $cnt++; + } + if(!$cnt) $fieldgroups->delete($fieldgroup); + } + } + $cache = $this->wire()->cache; $cache->maintenance($item);