Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
hungoptimizely committed Jan 4, 2024
2 parents 21cf29e + e0cc4f3 commit 6a2f399
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 17 deletions.
45 changes: 43 additions & 2 deletions src/@episerver/forms-react/src/components/FormBody.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useEffect, useRef } from "react";
import { useForms } from "../context/store";
import { StepHelper, FormContainer, FormSubmitter, IdentityInfo, isInArray, isNull, isNullOrEmpty, FormSubmitModel, FormSubmitResult, SubmitButton, FormCache, FormConstants, ProblemDetail, StepDependCondition } from "@episerver/forms-sdk";
import { StepHelper, FormContainer, FormSubmitter, IdentityInfo, isInArray, isNull, isNullOrEmpty, FormSubmitModel, FormSubmitResult, SubmitButton, FormCache, FormConstants, ProblemDetail, StepDependCondition, FormSubmission, FormStorage } from "@episerver/forms-sdk";
import { RenderElementInStep } from "./RenderElementInStep";
import { DispatchFunctions } from "../context/dispatchFunctions";
import { FormStepNavigation } from "./FormStepNavigation";
Expand Down Expand Up @@ -63,6 +63,37 @@ export const FormBody = (props: FormBodyProps) => {
message.current = error;
}

const buildConfirmMessage = (confirmationMessage: string, data: FormSubmission[], form: FormContainer): string => {
const fieldsToIgnore = ["FormStepBlock"]
const newLine = "\n"
let message = confirmationMessage + newLine;

data.forEach(element => {
let formElement = form.formElements.find(fe => fe.key === element.elementKey)

if (formElement && fieldsToIgnore.indexOf(formElement.contentType) === -1){
message += `${formElement.displayName}: ${element.value}${newLine}`;
}
});

return message
}

const handleConfirm = () => {
const form = formContext?.formContainer ?? {} as FormContainer;
const confirmationMessage = form.properties.confirmationMessage;
let confimStatus = true;

if (!isNullOrEmpty(confirmationMessage) && form.properties.showSummarizedData) {
const formStorage = new FormStorage(form);
const data = formStorage.loadFormDataFromStorage();
const confirmationMessageWithData = buildConfirmMessage(confirmationMessage, data, form)
confimStatus = confirm(confirmationMessageWithData);
}

return confimStatus
}

const handleSubmit = (e: any) => {
e.preventDefault();

Expand All @@ -77,6 +108,10 @@ export const FormBody = (props: FormBodyProps) => {
//when submitting by SubmitButton, isProgressiveSubmit default is true
isProgressiveSubmit.current = true;
}

let isLastStep = currentStepIndex === form.steps.length - 1;


//filter submissions by active elements and current step
let formSubmissions = (formContext?.formSubmissions ?? [])
.filter(fs => !isInArray(fs.elementKey, formContext?.dependencyInactiveElements ?? []) && stepHelper.isInCurrentStep(fs.elementKey, currentStepIndex));
Expand All @@ -92,7 +127,13 @@ export const FormBody = (props: FormBodyProps) => {
return;
}

let isLastStep = currentStepIndex === form.steps.length - 1;
// Confirm if user want to submit the form
if (submitButton?.properties?.finalizeForm || isLastStep) {
if (!handleConfirm()) {
return
}
}

let model: FormSubmitModel = {
formKey: form.key,
locale: form.locale,
Expand Down
31 changes: 16 additions & 15 deletions src/@episerver/forms-sdk/src/form-submit/formSubmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class FormSubmitter {
readonly _form: FormContainer
readonly _baseUrl: string

constructor(form: FormContainer, baseUrl: string){
constructor(form: FormContainer, baseUrl: string) {
this._form = form;
this._baseUrl = baseUrl;
}
Expand All @@ -92,13 +92,13 @@ export class FormSubmitter {
*/
combineData(dataFromStorage: FormSubmission[], submissionData: FormSubmission[]): FormSubmission[] {
const mapFromArray = new Map<string, FormSubmission>();

submissionData.forEach(element => {
mapFromArray.set(element.elementKey, element);
});

const combinedData = [...submissionData, ...dataFromStorage.filter(element => !mapFromArray.has(element.elementKey))];

return combinedData;
}

Expand All @@ -107,13 +107,7 @@ export class FormSubmitter {
* @param formSubmission the array of form submission to post
*/
doSubmit(model: FormSubmitModel): Promise<FormSubmitResult> {
return new Promise<FormSubmitResult>((resolve, reject)=>{
let formStorage = new FormStorage(this._form);

// Save data to storage of browser
let currentData = formStorage.loadFormDataFromStorage()
let dataCombined = this.combineData(currentData,model.submissionData)
formStorage.saveFormDataToStorage(dataCombined);
return new Promise<FormSubmitResult>((resolve, reject) => {
// Post data to API
let formData = new FormData();
formData.append("formKey", model.formKey);
Expand All @@ -128,7 +122,7 @@ export class FormSubmitter {
let ovalue = data.value;
let key = `${FormConstants.FormFieldPrefix}${data.elementKey}`;

if(isNull(ovalue)) {
if (isNull(ovalue)) {
return;
}

Expand All @@ -150,12 +144,19 @@ export class FormSubmitter {
fileNames += files[idx].name + "|"; // charactor | cannot be used in filename and then is safe for splitting later
}
formData.append(key, fileNames);
data.value = fileNames
}
else {
formData.append(key, data.value);
}
});

// Save data to session storage
let formStorage = new FormStorage(this._form);
let currentData = formStorage.loadFormDataFromStorage()
let dataCombined = this.combineData(currentData, model.submissionData)
formStorage.saveFormDataToStorage(dataCombined);

//init a request and call ajax
let requestInit: RequestInit = {
method: "POST",
Expand All @@ -168,9 +169,9 @@ export class FormSubmitter {
fetch(`${this._baseUrl}${ApiConstant.apiEndpoint}`, requestInit)
.then(async (response: Response) => {
let json = await response.json();
if(response.ok){
if (response.ok) {
let result = json as FormSubmitResult;
if(result.success && model.isFinalized){
if (result.success && model.isFinalized) {
//clear cache of form submission
formStorage.removeFormDataInStorage();
}
Expand All @@ -191,7 +192,7 @@ export class FormSubmitter {
* @param formSubmission the array of form submission to post
* @returns An array of validation result
*/
doValidate(formSubmissions: FormSubmission[]): FormValidationResult[]{
doValidate(formSubmissions: FormSubmission[]): FormValidationResult[] {
return this._form.formElements
.filter(e => formSubmissions.some(fs => equals(fs.elementKey, e.key)))
.map(e => {
Expand Down

0 comments on commit 6a2f399

Please sign in to comment.