/** * Saves a form */ public function actionSaveForm() { $this->requirePostRequest(); $form = new Applications_FormModel(); // Shared attributes $form->id = craft()->request->getPost('formId'); $form->name = craft()->request->getPost('name'); $form->handle = craft()->request->getPost('handle'); // Set the field layout $fieldLayout = craft()->fields->assembleLayoutFromPost(); $fieldLayout->type = ElementType::Asset; $form->setFieldLayout($fieldLayout); // Save it if (craft()->applications_forms->saveForm($form)) { craft()->userSession->setNotice(Craft::t('Form saved.')); $this->redirectToPostedUrl($form); } else { craft()->userSession->setError(Craft::t('Couldn’t save the form.')); } // Send the form back to the template craft()->urlManager->setRouteVariables(array('form' => $form)); }
/** * 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; } }