Content
This page covers the most common tasks in custom code: working with components and controls and other configuration tasks.
All functionality is provided by the Custom Code SDK (@combeenation/custom-code-sdk), which is pre-installed in the starter project. Everything can be imported directly from the package or via the CbnSdk barrel object.
Components and controls are accessed via the objects from the generated definitions file src/typings/cfgr-defs.generated.ts (see Link and sync the configurator).
Components
Components hold the values of your configurator. In custom code you can read them, write new input values and listen for changes:
import { MyComponent } from './typings/cfgr-defs.generated';
// Read the current value
const value = await MyComponent.getValue();
// Write a new input value
await MyComponent.setInput('myNewValue');
// Listen for value changes
const { unsubscribe } = await MyComponent.onValueChanged(newValue => {
console.log('value changed', newValue);
});
// Remove the listener again
unsubscribe();
To react to value changes of any component, use onAnyCmpValueChanged from the SDK.
Controls
Controls are the UI elements of your configurator. They are accessed via the generated definitions file as well:
import { MyButton } from './typings/cfgr-defs.generated';
MyButton.onClick(() => {
console.log('button clicked');
});
Every control type provides its own set of functions, e.g. onClick for buttons, setChecked for checkboxes or setText for text controls. The available functions depend on the control type and are fully typed via the generated definitions.
Besides interacting with existing controls, the SDK also provides add*Control functions (e.g. addButtonControl, addPanelControl, addTextControl) to add controls dynamically at runtime.
Custom control
The custom control allows you to render arbitrary HTML content inside your configurator and control it from custom code. This is the way to go whenever you need UI elements which aren't covered by the built-in controls, e.g. a date time picker, an embedded map or any other custom widget.
The control provides two main mechanisms:
-
renderFn: Gives custom code full control over what is rendered inside the control. When set, custom code is responsible for rendering the content of the control's element and the configurator won't render anything itself.noteFor the
renderFnto work, the property Custom code controlled has to be enabled on the control in the configurator editor. TherenderFnwill be ignored otherwise. -
onRendered: A classic event listener which is called after the control has been rendered. Use it to install event listeners on DOM nodes, add CSS classes etc. MultipleonRenderedcallbacks can be registered and they can be used side by side with arenderFn.
import { MyCustomCtrl } from './typings/cfgr-defs.generated';
// Take full control over the rendered content
MyCustomCtrl.renderFn = element => {
element.innerHTML = '<div class="my-widget">Hello from custom code!</div>';
};
// Perform actions after rendering, e.g. install event listeners
MyCustomCtrl.onRendered(element => {
element.querySelector('.my-widget')?.addEventListener('click', () => {
console.log('widget clicked');
});
});
Always use the renderFn instead of manually manipulating the DOM via vanilla JavaScript. Changes applied outside of the renderFn can be overridden by the configurator at any time, while the renderFn ensures that your content is applied in a stable and predictable way.
The renderFn holds the rendering logic of the control, but setting it does not trigger a render. To (re-)render the control, call the render method, which forces a re-render and thereby executes the installed renderFn. The render method also accepts an optional renderFn parameter, which allows setting the render function and triggering a render in one call. The given renderFn will be permanently installed and will override any previously set one.
Finishing a configuration
A finish runs all finish actions of the configurator (e.g. checkout, quote or PDF creation) and can be triggered from custom code with finishConfiguration:
import { finishConfiguration } from '@combeenation/custom-code-sdk';
const result = await finishConfiguration({
input: 'MyFinishAction',
sendDataToParentPage: false
});
The returned FinishResultData contains the results of all finish actions, keyed by finish action type. If the finish failed, the result contains the according error information.
When the configurator is embedded and sendDataToParentPage is set to true, the resulting data is passed to the function window.Combeenation.onConfigurationFinished(data) on the parent page. In this case the option transformParentPageData is required, which selects the checkout result from the finish result and defines the data which is sent to the parent page:
import { finishConfiguration, FinishActionResponseTypes } from '@combeenation/custom-code-sdk';
import type { CheckoutFinishActionResponse, FinishResultData, ParentPageCheckoutData } from '@combeenation/custom-code-sdk';
const result = await finishConfiguration({
input: 'MyFinishAction',
sendDataToParentPage: true,
transformParentPageData: (finishResult: FinishResultData): ParentPageCheckoutData => {
// Select the checkout result from the finish action results
const checkout = Object.values(finishResult.actionResults ?? {}).find(
(r): r is CheckoutFinishActionResponse => r.type === FinishActionResponseTypes.Checkout
);
if (!checkout) {
throw new Error('No checkout finish action result');
}
return {
id: checkout.cfgnId,
authentication: checkout.authToken,
checkoutParameters: checkout.checkoutParameters ?? '',
checkoutParametersHash: checkout.checkoutParametersHash ?? '',
// Additional, JSON-serializable data can be added as well
queryParameters: Object.fromEntries(new URLSearchParams(window.location.search))
};
}
});
The SDK can't know which of the entries in finishResult.actionResults is the actual checkout result, so it has to be selected manually. Don't change checkoutParameters, since checkoutParametersHash is built from it on the server and wouldn't match anymore. Besides the checkout data, you may add any additional JSON-serializable data to the returned object, which is passed to the parent page along with it.
See the configuration finish documentation for more details about finish actions in general.
Restart & share
The SDK also provides functions for common configuration tasks:
import { restartConfiguration, shareConfiguration } from '@combeenation/custom-code-sdk';
// Reset the configurator to a new configuration
await restartConfiguration();
// Create a share link for the current configuration
const shareResult = await shareConfiguration();
Cfgn files
Files that are uploaded into a configuration are called configuration files or cfgn files for short. They are permanently linked to the current configuration and can be accessed in Hive and viewed in the Configuration Insights.
Custom code allows you to upload programmatically created files like screenshots from a 2D or 3D preview, datasheets or similar:
import { uploadFiles } from '@combeenation/custom-code-sdk';
const uploadResult = await uploadFiles({
fileText: {
file: new File(['Lorem ipsum'], 'dummy.txt')
}
});
if (uploadResult.fileText.success) {
console.log(uploadResult.fileText.url);
}
The key of each entry (e.g. fileText) is the name under which the file can be retrieved in Hive via configuration.getFile("fileText"). Use uploadImages for image files, which are then accessible via configuration.getImage(...).
Cfgn files have an upper limit per configuration. If files are only needed temporarily during a configuration, use uploadTempFiles and uploadTempImages instead, which allow up to 10x of the regular cfgn file limit within a single configuration session.
See File upload & handling for the full documentation, including how to upload files with Signals & Slots and how to access them in Hive.
PDF creation
Besides the PDF finish action, which creates a PDF as part of a configuration finish, the SDK also allows creating PDFs directly from custom code at any time during a configuration. This is useful whenever you need a PDF before or independently of a finish, e.g. to show a live preview of a datasheet or quote document, to let users download the current state of their configuration, or to attach a PDF to an integration call.
The suggested way of creating a PDF is based on a PDF asset. You configure the PDF in the asset editor and pass flexible context data to the creation method:
import { createPdfFromAssets } from '@combeenation/custom-code-sdk';
const resultUrl = await createPdfFromAssets(
'MyBundle',
[
{
type: 'PdfAsset',
assetPath: 'quotePdfAsset',
context: {
subject: 'MySubject'
}
}
],
'QuotePdf',
`Your_quote_${new Date().toISOString()}`
);
The created PDF is stored as a cfgn file of the current configuration (see Cfgn files) and the returned URL points to that file.
Multiple asset tasks are merged in the given order, so you can e.g. combine a cover page and the actual quote document into one PDF. Use createTempPdfFromAssets if the PDF doesn't need to be persisted and isn't relevant for the finished configuration.
Parent page communication
When a configurator is embedded into a website via an iframe, the SDK provides functions to communicate with the surrounding parent page:
import {
configuratorIsInIFrame,
sendCustomMsgToParentPage,
onParentPageEvent,
setConfiguratorIFrameSize
} from '@combeenation/custom-code-sdk';
if (configuratorIsInIFrame()) {
// Send a custom message to the parent page
sendCustomMsgToParentPage('myCustomMessage', { foo: 'bar' });
// React to messages from the parent page
onParentPageEvent('parentPageMessage', data => {
console.log('message from parent page', data);
});
// Adjust the size of the configurator iframe
setConfiguratorIFrameSize(800, 600);
}
Additionally, getParentPageUrl returns the URL of the parent page and redirectParentPage allows redirecting it.
Analytics events
Custom code can send live analytics events to external services like Google Tag Manager:
import { fireAnalyticsEvent } from '@combeenation/custom-code-sdk';
fireAnalyticsEvent('MyAnalyticsEvent', { someData: 'someValue' });
See Analytics for more details about analytics in general.
Integrations
Configured integrations can be invoked from custom code with executeIntegration. All API calls are proxied through the Combeenation servers, so no credentials are exposed on the client side:
import { executeIntegration } from '@combeenation/custom-code-sdk';
const response = await executeIntegration({
integrationName: 'CRM',
httpMethod: 'GET',
url: 'https://www.mycrmendpoint.com/api/v1/getAllCustomerData'
});
if (!response.ok) {
console.error('CRM request failed');
}