/** * Save a Form Field * * @param SproutForms_FormModel $form * @param FieldModel $field * @param boolean $validate * @throws \Exception * @return boolean true/false */ public function saveField(SproutForms_FormModel $form, FieldModel $field, $validate = true) { if (!$validate || craft()->fields->validateField($field)) { $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null; try { if ($field->id) { $fieldLayoutFields = array(); $sortOrder = 0; // Save a new field layout with all form fields // to make sure we capture the required setting $sortOrder++; foreach ($form->getFields() as $oldField) { if ($oldField->id == $field->id) { $fieldLayoutFields[] = array('fieldId' => $field->id, 'required' => $field->required, 'sortOrder' => $sortOrder); } else { $fieldLayoutFields[] = array('fieldId' => $oldField->id, 'required' => $oldField->required, 'sortOrder' => $sortOrder); } } $fieldLayout = new FieldLayoutModel(); $fieldLayout->type = 'SproutForms_Form'; $fieldLayout->setFields($fieldLayoutFields); // Update the form model & record with our new field layout ID $form->setFieldLayout($fieldLayout); } else { // Save the new field craft()->fields->saveField($field); // Save a new field layout with all form fields $fieldLayoutFields = array(); $sortOrder = 0; foreach ($form->getFields() as $oldField) { $sortOrder++; $fieldLayoutFields[] = array('fieldId' => $oldField->id, 'required' => $oldField->required, 'sortOrder' => $sortOrder); } $sortOrder++; $fieldLayoutFields[] = array('fieldId' => $field->id, 'required' => $field->required, 'sortOrder' => $sortOrder); $fieldLayout = new FieldLayoutModel(); $fieldLayout->type = 'SproutForms_Form'; $fieldLayout->setFields($fieldLayoutFields); $form->setFieldLayout($fieldLayout); } sproutForms()->forms->saveForm($form); if ($transaction !== null) { $transaction->commit(); } } catch (\Exception $e) { if ($transaction !== null) { $transaction->rollback(); } throw $e; } return true; } else { return false; } }
/** * Populates an element model based on a query result. * * @param array $row * @return array */ public function populateElementModel($row) { return SproutForms_FormModel::populateModel($row); }
/** * Get Forms by Group ID * * @param int $groupId * @return SproutForms_FormModel */ public function getFormsByGroupId($groupId) { $query = craft()->db->createCommand()->from('sproutforms_forms')->where('groupId=:groupId', array('groupId' => $groupId))->order('name')->queryAll(); return SproutForms_FormModel::populateModels($query); }
/** * Save a form */ public function actionSaveForm() { $this->requirePostRequest(); $form = new SproutForms_FormModel(); if (craft()->request->getPost('saveAsNew')) { $form->saveAsNew = true; } else { $form->id = craft()->request->getPost('id'); } $form->groupId = craft()->request->getPost('groupId'); $form->name = craft()->request->getPost('name'); $form->handle = craft()->request->getPost('handle'); $form->titleFormat = craft()->request->getPost('titleFormat'); $form->displaySectionTitles = craft()->request->getPost('displaySectionTitles'); $form->redirectUri = craft()->request->getPost('redirectUri'); $form->submitAction = craft()->request->getPost('submitAction'); $form->submitButtonText = craft()->request->getPost('submitButtonText'); $form->notificationEnabled = craft()->request->getPost('notificationEnabled'); $form->notificationRecipients = craft()->request->getPost('notificationRecipients'); $form->notificationSubject = craft()->request->getPost('notificationSubject'); $form->notificationSenderName = craft()->request->getPost('notificationSenderName'); $form->notificationSenderEmail = craft()->request->getPost('notificationSenderEmail'); $form->notificationReplyToEmail = craft()->request->getPost('notificationReplyToEmail'); // Set the field layout $fieldLayout = craft()->fields->assembleLayoutFromPost(); $fieldLayout->type = 'SproutForms_Form'; $form->setFieldLayout($fieldLayout); // Delete any fields removed from the layout $deletedFields = craft()->request->getPost('deletedFields'); if ($deletedFields) { // Backup our field context and content table $oldFieldContext = craft()->content->fieldContext; $oldContentTable = craft()->content->contentTable; // Set our field content and content table to work with our form output craft()->content->fieldContext = $form->getFieldContext(); craft()->content->contentTable = $form->getContentTable(); foreach ($deletedFields as $fieldId) { craft()->fields->deleteFieldById($fieldId); } // Reset our field context and content table to what they were previously craft()->content->fieldContext = $oldFieldContext; craft()->content->contentTable = $oldContentTable; } // Save it if (sproutForms()->forms->saveForm($form)) { craft()->userSession->setNotice(Craft::t('Form saved.')); $_POST['redirect'] = str_replace('{id}', $form->id, $_POST['redirect']); $this->redirectToPostedUrl(); } else { craft()->userSession->setError(Craft::t('Couldn’t save form.')); $notificationFields = array('notificationRecipients', 'notificationSubject', 'notificationSenderName', 'notificationSenderEmail', 'notificationReplyToEmail'); $notificationErrors = false; foreach ($form->getErrors() as $fieldHandle => $error) { if (in_array($fieldHandle, $notificationFields)) { $notificationErrors = 'error'; break; } } // Send the form back to the template craft()->urlManager->setRouteVariables(array('form' => $form, 'notificationErrors' => $notificationErrors)); } }
/** * 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_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; } } }