Add a request-quote button
For products that are sold on request, such as custom or B2B products, shoppers request a quote instead of ordering. In this tutorial you add a request-quote button: first the ready-made <xpv-request-quote>, then a button and dialog of your own.
The finished code is the request-quote.html page of the example apps.
Before you start: set up a quote request for the product in Expivi, with the form that shoppers fill in. Without it, the request-quote button doesn't show.
How a quote request works
useRequestQuote(configurator) returns a quote controller:
isVisible:truewhen a quote request is set up for the product.formId: the ID of the quote form set up in Expivi.sendEmail:truewhen Expivi emails the shopper. The form then needs the shopper's email address.submit(values): sends the quote request with the form values.isBusyandsubscribeBusy(callback): whether a request is being sent.
When you call submit(), the controller saves the current configuration as a snapshot in Expivi and sends the quote request with the form values and a link to that snapshot. The link points to your product page if you set the getConfigurationLink option. The controller throws an error when sending fails.
1. Register the components
<xpv-request-quote> is part of offer-inquiry. The quote form is rendered by <xpv-form-renderer>, from form-renderer.
import { defineCustomElements as defineOfferInquiryElements } from '@expivi/sdk/offer-inquiry/components';
import { defineCustomElements as defineFormRendererElements } from '@expivi/sdk/form-renderer/components';
defineOfferInquiryElements();
defineFormRendererElements();
2. Add the ready-made button
Create the controller once the configurator is READY and give it to <xpv-request-quote>. The component shows a button that opens the quote form in a dialog, and sends the request. It renders nothing when quotes are not set up for the product.
- Vanilla JS
- Vue
- React
import '../shared/setup.js';
import { useRequestQuote } from '@expivi/sdk';
// <xpv-request-quote> lives in offer-inquiry; the quote form it shows comes from form-renderer.
import { defineCustomElements as defineOfferInquiryElements } from '@expivi/sdk/offer-inquiry/components';
import { defineCustomElements as defineFormRendererElements } from '@expivi/sdk/form-renderer/components';
import { mountQuoteButton } from '../components/quote-button.js';
import { createExpiviElement, mountProductConfigurator, startConfigurator } from '../shared/configurator.js';
import { renderShopHeader } from '../shared/navigation.js';
renderShopHeader('request-quote');
defineOfferInquiryElements();
defineFormRendererElements();
startConfigurator({
onReady(configurator) {
mountProductConfigurator(configurator);
const quoteController = useRequestQuote(configurator);
// The ready-made component renders nothing when quotes are not enabled for the product.
document
.querySelector('#quote-component')
.append(createExpiviElement('xpv-request-quote', { controller: quoteController }));
mountQuoteButton(document.querySelector('#quote-button'), quoteController);
},
});
<script setup lang="ts">
import { useRequestQuote, type ProductConfigurator } from '@expivi/sdk';
import QuoteButton from './QuoteButton.vue';
/** Rendered once the product is READY, so it can create its controller right away. */
const props = defineProps<{ configurator: ProductConfigurator }>();
const quoteController = useRequestQuote(props.configurator);
</script>
<template>
<section class="panel">
<h2 class="panel__title">Ready-made button</h2>
<!-- The ready-made <xpv-request-quote>. It renders nothing when quotes are not enabled for the product. -->
<xpv-request-quote .controller="quoteController" />
</section>
<section class="panel">
<h2 class="panel__title">Custom button</h2>
<!-- A custom button and dialog, built with useRequestQuote(). -->
<QuoteButton :controller="quoteController" />
</section>
</template>
import { useRequestQuote, type ProductConfigurator } from '@expivi/sdk';
import { useExpiviController } from '../hooks/useExpiviController';
import QuoteButton from './QuoteButton';
/** Rendered once the product is READY. */
export default function QuotePanels({ configurator }: { configurator: ProductConfigurator }) {
const quoteController = useExpiviController(() => useRequestQuote(configurator), [configurator]);
if (!quoteController) return null;
return (
<>
<section className="panel">
<h2 className="panel__title">Ready-made button</h2>
{/* The ready-made <xpv-request-quote>. It renders nothing when quotes are not enabled for the product. */}
<xpv-request-quote controller={quoteController} />
</section>
<section className="panel">
<h2 className="panel__title">Custom button</h2>
{/* A custom button and dialog, built with useRequestQuote(). */}
<QuoteButton controller={quoteController} />
</section>
</>
);
}
3. Build your own button and dialog
The ready-made button has fixed English texts and its own look. To match your site, build the button and dialog yourself and let <xpv-form-renderer> render the form:
- Show the button only when
isVisibleistrue. - In the dialog, render
<xpv-form-renderer>with theformIdand theconfigurator. WhensendEmailistrue, add an email field with the keyREQUEST_QUOTE_EMAIL_FIELD_KEYthroughextraFields. - When the shopper sends the form, call the form renderer's
submit()method. It validates the form, shows the errors and returnsfalsewhen the form is invalid. - Get the values with the form renderer's
getValue()method and pass them to the controller'ssubmit().
- Vanilla JS
- Vue
- React
import { REQUEST_QUOTE_EMAIL_FIELD_KEY } from '@expivi/sdk';
import { createExpiviElement } from '../shared/configurator.js';
/**
* A custom "Request a quote" button and dialog. The dialog shows the quote form configured in
* Expivi (rendered by <xpv-form-renderer>) and submits it with the current configuration.
* Requires the form-renderer web components to be registered.
*
* @param {HTMLElement} container
* @param {import('@expivi/sdk').RequestQuoteController} quoteController from useRequestQuote(configurator)
* @returns {() => void} removes the button
*/
export function mountQuoteButton(container, quoteController) {
// isVisible is false when no quote request is set up for this product in Expivi.
if (!quoteController.isVisible) {
container.innerHTML = '<p class="panel__note">Quote requests are not enabled for this product.</p>';
return () => {};
}
container.innerHTML = `
<button type="button" class="button" data-open>Request a quote</button>
<p class="message" role="status" hidden></p>
<dialog class="quote-dialog">
<div class="quote-dialog__body">
<h2 class="quote-dialog__title">Request a quote</h2>
<div data-form></div>
<div class="quote-dialog__actions">
<button type="button" class="button button--secondary" data-cancel>Cancel</button>
<button type="button" class="button" data-submit>Send request</button>
</div>
</div>
</dialog>`;
const openButton = container.querySelector('[data-open]');
const submitButton = container.querySelector('[data-submit]');
const dialog = container.querySelector('dialog');
const formSlot = container.querySelector('[data-form]');
const message = container.querySelector('.message');
let formRenderer = null;
openButton.addEventListener('click', () => {
// Render the form configured in Expivi. When Expivi emails the shopper, ask for the email address.
formRenderer = createExpiviElement('xpv-form-renderer', {
formId: quoteController.formId,
configurator: quoteController.configurator,
extraFields: quoteController.sendEmail
? [{ type: 'email', fieldKey: REQUEST_QUOTE_EMAIL_FIELD_KEY, label: 'Email', required: true }]
: undefined,
});
formSlot.replaceChildren(formRenderer);
showMessage('');
dialog.showModal();
});
container.querySelector('[data-cancel]').addEventListener('click', () => dialog.close());
submitButton.addEventListener('click', async () => {
// submit() validates the form and shows the errors; it returns false when the form is invalid.
if (!(await formRenderer.submit())) return;
const { values } = await formRenderer.getValue();
try {
await quoteController.submit(values);
dialog.close();
showMessage('Thank you! Your quote request has been sent.');
} catch (error) {
console.error(error);
showMessage('Your quote request could not be sent. Please try again.', true);
dialog.close();
}
});
const unsubscribeBusy = quoteController.subscribeBusy((isBusy) => {
submitButton.disabled = isBusy;
submitButton.textContent = isBusy ? 'Sending…' : 'Send request';
});
function showMessage(text, isError = false) {
message.textContent = text;
message.hidden = !text;
message.className = `message ${isError ? 'message--error' : 'message--success'}`;
}
return () => {
unsubscribeBusy();
container.replaceChildren();
};
}
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue';
import { REQUEST_QUOTE_EMAIL_FIELD_KEY, type RequestQuoteController } from '@expivi/sdk';
/**
* A custom "Request a quote" button and dialog. The dialog shows the quote form configured in
* Expivi (rendered by <xpv-form-renderer>) and submits it with the current configuration.
* Requires the form-renderer web components to be registered.
*/
const props = defineProps<{ controller: RequestQuoteController }>();
interface FormRendererElement extends HTMLElement {
submit(): Promise<boolean>;
getValue(): Promise<{ values: Record<string, unknown> }>;
}
const dialog = ref<HTMLDialogElement>();
const formRenderer = ref<FormRendererElement>();
const isFormOpen = ref(false);
const isBusy = ref(props.controller.isBusy);
const message = ref<{ text: string; isError: boolean } | null>(null);
// When Expivi emails the shopper, ask for the email address.
const extraFields = props.controller.sendEmail
? [{ type: 'email', fieldKey: REQUEST_QUOTE_EMAIL_FIELD_KEY, label: 'Email', required: true }]
: undefined;
const unsubscribeBusy = props.controller.subscribeBusy((busy) => (isBusy.value = busy));
onBeforeUnmount(unsubscribeBusy);
function openForm() {
message.value = null;
isFormOpen.value = true; // renders a fresh, empty form
dialog.value?.showModal();
}
function closeForm() {
dialog.value?.close();
isFormOpen.value = false;
}
async function sendRequest() {
const form = formRenderer.value;
// submit() validates the form and shows the errors; it returns false when the form is invalid.
if (!form || !(await form.submit())) return;
const { values } = await form.getValue();
try {
await props.controller.submit(values);
message.value = { text: 'Thank you! Your quote request has been sent.', isError: false };
} catch (error) {
console.error(error);
message.value = { text: 'Your quote request could not be sent. Please try again.', isError: true };
}
closeForm();
}
</script>
<template>
<!-- isVisible is false when no quote request is set up for this product in Expivi. -->
<p v-if="!controller.isVisible" class="panel__note">Quote requests are not enabled for this product.</p>
<template v-else>
<button type="button" class="button" @click="openForm">Request a quote</button>
<p v-if="message" :class="['message', message.isError ? 'message--error' : 'message--success']" role="status">
{{ message.text }}
</p>
<dialog ref="dialog" class="quote-dialog" @close="isFormOpen = false">
<div class="quote-dialog__body">
<h2 class="quote-dialog__title">Request a quote</h2>
<xpv-form-renderer
v-if="isFormOpen"
ref="formRenderer"
.formId="controller.formId"
.configurator="controller.configurator"
.extraFields="extraFields"
/>
<div class="quote-dialog__actions">
<button type="button" class="button button--secondary" @click="closeForm">Cancel</button>
<button type="button" class="button" :disabled="isBusy" @click="sendRequest">
{{ isBusy ? 'Sending…' : 'Send request' }}
</button>
</div>
</div>
</dialog>
</template>
</template>
import { useEffect, useRef, useState } from 'react';
import { REQUEST_QUOTE_EMAIL_FIELD_KEY, type RequestQuoteController } from '@expivi/sdk';
interface FormRendererElement extends HTMLElement {
submit(): Promise<boolean>;
getValue(): Promise<{ values: Record<string, unknown> }>;
}
type Message = { text: string; isError: boolean };
/**
* A custom "Request a quote" button and dialog. The dialog shows the quote form configured in
* Expivi (rendered by <xpv-form-renderer>) and submits it with the current configuration.
* Requires the form-renderer web components to be registered.
*/
export default function QuoteButton({ controller }: { controller: RequestQuoteController }) {
const dialogRef = useRef<HTMLDialogElement>(null);
const formRendererRef = useRef<FormRendererElement>(null);
const [isFormOpen, setIsFormOpen] = useState(false);
const [isBusy, setIsBusy] = useState(controller.isBusy);
const [message, setMessage] = useState<Message | null>(null);
useEffect(() => controller.subscribeBusy(setIsBusy), [controller]);
// isVisible is false when no quote request is set up for this product in Expivi.
if (!controller.isVisible) {
return <p className="panel__note">Quote requests are not enabled for this product.</p>;
}
// When Expivi emails the shopper, ask for the email address.
const extraFields = controller.sendEmail
? [{ type: 'email', fieldKey: REQUEST_QUOTE_EMAIL_FIELD_KEY, label: 'Email', required: true }]
: undefined;
function openForm() {
setMessage(null);
setIsFormOpen(true); // renders a fresh, empty form
dialogRef.current?.showModal();
}
function closeForm() {
dialogRef.current?.close();
setIsFormOpen(false);
}
async function sendRequest() {
const form = formRendererRef.current;
// submit() validates the form and shows the errors; it returns false when the form is invalid.
if (!form || !(await form.submit())) return;
const { values } = await form.getValue();
try {
await controller.submit(values);
setMessage({ text: 'Thank you! Your quote request has been sent.', isError: false });
} catch (error) {
console.error(error);
setMessage({ text: 'Your quote request could not be sent. Please try again.', isError: true });
}
closeForm();
}
return (
<>
<button type="button" className="button" onClick={openForm}>
Request a quote
</button>
{message && (
<p className={`message ${message.isError ? 'message--error' : 'message--success'}`} role="status">
{message.text}
</p>
)}
<dialog ref={dialogRef} className="quote-dialog" onClose={() => setIsFormOpen(false)}>
<div className="quote-dialog__body">
<h2 className="quote-dialog__title">Request a quote</h2>
{isFormOpen && (
<xpv-form-renderer
ref={formRendererRef}
formId={controller.formId}
configurator={controller.configurator}
extraFields={extraFields}
/>
)}
<div className="quote-dialog__actions">
<button type="button" className="button button--secondary" onClick={closeForm}>
Cancel
</button>
<button type="button" className="button" disabled={isBusy} onClick={sendRequest}>
{isBusy ? 'Sending…' : 'Send request'}
</button>
</div>
</div>
</dialog>
</>
);
}
Result
The page shows the ready-made button and your own. Both open the quote form set up in Expivi. Sending it with empty required fields shows the validation errors; sending a valid form creates the quote request in Expivi.
Sending the form creates a real quote request in Expivi, and an email to the shopper when that is set up. Test with an address you own.
See also
useRequestQuotereference- Save and restore configurations, for the links in quote emails