Skip to content

Commit

Permalink
Merge pull request #1531 from hlxsites/rfq-form
Browse files Browse the repository at this point in the history
Migrate RFQ iframe to form block
  • Loading branch information
dev-rajneeshkumar authored Nov 22, 2024
2 parents dea0913 + 1193d5c commit b4c8a9c
Show file tree
Hide file tree
Showing 6 changed files with 189 additions and 206 deletions.
40 changes: 39 additions & 1 deletion blocks/forms/formHelper.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { input } from '../../scripts/dom-helpers.js';
import { getCookie } from '../../scripts/scripts.js';

/* Helper functions */
export const RESOURCEKEYS = ['heading', 'region', 'portalId', 'formId', 'redirectUrl', 'productFamily', 'productPrimaryApplication', 'cmp'];
Expand Down Expand Up @@ -103,7 +104,7 @@ export function createSalesforceForm(hubspotForm, formConfig) {
});

/* qdc */
const qdcCall = hubspotForm.querySelector('input[name="requested_a_salesperson_to_call__c"]').checked;
const qdcCall = hubspotForm.querySelector('input[name="requested_a_salesperson_to_call__c"]');
let qdc = '';

if (qdcCall) {
Expand Down Expand Up @@ -174,3 +175,40 @@ export function createSalesforceForm(hubspotForm, formConfig) {
setTimeout(() => { window.top.location.href = returnURL; }, 200);
}
}

/* get form ready */
export function getFormFieldValues(formConfig) {
// Get the `cmp` parameters from URL or cookie
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
const cmpCookieValue = getCookie('cmp');
const valuecmp = params.cmp || cmpCookieValue;

return {
product_family__c: formConfig.productFamily,
research_area: formConfig.researchArea,
product_primary_application__c: formConfig.productPrimaryApplication,
requested_qdc_discussion__c: formConfig.qdc,
cmp: valuecmp || formConfig.cmp,
return_url: formConfig.redirectUrl,
product_selection__c: formConfig.productSelection,
google_analytics_medium__c: formConfig.googleAnalyticsMedium,
google_analytics_source__c: formConfig.googleAnalyticsSource,
keyword_ppc__c: formConfig.keywordPPC,
gclid__c: formConfig.gclid,
product_image: formConfig.productImage,
product_bundle_image: formConfig.productBundleImage,
product_bundle: formConfig.productBundle,
qdc: formConfig.qdc,
};
}

// Function to update multiple form fields
export function updateFormFields(form, fieldValues) {
Object.entries(fieldValues).forEach(([fieldName, value]) => {
if (value && form.querySelector(`input[name="${fieldName}"]`)) {
form.querySelector(`input[name="${fieldName}"]`).value = value;
}
});
}
22 changes: 16 additions & 6 deletions blocks/forms/forms.css
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
height: 40px;
line-height: 1.4286;
outline: none;
padding: 5px;
padding: 5px 15px;
max-width: 100%;
width: 100%;
margin-bottom: 0;
Expand Down Expand Up @@ -133,6 +133,7 @@ label.privacy {
font-weight: 400;
line-height: 1.4286;
margin-bottom: 0;
display: block;
}

