/** * Save a tag group. * * @return null */ public function actionSaveTagGroup() { $this->requirePostRequest(); craft()->userSession->requireAdmin(); $tagGroup = new TagGroupModel(); // Set the simple stuff $tagGroup->id = craft()->request->getPost('tagGroupId'); $tagGroup->name = craft()->request->getPost('name'); $tagGroup->handle = craft()->request->getPost('handle'); // Set the field layout $fieldLayout = craft()->fields->assembleLayoutFromPost(false); $fieldLayout->type = ElementType::Tag; $tagGroup->setFieldLayout($fieldLayout); // Save it if (craft()->tags->saveTagGroup($tagGroup)) { craft()->userSession->setNotice(Craft::t('Tag group saved.')); $this->redirectToPostedUrl($tagGroup); } else { craft()->userSession->setError(Craft::t('Couldn’t save the tag group.')); } // Send the tag group back to the template craft()->urlManager->setRouteVariables(array('tagGroup' => $tagGroup)); }
/** * Saves a tag group. * * @param TagGroupModel $tagGroup * * @throws \Exception * @return bool */ public function saveTagGroup(TagGroupModel $tagGroup) { if ($tagGroup->id) { $tagGroupRecord = TagGroupRecord::model()->findById($tagGroup->id); if (!$tagGroupRecord) { throw new Exception(Craft::t('No tag group exists with the ID “{id}”.', array('id' => $tagGroup->id))); } $oldTagGroup = TagGroupModel::populateModel($tagGroupRecord); $isNewTagGroup = false; } else { $tagGroupRecord = new TagGroupRecord(); $isNewTagGroup = true; } $tagGroupRecord->name = $tagGroup->name; $tagGroupRecord->handle = $tagGroup->handle; $tagGroupRecord->validate(); $tagGroup->addErrors($tagGroupRecord->getErrors()); if (!$tagGroup->hasErrors()) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if (!$isNewTagGroup && $oldTagGroup->fieldLayoutId) { // Drop the old field layout craft()->fields->deleteLayoutById($oldTagGroup->fieldLayoutId); } // Save the new one $fieldLayout = $tagGroup->getFieldLayout(); craft()->fields->saveLayout($fieldLayout); // Update the tag group record/model with the new layout ID $tagGroup->fieldLayoutId = $fieldLayout->id; $tagGroupRecord->fieldLayoutId = $fieldLayout->id; // Save it! $tagGroupRecord->save(false); // Now that we have a tag group ID, save it on the model if (!$tagGroup->id) { $tagGroup->id = $tagGroupRecord->id; } // Might as well update our cache of the tag group while we have it. $this->_tagGroupsById[$tagGroup->id] = $tagGroup; if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } return true; } else { return false; } }