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