.hs-fieldtype-booleancheckbox .input {
Expand All @@ -158,6 +159,7 @@ label.privacy {
line-height: 1.5;
margin: 0;
width: 100%;
text-align: left;
}

.hs-error-msgs.inputs-list {
Expand All @@ -169,10 +171,6 @@ label.privacy {
margin-top: 0;
}

.form-columns-2 + .form-columns-1 .hs-form-field:first-child {
padding-top: 15px;
}

.form-columns-1 .hs-form-field.hs-subscribe:first-child {
margin-top: 9px;
}
Expand Down Expand Up @@ -226,10 +224,15 @@ label.privacy {
}

/* hubspot form */
main form fieldset[class*='form-columns'] .input {
margin-right: 0 !important;
}

.hubspot-form form {
display: flex;
flex-direction: column;
line-height: 16px;
text-align: left;
}

.hubspot-form form .hs-submit {
Expand Down Expand Up @@ -269,8 +272,15 @@ input[type="submit"] {
text-decoration: none !important;
}

@media only screen and (min-width: 768px) {
main form fieldset.form-columns-2 {
display: flex;
gap: 15px;
}
}

@media only screen and (max-width: 400px) {
.hbspt-form {
padding-bottom: 110px;
}
}
}
174 changes: 27 additions & 147 deletions blocks/forms/forms.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
import {
button, div, h3, input,
a, button, div, h3, label,
} from '../../scripts/dom-helpers.js';
import { toCamelCase, toClassName } from '../../scripts/lib-franklin.js';
import { getCookie, loadScript } from '../../scripts/scripts.js';
import { loadCSS, toCamelCase, toClassName } from '../../scripts/lib-franklin.js';
import { loadScript } from '../../scripts/scripts.js';
import {
fieldsObj, getDefaultForKey, marketingOptin, OID, prodPrimApp, QDCRrequest, RESOURCEKEYS,
createSalesforceForm, getDefaultForKey, getFormFieldValues, RESOURCEKEYS, updateFormFields,
} from './formHelper.js';

/* custom form fields */
function createCustomField(hubspotFormData, fieldName, newName) {
const fieldVal = hubspotFormData.get(fieldName);
if (fieldVal && fieldVal !== undefined && fieldVal !== '') {
const elementCompany = input({ name: newName, value: fieldVal, type: 'hidden' });
return elementCompany;
}
return 0;
}

/* extract data from table */
async function extractFormData(block) {
const blockData = {};
Expand All @@ -35,53 +25,19 @@ async function extractFormData(block) {
}

/* create hubspot form */
function createHubSpotForm(formConfig, target) {
export function createHubSpotForm(formConfig, target) {
try {
hbspt.forms.create({ // eslint-disable-line
region: formConfig.region,
portalId: formConfig.portalId,
region: formConfig.region || 'na1',
portalId: formConfig.portalId || '20222769',
formId: formConfig.formId,
target: `#${target}`,
onFormReady: (form) => {
// Handle Salesforce hidden fields via message event listener
window.addEventListener('message', (event) => {
if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
// Get the cmp parameters
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
const cmpCookieValue = getCookie('cmp');
const valuecmp = params.cmp || cmpCookieValue;

// Salesforce form fields
const mProductFamily = formConfig.productFamily;
const mResearchArea = formConfig.researchArea;
const mPrimaryApplication = formConfig.productPrimaryApplication;
const mRequestedQdcDiscussionC = formConfig.qdc;
const mCmp = valuecmp || formConfig.cmp;
const mReturnUrl = formConfig.redirectUrl;

// Update the form with SFDC values if they exist
if (form.querySelector('input[name="return_url"]') && mReturnUrl !== '') {
form.querySelector('input[name="return_url"]').value = mReturnUrl;
}
if (form.querySelector('input[name="product_family__c"]') && mProductFamily !== '') {
form.querySelector('input[name="product_family__c"]').value = mProductFamily;
}
if (form.querySelector('input[name="research_area"]') && mResearchArea !== '') {
form.querySelector('input[name="research_area"]').value = mResearchArea;
}

if (form.querySelector('input[name="product_primary_application__c"]') && mPrimaryApplication !== '') {
form.querySelector('input[name="product_primary_application__c"]').value = mPrimaryApplication;
}
if (form.querySelector('input[name="requested_qdc_discussion__c"]') && mRequestedQdcDiscussionC !== '') {
form.querySelector('input[name="requested_qdc_discussion__c"]').value = mRequestedQdcDiscussionC;
}

if (form.querySelector('input[name="cmp"]') && mCmp) {
form.querySelector('input[name="cmp"]').value = mCmp;
}
const fieldValues = getFormFieldValues(formConfig);
updateFormFields(form, fieldValues);

// Customize the submit button
const submitInput = form.querySelector('input[type="submit"]');
Expand All @@ -92,103 +48,26 @@ function createHubSpotForm(formConfig, target) {
}, submitInput.value || 'Submit');
submitInput.replaceWith(submitButton);
}

const privacy = document.querySelector('label.privacy');
if (!privacy) {
const privacyMsg = label({ class: 'privacy' },
'By submitting your details, you confirm that you have reviewed and agree with the Molecular Devices ',
a({
href: 'https://www.moleculardevices.com/privacy', title: 'Privacy Policy', target: '_blank', rel: 'noopener',
}, 'Privacy Policy'),
', and that you understand your privacy choices as they pertain to your personal data as provided in the ',
a({
href: 'https://www.moleculardevices.com/privacy', title: 'Privacy Policy', target: '_blank', rel: 'noopener',
}, 'Privacy Policy'),
' under “Your Privacy Choices”.');
form.appendChild(privacyMsg);
}
}
});
},
onFormSubmit: (hubspotForm) => {
setTimeout(() => {
const hubspotFormData = new FormData(hubspotForm);
const form = document.createElement('form');
form.method = 'POST';
form.action = 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';

// Your org ID
const elementOID = input({ name: 'oid', value: OID, type: 'hidden' });
form.appendChild(elementOID);

// generate a form from Customize | Leads | Web-to-Lead to figure out more
fieldsObj.forEach(({ newName, fieldName }) => {
const inputField = createCustomField(hubspotFormData, fieldName, newName);
if (inputField && inputField !== 0) {
form.appendChild(inputField);
}
});

/* qdc */ // test case
const qdcCall = hubspotForm.querySelector('input[name="requested_a_salesperson_to_call__c"]').checked;
let qdc = '';

if (qdcCall) {
qdc = 'Call';
} else {
qdc = hubspotFormData.get('requested_qdc_discussion__c') || ''; // test case
}
if (qdc === '') {
qdc = formConfig.qdc || '';
}

const elementqdcrequest = input({ name: QDCRrequest, value: qdc, type: 'hidden' });
form.appendChild(elementqdcrequest);

/* subscribe */
let subscribe = hubspotForm.querySelector('input[name="subscribe"]').checked;
if (!subscribe) { subscribe = 'false'; }
const elementmarketingoptin = input({ name: marketingOptin, value: subscribe, type: 'hidden' });
form.appendChild(elementmarketingoptin);

// SFDC redirects to returnURL in the response to the form post
let returnURL = hubspotFormData.get('return_url');
if (!returnURL) {
returnURL = formConfig.redirectUrl;
}

if (returnURL) {
const hsmduri = returnURL;
const hsmdkey = 'rfq';
const hsmdvalue = qdc;

const re = new RegExp(`([?&])${hsmdkey}=.*?(&|$)`, 'i');
const separator = hsmduri.indexOf('?') !== -1 ? '&' : '?';

if (hsmduri.match(re)) {
returnURL = hsmduri.replace(re, `$1${hsmdkey}=${hsmdvalue}$2`);
} else {
returnURL = `${hsmduri}${separator}${hsmdkey}=${hsmdvalue}`;
}

returnURL = `${returnURL}&subscribe=${subscribe}`;
}
const elementRetURL = input({ name: 'retURL', value: returnURL, type: 'hidden' });
form.appendChild(elementRetURL);

// test case
const primaryApplicationText = hubspotFormData.get('product_primary_application__c');
const productAndPrimaryFtype = hubspotFormData.get('product_and_primary_application_na___service_contracts');
let primaryApplication = '';
if (productAndPrimaryFtype) {
const checkboxes = hubspotForm.getElementsByName('product_and_primary_application_na___service_contracts');
for (let i = 0; i < checkboxes.length; i += 1) {
if (checkboxes[i].checked) {
primaryApplication += `${checkboxes[i].value} , `;
}
}
} else if (primaryApplicationText !== '' && primaryApplicationText !== undefined) {
primaryApplication = primaryApplicationText;
}
const elementprodprimapp = input({ name: prodPrimApp, value: primaryApplication, type: 'hidden' });
form.appendChild(elementprodprimapp);

// Append the form to the body
document.body.appendChild(form);

const allowedValues = ['Call', 'Demo', 'Quote'];
if (allowedValues.includes(qdc)) {
form.submit();
} else {
setTimeout(() => { window.top.location.href = returnURL; }, 200);
}
/* END */
}, 1000);
createSalesforceForm(hubspotForm, formConfig);
},
});
} catch (e) {
Expand All @@ -199,7 +78,8 @@ function createHubSpotForm(formConfig, target) {
}

/* load hubspot script */
function loadHubSpotScript(callback) {
export function loadHubSpotScript(callback) {
loadCSS('/blocks/forms/forms.css');
loadScript(`https://js.hsforms.net/forms/v2.js?v=${new Date().getTime()}`, callback);
}

Expand Down
Loading

0 comments on commit b4c8a9c

Please sign in to comment.