/** * Saves a form. * * @param Applications_FormModel $form * @throws \Exception * @return bool */ public function saveForm(Applications_FormModel $form) { if ($form->id) { $formRecord = Applications_FormRecord::model()->findById($form->id); if (!$formRecord) { throw new Exception(Craft::t('No form exists with the ID “{id}”', array('id' => $form->id))); } $oldForm = Applications_FormModel::populateModel($formRecord); $isNewForm = false; } else { $formRecord = new Applications_FormRecord(); $isNewForm = true; } $formRecord->name = $form->name; $formRecord->handle = $form->handle; $formRecord->validate(); $form->addErrors($formRecord->getErrors()); if (!$form->hasErrors()) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if (!$isNewForm && $oldForm->fieldLayoutId) { // Drop the old field layout craft()->fields->deleteLayoutById($oldForm->fieldLayoutId); } // Save the new one $fieldLayout = $form->getFieldLayout(); craft()->fields->saveLayout($fieldLayout); // Update the form record/model with the new layout ID $form->fieldLayoutId = $fieldLayout->id; $formRecord->fieldLayoutId = $fieldLayout->id; // Save it! $formRecord->save(false); // Now that we have a form ID, save it on the model if (!$form->id) { $form->id = $formRecord->id; } // Might as well update our cache of the form while we have it. $this->_formsById[$form->id] = $form; if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } return true; } else { return false; } }