/** * @return bool */ public function safeUp() { if ($table = $this->dbConnection->schema->getTable('{{sproutemail_campaigns_notifications}}')) { if ($table->getColumn('options') != null) { $notifications = craft()->db->createCommand()->select('id, eventId, options')->from('sproutemail_campaigns_notifications')->where('eventId=:eventId', array(':eventId' => 'sproutForms-saveEntry'))->queryAll(); if ($count = count($notifications)) { SproutFormsPlugin::log('Notifications found: ' . $count, LogLevel::Info, true); $newOptions = array(); foreach ($notifications as $notification) { SproutFormsPlugin::log('Migrating Sprout Forms saveEntry notification', LogLevel::Info, true); $newOptions = $this->_updateSaveFormEntryOptions($notification['options']); craft()->db->createCommand()->update('sproutemail_campaigns_notifications', array('options' => $newOptions), 'id= :id', array(':id' => $notification['id'])); SproutFormsPlugin::log('Migration of notification complete', LogLevel::Info, true); } } SproutFormsPlugin::log('No notifications found to migrate.', LogLevel::Info, true); } else { SproutFormsPlugin::log('Could not find the `options` column.', LogLevel::Info, true); } } else { SproutFormsPlugin::log('Could not find the `sproutemail_campaigns_notifications` table.', LogLevel::Info, true); } return true; }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { $oldTable = 'sproutforms_forms_old'; $newTable = 'sproutforms_forms'; // Rename the old Form table if (craft()->db->tableExists($newTable)) { craft()->db->createCommand()->renameTable($newTable, $oldTable); SproutFormsPlugin::log("`{$newTable}` table renamed `{$oldTable}`.", LogLevel::Info, true); // ------------------------------------------------------------ // Create new Form Table SproutFormsPlugin::log("Creating the new `{$newTable}` table.", LogLevel::Info, true); // Create the craft_sproutforms_forms table craft()->db->createCommand()->createTable($newTable, array('id' => array('column' => 'integer', 'required' => true, 'primaryKey' => true), 'fieldLayoutId' => array('column' => 'integer', 'required' => false), 'groupId' => array('maxLength' => 11, 'decimals' => 0, 'unsigned' => false, 'length' => 10, 'column' => 'integer'), 'name' => array('required' => true), 'handle' => array('required' => true), 'titleFormat' => array('required' => true, 'default' => "{dateCreated|date('D, d M Y H:i:s')}"), 'displaySectionTitles' => array(), 'redirectUri' => array(), 'submitAction' => array(), 'submitButtonText' => array(), 'notificationRecipients' => array(), 'notificationSubject' => array(), 'notificationSenderName' => array(), 'notificationSenderEmail' => array(), 'notificationReplyToEmail' => array()), null, false); // Add foreign keys to craft_sproutforms_forms craft()->db->createCommand()->addForeignKey($newTable, 'id', 'elements', 'id', 'CASCADE', null); craft()->db->createCommand()->addForeignKey($newTable, 'fieldLayoutId', 'fieldlayouts', 'id', 'SET NULL', null); SproutFormsPlugin::log("New `{$newTable}` table created.", LogLevel::Info, true); // ------------------------------------------------------------ // Clean up Foreign Keys craft()->db->createCommand()->dropForeignKey('sproutforms_fields', 'formId'); SproutFormsPlugin::log("Removed formId Foreign Key Constraint from 'sproutforms_fields' table.", LogLevel::Info, true); } return true; }
/** * Notify admin * * @param SproutForms_FormModel $form * @param SproutForms_EntryModel $entry */ private function _notifyAdmin(SproutForms_FormModel $form, SproutForms_EntryModel $entry) { // Get our recipients $recipients = ArrayHelper::stringToArray($form->notificationRecipients); $recipients = array_unique($recipients); if (count($recipients)) { $email = new EmailModel(); $tabs = $form->getFieldLayout()->getTabs(); $settings = craft()->plugins->getPlugin('sproutforms')->getSettings(); $templateFolderOverride = $settings->templateFolderOverride; $emailTemplate = craft()->path->getPluginsPath() . 'sproutforms/templates/_special/templates/'; if ($templateFolderOverride) { $emailTemplateFile = craft()->path->getSiteTemplatesPath() . $templateFolderOverride . '/email'; foreach (craft()->config->get('defaultTemplateExtensions') as $extension) { if (IOHelper::fileExists($emailTemplateFile . '.' . $extension)) { $emailTemplate = craft()->path->getSiteTemplatesPath() . $templateFolderOverride . '/'; } } } // Set our Sprout Forms Email Template path craft()->path->setTemplatesPath($emailTemplate); $email->htmlBody = craft()->templates->render('email', array('formName' => $form->name, 'tabs' => $tabs, 'element' => $entry)); craft()->path->setTemplatesPath(craft()->path->getCpTemplatesPath()); $post = (object) $_POST; $email->fromEmail = $form->notificationSenderEmail; $email->fromName = $form->notificationSenderName; $email->subject = $form->notificationSubject; // Has a custom subject been set for this form? if ($form->notificationSubject) { try { $email->subject = craft()->templates->renderObjectTemplate($form->notificationSubject, $post); } catch (\Exception $e) { SproutFormsPlugin::log($e->getMessage(), LogLevel::Error); } } // custom replyTo has been set for this form if ($form->notificationReplyToEmail) { try { $email->replyTo = craft()->templates->renderObjectTemplate($form->notificationReplyToEmail, $post); if (!filter_var($email->replyTo, FILTER_VALIDATE_EMAIL)) { $email->replyTo = null; } } catch (\Exception $e) { SproutFormsPlugin::log($e->getMessage(), LogLevel::Error); } } foreach ($recipients as $emailAddress) { try { $email->toEmail = craft()->templates->renderObjectTemplate($emailAddress, $post); if (filter_var($email->toEmail, FILTER_VALIDATE_EMAIL)) { craft()->email->sendEmail($email, array('sproutFormsEntry' => $entry)); } } catch (\Exception $e) { SproutFormsPlugin::log($e->getMessage(), LogLevel::Error); } } } }
/** * @param SproutForms_EntryModel $entry * * @throws \Exception * @return bool */ public function saveEntry(SproutForms_EntryModel &$entry) { $isNewEntry = !$entry->id; if ($entry->id) { $entryRecord = SproutForms_EntryRecord::model()->findById($entry->id); if (!$entryRecord) { throw new Exception(Craft::t('No entry exists with id “{id}”', array('id' => $entry->id))); } } else { $entryRecord = new SproutForms_EntryRecord(); } $entryRecord->formId = $entry->formId; $entryRecord->ipAddress = $entry->ipAddress; $entryRecord->userAgent = $entry->userAgent; $entryRecord->validate(); $entry->addErrors($entryRecord->getErrors()); Craft::import('plugins.sproutforms.events.SproutForms_OnBeforeSaveEntryEvent'); $event = new SproutForms_OnBeforeSaveEntryEvent($this, array('entry' => $entry, 'isNewEntry' => $isNewEntry)); craft()->sproutForms->onBeforeSaveEntry($event); if (!$entry->hasErrors()) { $form = sproutForms()->forms->getFormById($entry->formId); $entry->getContent()->title = craft()->templates->renderObjectTemplate($form->titleFormat, $entry); $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if ($event->isValid) { $oldFieldContext = craft()->content->fieldContext; $oldContentTable = craft()->content->contentTable; craft()->content->fieldContext = $entry->getFieldContext(); craft()->content->contentTable = $entry->getContentTable(); SproutFormsPlugin::log('Transaction: Event is Valid'); $success = craft()->elements->saveElement($entry); SproutFormsPlugin::log('Element Saved: ' . $success); if ($success) { // Now that we have an element ID, save it on the other stuff if ($isNewEntry) { $entryRecord->id = $entry->id; } // Save our Entry Settings $entryRecord->save(false); if ($transaction !== null) { $transaction->commit(); SproutFormsPlugin::log('Transaction committed'); } // Reset our field context and content table to what they were previously craft()->content->fieldContext = $oldFieldContext; craft()->content->contentTable = $oldContentTable; Craft::import('plugins.sproutforms.events.SproutForms_OnSaveEntryEvent'); $event = new SproutForms_OnSaveEntryEvent($this, array('entry' => $entry, 'isNewEntry' => $isNewEntry, 'event' => 'saveEntry', 'entity' => $entry)); craft()->sproutForms->onSaveEntry($event); return true; } craft()->content->fieldContext = $oldFieldContext; craft()->content->contentTable = $oldContentTable; } else { SproutFormsPlugin::log('OnBeforeSaveEntryEvent is not valid', LogLevel::Error); if ($event->fakeIt) { sproutForms()->entries->fakeIt = true; } } } catch (\Exception $e) { SproutFormsPlugin::log('Failed to save element'); throw $e; } } else { SproutFormsPlugin::log('Service returns false'); return false; } }
/** * Any migration code in here is wrapped inside of a transaction. * * @return bool */ public function safeUp() { $oldTable = 'sproutforms_forms_old'; $newTable = 'sproutforms_forms'; // ------------------------------------------------------------ // Loop through each form in the old table and migrate it to the new table SproutFormsPlugin::log("Gathering all forms from the `{$oldTable}` table.", LogLevel::Info, true); $oldForms = craft()->db->createCommand()->select('*')->from($oldTable)->queryAll(); $user = craft()->userSession->getUser(); $email = isset($user->email) && $user->email != "" ? $user->email : ""; foreach ($oldForms as $oldForm) { SproutFormsPlugin::log("Build SproutForms_FormModel for " . $oldForm['name'] . " Form", LogLevel::Info, true); // Map any values from the old form to their // new column names to save to the new form $newForm = new SproutForms_FormModel(); $newForm->name = $oldForm['name']; $newForm->handle = $oldForm['handle']; $newForm->submitButtonText = $oldForm['submitButtonText']; $newForm->redirectUri = $oldForm['redirectUri']; $newForm->handle = $oldForm['handle']; $newForm->titleFormat = "Form submission on " . "{dateCreated|date('D, d M Y H:i:s')}"; $newForm->displaySectionTitles = 0; $newForm->notificationRecipients = $oldForm['email_distribution_list']; $newForm->notificationSubject = $oldForm['notification_subject']; $newForm->notificationSenderName = craft()->getSiteName(); $newForm->notificationSenderEmail = $email; $newForm->notificationReplyToEmail = $oldForm['notification_reply_to']; // Save the Form // Create a new content table sproutForms()->forms->saveForm($newForm); SproutFormsPlugin::log($newForm->name . " Form saved anew. Form ID: " . $newForm->id, LogLevel::Info, true); // Set our field context craft()->content->fieldContext = $newForm->getFieldContext(); craft()->content->contentTable = $newForm->getContentTable(); SproutFormsPlugin::log($newForm->name . " Form fieldContext: " . craft()->content->fieldContext, LogLevel::Info, true); SproutFormsPlugin::log($newForm->name . " Form contentTable: " . craft()->content->contentTable, LogLevel::Info, true); SproutFormsPlugin::log("Grab all fields for " . $newForm->name . " Form", LogLevel::Info, true); // Get the Form Fields $oldFormFields = craft()->db->createCommand()->select('*')->from('sproutforms_fields')->where('formId=:formId', array(':formId' => $oldForm['id']))->queryAll(); // Prepare a couple variables to help save our fields and layout $fieldLayout = array(); $requiredFields = array(); $fieldMap = array(); foreach ($oldFormFields as $oldFormField) { $newFieldHandle = str_replace("formId" . $oldForm['id'] . "_", "", $oldFormField['handle']); // Determine if we have a Number field // Might need to update teh Settings object to have the correct values min/max... if (strpos($oldFormField['validation'], 'numerical') !== FALSE) { $oldFormField['type'] = 'Number'; $oldFormField['settings'] = '{"min":"0","max":"","decimals":"0"}'; } // Build a field map of our old field handles and our new ones // so we can more easily match things up when inserting fields later $fieldMap[$oldFormField['handle']] = array('type' => $oldFormField['type'], 'newHandle' => $newFieldHandle); //------------------------------------------------------------ SproutFormsPlugin::log("Build FieldModel for " . $oldFormField['name'] . " Field", LogLevel::Info, true); // SproutFormsPlugin::log("The Fieldtype " . $newFieldType . " for the " . $oldFormField['name'] ." Field", LogLevel::Info, true); $newField = new FieldModel(); $newField->name = $oldFormField['name']; $newField->handle = $newFieldHandle; $newField->instructions = $oldFormField['instructions']; $newField->type = $oldFormField['type']; $newField->required = strpos($oldFormField['validation'], 'required') !== FALSE; $newField->settings = $oldFormField['settings']; // Save our field craft()->fields->saveField($newField); SproutFormsPlugin::log($oldFormField['name'] . " Field saved.", LogLevel::Info, true); $fieldLayout['Form'][] = $newField->id; if ($newField->required) { $requiredFields[] = $newField->id; } } // Set the field layout $fieldLayout = craft()->fields->assembleLayout($fieldLayout, $requiredFields); $fieldLayout->type = 'SproutForms_Form'; $newForm->setFieldLayout($fieldLayout); // Save our form again with a layouts sproutForms()->forms->saveForm($newForm); SproutFormsPlugin::log("Form saved again with fieldLayout", LogLevel::Info, true); // Migrate the Entries Content SproutFormsPlugin::log("Grab Form Entries for " . $oldForm['name'] . " Form", LogLevel::Info, true); // Get the Form Entries $oldFormEntries = craft()->db->createCommand()->select('*')->from('sproutforms_content')->where('formId=:formId', array(':formId' => $oldForm['id']))->queryAll(); foreach ($oldFormEntries as $oldFormEntry) { SproutFormsPlugin::log("Build SproutForms_EntryModel for Form Entry ID " . $oldFormEntry['id'], LogLevel::Info, true); $newFormEntry = new SproutForms_EntryModel(); SproutFormsPlugin::log("Server data: " . $oldFormEntry['serverData'], LogLevel::Info, true); $oldEntryServerData = json_decode($oldFormEntry['serverData']); $newFormEntry->formId = $newForm->id; if (isset($oldEntryServerData)) { $newFormEntry->ipAddress = $oldEntryServerData->ipAddress; $newFormEntry->userAgent = $oldEntryServerData->userAgent; $newFormEntry->dateCreated = $oldFormEntry['dateCreated']; $newFormEntry->dateUpdated = $oldFormEntry['dateUpdated']; } else { // Add null values if we don't have data for some reason $newFormEntry->ipAddress = NULL; $newFormEntry->userAgent = NULL; } $newFormFields = array(); // Loop through our field map foreach ($fieldMap as $oldHandle => $fieldInfo) { // If any columns in our current Form Entry match a // field in our field map, add that field to be saved if ($oldFormEntry[$oldHandle]) { $newFormFields[$fieldInfo['newHandle']] = $oldFormEntry[$oldHandle]; } } $_POST['fields'] = $newFormFields; $fieldsLocation = 'fields'; $newFormEntry->setContentFromPost($fieldsLocation); $newFormEntry->setContentPostLocation($fieldsLocation); SproutFormsPlugin::log("Try to Save Old Form Entry ID " . $oldFormEntry['id'], LogLevel::Info, true); sproutForms()->entries->saveEntry($newFormEntry); SproutFormsPlugin::log("Save New Form Entry ID " . $newFormEntry->id, LogLevel::Info, true); } } // Drop old field table if (craft()->db->tableExists('sproutforms_fields')) { SproutFormsPlugin::log("Dropping the 'sproutforms_fields' table.", LogLevel::Info, true); craft()->db->createCommand()->dropTable('sproutforms_fields'); SproutFormsPlugin::log("'sproutforms_fields' table dropped.", LogLevel::Info, true); } // Drop old entries table if (craft()->db->tableExists('sproutforms_content')) { SproutFormsPlugin::log("Dropping the 'sproutforms_content' table.", LogLevel::Info, true); craft()->db->createCommand()->dropTable('sproutforms_content'); SproutFormsPlugin::log("'sproutforms_content' table dropped.", LogLevel::Info, true); } // Drop old forms table if (craft()->db->tableExists($oldTable)) { SproutFormsPlugin::log("Dropping the old `{$oldTable}` table.", LogLevel::Info, true); craft()->db->createCommand('SET FOREIGN_KEY_CHECKS = 0;')->execute(); // Need to drop this after we drop the fields table because fields has a fk craft()->db->createCommand()->dropTable($oldTable); craft()->db->createCommand('SET FOREIGN_KEY_CHECKS = 1;')->execute(); SproutFormsPlugin::log("`{$oldTable}` table dropped.", LogLevel::Info, true); } return true; }
/** * @param mixed $message * @param array $vars */ public function log($message, array $vars = array()) { if (is_string($message)) { $message = Craft::t($message, $vars); } else { $message = print_r($message, true); } SproutFormsPlugin::log($message, LogLevel::Info); }
/** * Save a field. */ public function actionSaveField() { $this->requirePostRequest(); // Make sure our field has a section // @TODO - handle this much more gracefully $tabId = craft()->request->getPost('tabId'); // Get the Form these fields are related to $formId = craft()->request->getRequiredPost('formId'); $form = sproutForms()->forms->getFormById($formId); $field = new FieldModel(); $field->id = craft()->request->getPost('fieldId'); $field->name = craft()->request->getRequiredPost('name'); $field->handle = craft()->request->getRequiredPost('handle'); $field->instructions = craft()->request->getPost('instructions'); $field->required = craft()->request->getPost('required'); $field->translatable = (bool) craft()->request->getPost('translatable'); $field->type = craft()->request->getRequiredPost('type'); $typeSettings = craft()->request->getPost('types'); if (isset($typeSettings[$field->type])) { $field->settings = $typeSettings[$field->type]; } // Set our field context craft()->content->fieldContext = $form->getFieldContext(); craft()->content->contentTable = $form->getContentTable(); // Does our field validate? if (!craft()->fields->validateField($field)) { SproutFormsPlugin::log("Field does not validate."); // Send the field back to the template craft()->urlManager->setRouteVariables(array('field' => $field)); // Route our request back to the field template $route = craft()->urlManager->parseUrl(craft()->request); craft()->runController($route); craft()->end(); } // Save a new field if (!$field->id) { SproutFormsPlugin::log('New Field'); $isNewField = true; } else { SproutFormsPlugin::log('Existing Field'); $isNewField = false; } // Save our field craft()->fields->saveField($field); // Now let's add this field to our field layout // ------------------------------------------------------------ // Set the field layout $oldFieldLayout = $form->getFieldLayout(); $oldFields = $oldFieldLayout->getFields(); $oldTabs = $oldFieldLayout->getTabs(); $tabFields = array(); $postedFieldLayout = array(); $requiredFields = array(); // If no tabs exist, let's create a // default one for all of our fields if (!$oldTabs) { // Create a tab $fieldLayoutTab = new FieldLayoutTabModel(); $fieldLayoutTab->name = Craft::t('Form'); $fieldLayoutTab->sortOrder = 1; if ($oldFields) { $fieldSortOrder = 0; // Add any existing fields to a default tab foreach ($oldFields as $oldFieldLayoutField) { $fieldSortOrder++; $newField = new FieldLayoutFieldModel(); $newField->fieldId = $oldFieldLayoutField->fieldId; $newField->required = $oldFieldLayoutField->required; $newField->sortOrder = $fieldSortOrder; $tabFields[] = $newField; $postedFieldLayout[$fieldLayoutTab->name][] = $oldFieldLayoutField->fieldId; if ($oldFieldLayoutField->required) { $requiredFields[] = $oldFieldLayoutField->fieldId; } } } // Add our new field $postedFieldLayout[$fieldLayoutTab->name][] = $field->id; $fieldLayoutTab->setFields($tabFields); } else { foreach ($oldTabs as $oldTab) { $oldTabFields = $oldTab->getFields(); foreach ($oldTabFields as $oldFieldLayoutField) { $postedFieldLayout[$oldTab->name][] = $oldFieldLayoutField->fieldId; if ($oldFieldLayoutField->required) { $requiredFields[] = $oldFieldLayoutField->fieldId; } } // Add our new field to the tab it belongs to if ($isNewField && $tabId == $oldTab->id) { $postedFieldLayout[$oldTab->name][] = $field->id; } } } // Set the field layout $fieldLayout = craft()->fields->assembleLayout($postedFieldLayout, $requiredFields); $fieldLayout->type = 'SproutForms_Form'; $form->setFieldLayout($fieldLayout); // Hand the field off to be saved in the // field layout of our Form Element if (sproutForms()->forms->saveForm($form)) { SproutFormsPlugin::log('Field Saved'); craft()->userSession->setNotice(Craft::t('Field saved.')); $this->redirectToPostedUrl($field); } else { SproutFormsPlugin::log("Couldn't save field."); craft()->userSession->setError(Craft::t('Couldn’t save field.')); // Send the field back to the template craft()->urlManager->setRouteVariables(array('field' => $field)); } }
/** * @param SproutForms_FormModel $form * * @throws \Exception * @return bool */ public function saveForm(SproutForms_FormModel $form) { $formRecord = new SproutForms_FormRecord(); $isNewForm = true; if ($form->id && !$form->saveAsNew) { $formRecord = SproutForms_FormRecord::model()->findById($form->id); if (!$formRecord) { throw new Exception(Craft::t('No form exists with the ID “{id}”', array('id' => $form->id))); } $oldForm = SproutForms_FormModel::populateModel($formRecord); $isNewForm = false; $hasLayout = count($form->getFieldLayout()->getFields()) > 0; // Add the oldHandle to our model so we can determine if we // need to rename the content table $form->oldHandle = $formRecord->getOldHandle(); } // Create our new Form Record $formRecord->name = $form->name; $formRecord->handle = $form->handle; $formRecord->titleFormat = $form->titleFormat ? $form->titleFormat : "{dateCreated|date('D, d M Y H:i:s')}"; $formRecord->displaySectionTitles = $form->displaySectionTitles; $formRecord->groupId = $form->groupId; $formRecord->redirectUri = $form->redirectUri; $formRecord->submitAction = $form->submitAction; $formRecord->submitButtonText = $form->submitButtonText; $formRecord->notificationEnabled = $form->notificationEnabled; $formRecord->notificationRecipients = $form->notificationRecipients; $formRecord->notificationSubject = $form->notificationSubject; $formRecord->notificationSenderName = $form->notificationSenderName; $formRecord->notificationSenderEmail = $form->notificationSenderEmail; $formRecord->notificationReplyToEmail = $form->notificationReplyToEmail; $formRecord->validate(); $form->addErrors($formRecord->getErrors()); if ($form->saveAsNew) { $form->name = $formRecord->name; $form->handle = $formRecord->handle; } if (!$form->hasErrors()) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { // Set the field context craft()->content->fieldContext = $form->getFieldContext(); craft()->content->contentTable = $form->getContentTable(); if ($isNewForm) { $fieldLayout = $form->getFieldLayout(); // Save the field layout craft()->fields->saveLayout($fieldLayout); // Assign our new layout id info to our form model and records $form->fieldLayoutId = $fieldLayout->id; $form->setFieldLayout($fieldLayout); $formRecord->fieldLayoutId = $fieldLayout->id; } else { // If we have a layout use it, otherwise // since this is an existing form, grab the oldForm layout if ($hasLayout) { // Delete our previous record craft()->fields->deleteLayoutById($oldForm->fieldLayoutId); $fieldLayout = $form->getFieldLayout(); // Save the field layout craft()->fields->saveLayout($fieldLayout); // Assign our new layout id info to our // form model and records $form->fieldLayoutId = $fieldLayout->id; $form->setFieldLayout($fieldLayout); $formRecord->fieldLayoutId = $fieldLayout->id; } else { // We don't have a field layout right now $form->fieldLayoutId = NULL; } } // Create the content table first since the form will need it $oldContentTable = $this->getContentTableName($form, true); $newContentTable = $this->getContentTableName($form); // Do we need to create/rename the content table? if (!craft()->db->tableExists($newContentTable)) { if ($oldContentTable && craft()->db->tableExists($oldContentTable)) { MigrationHelper::renameTable($oldContentTable, $newContentTable); } else { $this->_createContentTable($newContentTable); } } if (craft()->elements->saveElement($form)) { // Create the new fields if ($form->saveAsNew) { // Duplicate the fields in the newContent Table also set the fields in the craft fields table $newFields = array(); foreach ($form->getFields() as $key => $value) { $field = new FieldModel(); $field->name = $value->name; $field->handle = $value->handle; $field->instructions = $value->instructions; $field->required = $value->required; $field->translatable = (bool) $value->translatable; $field->type = $value->type; if (isset($value->settings)) { $field->settings = $value->settings; } craft()->content->fieldContext = $form->getFieldContext(); craft()->content->contentTable = $form->getContentTable(); craft()->fields->saveField($field); array_push($newFields, $field); SproutFormsPlugin::log('Saved field as new ' . $field->id); } // Update fieldId on layoutfields table $fieldLayout = $form->getFieldLayout(); $fieldLayoutIds = FieldLayoutFieldRecord::model()->findAll("layoutId = {$fieldLayout->id}"); foreach ($fieldLayoutIds as $key => $layout) { SproutFormsPlugin::log('Updated field layout ' . $layout->id); $model = FieldLayoutFieldRecord::model()->findByPk($layout->id); $model->fieldId = $newFields[$key]->id; $model->save(); } } // Now that we have an element ID, save it on the other stuff if ($isNewForm) { $formRecord->id = $form->id; } // Save our Form Settings $formRecord->save(false); if ($transaction !== null) { $transaction->commit(); } return true; } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } } }