### Initialize Formio Project Source: https://github.com/formio/formio.js/blob/main/app/builder.md Standard commands to clone the repository and start the server. ```bash git clone https://github.com/formio/formio.git cd formio npm install node server ``` -------------------------------- ### Install Form.io SDK Source: https://github.com/formio/formio.js/blob/main/README.md Use npm to add the Form.io library to your project dependencies. ```bash npm install --save @formio/js ``` -------------------------------- ### Constructor and Timezone Setup Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/widgets/CalendarWidget.js.html Initializes component settings and prepares the URL for loading timezone data. ```javascript constructor(settings, component, instance, index) { super(settings, component, instance, index); // Change the format to map to the settings. if (this.settings.noCalendar) { this.settings.format = this.settings.format.replace(/yyyy-MM-dd /g, ''); } if (!this.settings.enableTime) { this.settings.format = this.settings.format.replace(/ hh:mm a$/g, ''); } else if (this.settings.time_24hr) { this.settings.format = this.settings.format.replace(/hh:mm a$/g, 'HH:mm'); } this.zoneLoading = false; this.timezonesUrl = `${Formio.cdn['moment-timezone']}/data/packed/latest.json`; } ``` -------------------------------- ### Get Form Initialization Options Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Form.js.html Determines base and project options based on the form URL and path. ```javascript getFormInitOptions(url, form) { const options = {}; const index = url.indexOf(form?.path); // form url doesn't include form path Iif (index === -1) { return options; } const projectUrl = url.substring(0, index - 1); const urlParts = Formio.getUrlParts(projectUrl); // project url doesn't include subdirectories path Iif (!urlParts || urlParts.filter(part => !!part).length < 4) { return options; } const baseUrl = `${urlParts[1]}${urlParts[2]}`; // Skip if baseUrl has already been set if (baseUrl !== Formio.baseUrl) { return { base: baseUrl, project: projectUrl, }; } return {}; } ``` -------------------------------- ### Setup Formio HTML Container Source: https://github.com/formio/formio.js/wiki/Override-Delimiter-and-Decimal-Separator Include the required Formio CSS and JS libraries and define the target container element. ```html
``` -------------------------------- ### Initialize Formio Renderer Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Embed.js.html Handles the setup of the wrapper element, shadow DOM configuration, and asynchronous loading of required scripts and styles. ```javascript const id = Formio.config.id || `formio-${Math.random().toString(36).substring(7)}`; // Create a new wrapper and add the element inside of a new wrapper. let wrapper = Formio.createElement('div', { 'id': `${id}-wrapper` }); element.parentNode.insertBefore(wrapper, element); // If we include the libraries, then we will attempt to run this in shadow dom. const useShadowDom = Formio.config.includeLibs && !Formio.config.noshadow && (typeof wrapper.attachShadow === 'function'); Iif (useShadowDom) { wrapper = wrapper.attachShadow({ mode: 'open' }); options.shadowRoot = wrapper; } element.parentNode.removeChild(element); wrapper.appendChild(element); // If this is inside of shadow dom, then we need to add the styles and scripts to the shadow dom. const libWrapper = useShadowDom ? wrapper : document.body; // Load the renderer styles. await Formio.addStyles(libWrapper, Formio.config.embedCSS || `${Formio.cdn.js}/formio.embed.css`); // Add a loader. Formio.addLoader(wrapper); const formioSrc = Formio.config.full ? 'formio.full' : 'formio.form'; const renderer = Formio.config.debug ? formioSrc : `${formioSrc}.min`; Formio.FormioClass = await Formio.addScript( libWrapper, Formio.formioScript(Formio.config.script || `${Formio.cdn.js}/${renderer}.js`, builder), 'Formio', builder ? 'isBuilder' : 'isRenderer' ); Formio.FormioClass.cdn = Formio.cdn; Formio.FormioClass.setBaseUrl(options.baseUrl || Formio.baseUrl || Formio.config.base); Formio.FormioClass.setProjectUrl(options.projectUrl || Formio.projectUrl || Formio.config.project); Formio.FormioClass.language = Formio.language; Formio.setLicense(Formio.license || Formio.config.license || false); Formio.modules.forEach((module) => { Formio.FormioClass.use(module); }); Iif (Formio.icons) { Formio.FormioClass.icons = Formio.icons; } Iif (Formio.pathType) { Formio.FormioClass.setPathType(Formio.pathType); } // Add libraries if they wish to include the libs. Iif (Formio.config.template && Formio.config.includeLibs) { await Formio.addLibrary( libWrapper, Formio.config.libs[Formio.config.template], Formio.config.template ); } Iif (!Formio.config.libraries) { Formio.config.libraries = Formio.config.modules || {}; } // Adding premium if it is provided via the config. Iif (Formio.config.premium) { Formio.config.libraries.premium = Formio.config.premium; } // Allow adding dynamic modules. Iif (Formio.config.libraries) { for (const name in Formio.config.libraries) { const lib = Formio.config.libraries[name]; lib.use = lib.use || true; await Formio.addLibrary(libWrapper, lib, name); } } await Formio.addStyles(libWrapper, Formio.formioScript(Formio.config.style || `${Formio.cdn.js}/${renderer}.css`, builder)); Iif (Formio.config.before) { await Formio.config.before(Formio.FormioClass, element, Formio.config); } Formio.FormioClass.license = true; Formio._formioReady(Formio.FormioClass); return wrapper; } ``` -------------------------------- ### Install formio.js via npm Source: https://github.com/formio/formio.js/wiki/Home Use this command to add the formio.js library to your project's dependencies. ```bash npm install --save formiojs ``` -------------------------------- ### Get Multipart Upload Options Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/file/File.js.html Returns configuration for multipart uploads, including progress and message callbacks. ```javascript getMultipartOptions(fileToSync) { let count = 0; return this.component.useMultipartUpload && this.component.multipart ? { ...this.component.multipart, progressCallback: (total) => { count++; fileToSync.status = 'progress'; fileToSync.progress = parseInt(100 * count / total); delete fileToSync.message; this.redraw(); }, changeMessage: (message) => { fileToSync.message = message; this.redraw(); }, } : false; } ``` -------------------------------- ### Generate a GUID Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/utils/utils.js.html Creates a RFC4122 version 4 compliant GUID string. ```javascript export function guid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random()*16|0; const v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } ``` -------------------------------- ### Basic Wizard Initialization Source: https://github.com/formio/formio.js/blob/main/app/examples/wizard.md Include necessary CSS and JS files, then use Formio.createForm to render a wizard. Event listeners for 'nextPage' and 'submit' are demonstrated. ```html
``` ```javascript Formio.createForm(document.getElementById('wizard'), 'https://examples.form.io/wizard') .then(function(wizard) { wizard.on('nextPage', function(page) { console.log(page); }); wizard.on('submit', function(submission) { console.log(submission); }); }); ``` -------------------------------- ### GUID Generation Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/utils/utils.js.html Generates a universally unique identifier (GUID) using a standard algorithm. ```APIDOC ## GUID Generation ### Description Generates a universally unique identifier (GUID). ### Returns - **string**: A GUID. ### Example ```javascript guid(); // Returns a string like '123e4567-e89b-12d3-a456-426614174000' ``` ``` -------------------------------- ### Generate Unique Filename Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/utils/utils.js.html Creates a unique filename by incorporating a GUID into a provided template. If no template is given, it defaults to '{{fileName}}-{{guid}}'. The function ensures a GUID is always included to prevent overwrites. It splits the original name to isolate the base filename. ```javascript export function uniqueName(name, template, evalContext) { template = template || '{{fileName}}-{{guid}}'; //include guid in template anyway, to prevent overwriting issue if filename matches existing file Iif (!template.includes('{{guid}}')) { template = `${template}-{{guid}}`; } const parts = name.split('.'); let fileName = parts.slice(0, parts.length - 1).join('.'); ``` -------------------------------- ### Initialize Form Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Webform.js.html Sets up the form instance, including submission data, component destruction, and event listeners. ```javascript init() { if (this.options.submission) { const submission = \_.extend({}, this.options.submission); this.\_submission = submission; this.\_data = submission.data; } else { this.\_submission = this.\_submission || { data: {} }; } // Remove any existing components. if (this.components && this.components.length) { this.destroyComponents(); this.components = []; } if (this.component) { this.component.components = this.form ? this.form.components : []; } else E{ this.component = this.form; } this.component.type = "form"; this.component.input = false; this.addComponents(); this.on( "submitButton", (options) => { this.submit(false, options).catch((e) => { if (options?.instance) { options.instance.loading = false; } ``` -------------------------------- ### Initialization and Addon Management Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Handles component initialization and the dynamic creation of addons. ```javascript init() { this.disabled = this.shouldDisabled; this._visible = this.conditionallyVisible(null, null); Iif (this.component.addons?.length) { this.component.addons.forEach((addon) => this.createAddon(addon)); } } afterComponentAssign() { //implement in extended classes } createAddon(addonConfiguration) { const name = addonConfiguration.name; Iif (!name) { return; } const settings = addonConfiguration.settings?.data || {}; const Addon = Addons[name.value]; let addon = null; Iif (Addon) { const supportedComponents = Addon.info.supportedComponents; const supportsThisComponentType = !supportedComponents?.length || supportedComponents.indexOf(this.component.type) !== -1; if (supportsThisComponentType) { addon = new Addon(settings, this); this.addons.push(addon); } else { console.warn(`Addon ${name.label} does not support component of type ${this.component.type}.`); } } return addon; } ``` -------------------------------- ### Get Subform Data Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/form/Form.js.html Retrieves the submission data for the subform. If the subform display is 'pdf', it gets the submission from the subform; otherwise, it resolves with the current data value. ```javascript getSubFormData() { Iif (​_.get(this.subForm, 'form.display') === 'pdf') { return this.subForm.getSubmission(); } else { return Promise.resolve(this.dataValue); } } ``` -------------------------------- ### Configure File Name Template Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/file/editForm/File.edit.file.js.html Defines a template for naming uploaded files. Supports standard template variables and includes 'fileName' and 'guid'. The 'guid' is appended if not present. ```javascript { type: 'textfield', input: true, key: 'fileNameTemplate', label: 'File Name Template', placeholder: '(optional) { {name} }-{ {guid} }', tooltip: 'Specify template for name of uploaded file(s). Regular template variables are available (\`data\`, \`component\`, \`user\`, \`value\`, \`moment\` etc.), also \`fileName\`, \`guid\` variables are available. \`guid\` part must be present, if not found in template, will be added at the end.', weight: 25 } ``` -------------------------------- ### Formio Plugin Usage Syntax Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/formio.form.js.html Demonstrates the usage of Formio.use to register plugins. ```javascript Formio.use = useModule(); export { Formio as FormioCore } from './Formio'; // Export the components. export { Components, Displays, Providers, Widgets, Templates, Utils, Form, Formio, Licenses, EventEmitter, Webform }; ``` -------------------------------- ### Get Wizard Schema Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/WizardBuilder.js.html Generates and returns the schema for the wizard. It assigns the current page's components to the webform and then creates a new Webform instance to get the final schema. ```javascript get schema() { _.assign(this.currentPage, this.webform._form.components[0]); const webform = new Webform(this.options); webform.setForm(this._form, { noEmit: true }); return webform.schema; } ``` -------------------------------- ### Initialize Formio Core and CDN Settings Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Formio.js.html Sets up the Formio core SDK, embeds, CDN, and providers. Configures the default CDN based on the Formio version. ```javascript import { Formio as FormioCore } from '@formio/core/sdk'; import { Formio as FormioEmbed } from './Embed'; import CDN from './CDN'; import Providers from './providers'; FormioCore.cdn = new CDN(); FormioCore.Providers = Providers; FormioCore.version = 'FORMIO_VERSION'; CDN.defaultCDN = FormioCore.version.includes('rc') ? 'https://cdn.test-form.io' : 'https://cdn.form.io'; ``` -------------------------------- ### Create Enclosed State with Get and Toggle Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/utils/utils.js.html The `withSwitch` function creates an enclosed state and returns two functions: `get` to retrieve the current state and `toggle` to switch between two predefined states. ```javascript export function withSwitch(a, b) { let state = a; let next = b; function get() { return state; } function toggle() { const prev = state; state = next; next = prev; } return [get, toggle]; } ``` -------------------------------- ### Initialize Formio and Load Modules Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/formio.form.js.html Sets up core Formio dependencies and provides a method for loading external modules. ```javascript import _ from 'lodash'; import { Formio } from './Formio'; import AllComponents from './components'; import Components from './components/Components'; import Displays from './displays/Displays'; import Templates from './templates/Templates'; import Providers from './providers'; import Widgets from './widgets'; import Form from './Form'; import Utils from './utils'; import { Evaluator } from './utils/Evaluator'; import Licenses from './licenses'; import EventEmitter from './EventEmitter'; import Webform from './Webform'; Formio.loadModules = (path = `${Formio.getApiUrl() }/externalModules.js`, name = 'externalModules') => { Formio.requireLibrary(name, name, path, true) .then((modules) => { Formio.use(modules); }); }; // This is needed to maintain correct imports using the "dist" file. Formio.isRenderer = true; Formio.Components = Components; Formio.Templates = Templates; Formio.Utils = Utils; Formio.Form = Form; Formio.Displays = Displays; Formio.Providers = Providers; Formio.Widgets = Widgets; Formio.Evaluator = Evaluator; Formio.AllComponents = AllComponents; Formio.Licenses = Licenses; // This is strange, but is needed for "premium" components to import correctly. Formio.Formio = Formio; Formio.Components.setComponents(AllComponents); ``` -------------------------------- ### Data Grid 'components' Property Example Source: https://github.com/formio/formio.js/wiki/Data-Grid-Component An example of the 'components' property for the Data Grid component, which defines the schema for each row. This property is required for configuring the structure of rows within the Data Grid. ```json [] ``` -------------------------------- ### Get icon template Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Renders an icon template with specified properties. ```javascript getIcon(name, content, styles, ref = 'icon') { return this.renderTemplate('icon', { className: this.iconClass(name), ref, styles, content }); } ``` -------------------------------- ### Create Form Builder with Initial Form and Options Source: https://context7.com/formio/formio.js/llms.txt Initialize the Formio.builder with an existing form schema and configuration options. This example demonstrates how to set initial form data, configure builder options like `noDefaultSubmitButton`, and customize component edit forms. ```javascript Formio.builder(document.getElementById('builder'), { display: 'form', components: [ { type: 'textfield', key: 'existingField', label: 'Existing Field', input: true } ] }, { noDefaultSubmitButton: false, alwaysConfirmComponentRemoval: true, editForm: { textfield: [ { key: 'display', components: [ { key: 'placeholder', ignore: true } // Hide placeholder option ] } ] } }).then(function(builder) { // Save the form schema document.getElementById('saveBtn').addEventListener('click', function() { const formJson = builder.schema; console.log('Saving form:', formJson); // Send formJson to your backend }); }); ``` -------------------------------- ### Get Error Label Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Retrieves the translated error label for the component. ```javascript get errorLabel() { return this.t(this.component.errorLabel || this.component.label ``` -------------------------------- ### Get Component Name Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Returns the translated label or key for the component. ```javascript get name() { return this.t(this.component.label || this.component.placeholder || this.key, { _userInput: true }); } ``` -------------------------------- ### Initialize Camera and Canvas Polyfill Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/file/File.js.html Sets up the camera reference and provides a polyfill for HTMLCanvasElement.toBlob if it is missing in the current environment. ```javascript let Camera; let webViewCamera = 'undefined' !== typeof window ? navigator.camera : Camera; // canvas.toBlob polyfill. let htmlCanvasElement; if (typeof window !== 'undefined') { htmlCanvasElement = window.HTMLCanvasElement; } else IEif (typeof global !== 'undefined') { htmlCanvasElement = global.HTMLCanvasElement; } Iif (htmlCanvasElement && !htmlCanvasElement.prototype.toBlob) { Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', { value: function(callback, type, quality) { var canvas = this; setTimeout(function() { ``` -------------------------------- ### Get Component Element Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Returns the DOM element wrapping the component. ```javascript getElement() { return this.element; } ``` -------------------------------- ### Initialize and Submit a Webform Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Webform.js.html Demonstrates how to instantiate a Webform, set its source, provide initial data, and trigger the submission process. ```javascript let form = new Webform(document.getElementById('formio')); form.src = 'https://examples.form.io/example'; form.submission = {data: { firstName: 'Joe', lastName: 'Smith', email: 'joe@example.com' }}; form.submit().then((submission) => { console.log(submission); }); ``` -------------------------------- ### Get Current Form Instance Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/form/Form.js.html Accessor for the current form instance. ```javascript get currentForm() { return this._currentForm; } ``` -------------------------------- ### Initialize Formio Library and CDN Configuration Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Embed.js.html Configures the CDN provider and defines the library registry, including dependencies and global style overrides for shadow DOM support. ```javascript static async init(element, options = {}, builder = false) { Formio.cdn = new CDN(Formio.config.cdn, Formio.config.cdnUrls || {}); Formio.config.libs = Formio.config.libs || { uswds: { dependencies: ['fontawesome'], js: `${Formio.cdn.uswds}/uswds.min.js`, css: `${Formio.cdn.uswds}/uswds.min.css`, use: true }, fontawesome: { // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page. css: `https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css`, globalStyle: `@font-face { font-family: 'FontAwesome'; src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?v=4.7.0'); src: url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg'); font-weight: normal; font-style: normal; }` }, bootstrap4: { dependencies: ['fontawesome'], css: `${Formio.cdn.bootstrap4}/css/bootstrap.min.css` }, bootstrap: { dependencies: ['bootstrap-icons'], css: `${Formio.cdn.bootstrap}/css/bootstrap.min.css` }, 'bootstrap-icons': { // Due to an issue with font-face not loading in the shadowdom (https://issues.chromium.org/issues/41085401), we need // to do 2 things. 1.) Load the fonts from the global cdn, and 2.) add the font-face to the global styles on the page. css: 'https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.min.css', globalStyle: `@font-face { font-display: block; font-family: "bootstrap-icons"; src: url("https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff2?dd67030699838ea613ee6dbda90effa6") format("woff2"), url("https://cdn.jsdelivr.net/npm/bootstrap-icons/font/fonts/bootstrap-icons.woff?dd67030699838ea613ee6dbda90effa6") format("woff"); }` } }; // Add all bootswatch templates. ['cerulean', 'cosmo', 'cyborg', 'darkly', 'flatly', 'journal', 'litera', 'lumen', 'lux', 'materia', 'minty', 'pulse', 'sandstone', 'simplex', 'sketchy', 'slate', 'solar', 'spacelab', 'superhero', 'united', 'yeti'].forEach((template) => { Formio.config.libs[template] = { dependencies: ['bootstrap-icons'], css: `${Formio.cdn.bootswatch}/dist/${template}/bootstrap.min.css` }; }); ``` -------------------------------- ### Get Form Schema Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/WebformBuilder.js.html Provides a getter for the webform's schema. ```javascript get schema() { return this.webform.schema; } ``` -------------------------------- ### Get Form Schema Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/WebformBuilder.js.html Provides a getter for the current form schema. ```javascript get form() { return this.webform.form; } ``` -------------------------------- ### Attach Signature Pad Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/signature/Signature.js.html Initializes the signature pad, sets up event listeners, and handles responsive resizing. ```javascript attach(element) { this.loadRefs(element, { canvas: 'single', refresh: 'single', padBody: 'single', signatureImage: 'single' }); const superAttach = super.attach(element); Iif (this.refs.refresh && this.options.readOnly) { this.refs.refresh.classList.add('disabled'); } // Create the signature pad. Iif (this.refs.canvas) { this.signaturePad = new SignaturePad(this.refs.canvas, { minWidth: this.component.minWidth, maxWidth: this.component.maxWidth, penColor: this.component.penColor, backgroundColor: this.component.backgroundColor }); this.signaturePad.addEventListener('endStroke', () => this.setValue(this.signaturePad.toDataURL())); this.refs.signatureImage.setAttribute('src', this.signaturePad.toDataURL()); this.onDisabled(); // Ensure the signature is always the size of its container. Iif (this.refs.padBody) { Iif (!this.refs.padBody.style.maxWidth) { this.refs.padBody.style.maxWidth = '100%'; } Iif (!this.builderMode && !this.options.preview) { this.observer = new ResizeObserver(() => { this.checkSize(); }); this.observer.observe(this.refs.padBody); } this.addEventListener(window, 'resize', _.debounce(() => this.checkSize(), 10)); setTimeout(function checkWidth() { if (this.refs.padBody && this.refs.padBody.offsetWidth) { this.checkSize(); } else { setTimeout(checkWidth.bind(this), 20); } }.bind(this), 20); } } this.addEventListener(this.refs.refresh, 'click', (event) => { event.preventDefault(); this.showCanvas(true); this.signaturePad.clear(); this.setValue(this.defaultValue); }); this.setValue(this.dataValue); return superAttach; } ``` -------------------------------- ### GET /submission Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Webform.js.html Retrieves the current submission object associated with the form. ```APIDOC ## GET /submission ### Description Returns the submission object that was set within this form. ### Method GET ### Response #### Success Response (200) - **submission** (object) - The current submission data. ``` -------------------------------- ### GET /form Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Webform.js.html Retrieves the current form JSON schema object. ```APIDOC ## GET /form ### Description Gets the current form object containing the components schema. ### Method GET ### Response #### Success Response (200) - **components** (array) - The list of form components. ``` -------------------------------- ### Initialize Flatpickr and Plugins Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/widgets/CalendarWidget.js.html Handles the asynchronous loading of Flatpickr and the ShortcutButtonsPlugin, including locale-specific configurations. ```javascript 'shortcut-buttons-flatpickr', 'ShortcutButtonsPlugin', `${Formio.cdn['shortcut-buttons-flatpickr']}/shortcut-buttons-flatpickr.min.js`, true ); } }) .then((ShortcutButtonsPlugin) => { return Formio.requireLibrary('flatpickr', 'flatpickr', `${Formio.cdn['flatpickr']}/flatpickr.min.js`, true) .then((Flatpickr) => { Iif (this.component.shortcutButtons?.length && ShortcutButtonsPlugin) { this.initShortcutButtonsPlugin(ShortcutButtonsPlugin); } this.settings.formatDate = this.getFlatpickrFormatDate(Flatpickr); if (this._input) { const { locale } = this.settings; Iif (locale && locale.length >= 2 && locale !== 'en') { return Formio.requireLibrary( `flatpickr-${locale}`, `flatpickr.l10ns.${locale}`, `${Formio.cdn['flatpickr']}/l10n/${locale}.js`, true).then(() => this.initFlatpickr(Flatpickr)); } else { this.initFlatpickr(Flatpickr); } } }); }) .catch((err) => { console.warn(err); }); } ``` -------------------------------- ### Get Value as String Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/tags/Tags.js.html Formats the component value as a string for display purposes. ```javascript getValueAsString(value) { if (!value) { return ''; } if (Array.isArray(value)) { return value.join(`${this.delimiter || ','} `); } const stringValue = value.toString(); return this.sanitize(stringValue, this.shouldSanitizeValue); } ``` -------------------------------- ### Get Value as String Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/signature/Signature.js.html Converts the signature boolean value to a human-readable string. ```javascript getValueAsString(value) { Iif (_.isUndefined(value) && this.inDataTable) { return ''; } return value ? 'Yes' : 'No'; } ``` -------------------------------- ### Add Library Dependencies Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Embed.js.html Initializes library loading by processing dependencies. ```javascript static async addLibrary(libWrapper, lib, name) { Iif (!lib) { return; } Iif (lib.dependencies) { for (let i = 0; i < lib.dependencies.length; i++) { const libName = lib.dependencies[i]; ``` -------------------------------- ### Initialize Tooltips Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Creates and attaches tooltips using tippy.js, supporting HTML content and custom settings. ```javascript createTooltip(tooltipEl, settings = {}) { const tooltipAttribute = tooltipEl.getAttribute('data-tooltip'); const tooltipDataTitle = tooltipEl.getAttribute('data-title'); const tooltipText = this.interpolate(tooltipDataTitle || tooltipAttribute) .replace(/(?:\r\n|\r|\n)/g, '
'); return tippy(tooltipEl, { allowHTML: true, trigger: 'mouseenter click focus', placement: 'right', zIndex: 10000, interactive: true, ...settings, content: this.t(this.sanitize(tooltipText), { _userInput: true }), }); } ``` ```javascript attachTooltips(toolTipsRefs) { toolTipsRefs?.forEach((tooltip, index) => { if (tooltip) { this.tooltips[index] = this.createTooltip(tooltip); } }); } ``` -------------------------------- ### Component Value Management Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Methods related to setting, getting, and managing component values. ```APIDOC ## Component Value Management ### Description Methods for initializing and managing component values, including setting default or empty values. ### Methods #### `setValue(value, flags)` Sets the component's value. Flags can control event triggering and validation. #### `getValue()` Retrieves the current value of the component. #### `unset()` Clears the component's current value. #### `emptyValue` Property representing the default empty value for the component. #### `defaultValue` Property representing the default value for the component if not otherwise set. ``` -------------------------------- ### Create Form Instance Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Embed.js.html Main entry point for creating a form, handling initialization and submission data injection. ```javascript // Create a new form. static async createForm(element, form, options = {}) { Iif (Formio.FormioClass) { return Formio.FormioClass.createForm(element, form, { ...options, ...{ noLoader: true } }); } const wrapper = await Formio.init(element, options); return Formio.FormioClass.createForm(element, form, { ...options, ...{ noLoader: true } }).then((instance) => { // Set the default submission data. Iif (Formio.config.submission) { Formio.debug('Setting submission', Formio.config.submission); instance.submission = Formio.config.submission; } // Call the after create method. ``` -------------------------------- ### Component Initialization and Rendering Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/day/Day.js.html Methods for initializing component state and rendering the template. ```javascript init() { super.init(); const minYear = this.component.fields.year.minYear; const maxYear = this.component.fields.year.maxYear; this.component.maxYear = maxYear; this.component.minYear = minYear; const dateFormatInfo = getLocaleDateFormatInfo(this.options.language); this.dayFirst = this.component.useLocaleSettings ? dateFormatInfo.dayFirst : this.component.dayFirst; } ``` ```javascript render() { if (this.isHtmlRenderMode()) { return super.render(this.renderTemplate('input')); } return super.render(this.renderTemplate('day', { dayFirst: this.dayFirst, showDay: this.showDay, showMonth: this.showMonth, showYear: this.showYear, day: this.renderField('day'), month: this.renderField('month'), year: this.renderField('year'), })); } ``` ```javascript renderField(name) { if (this.component.fields[name].type === 'select') { return this.renderTemplate('select', { input: this.selectDefinition(name), selectOptions: this[`${name}s`].reduce((html, option) => html + this.renderTemplate('selectOption', { option, selected: false, attrs: {} }), '' ), }); } else { return this.renderTemplate('input', { prefix: this.prefix, suffix: this.suffix, input: this.inputDefinition(name) }); } } ``` -------------------------------- ### Get Size Class Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Resolves the size CSS class based on the current template. ```javascript size(size) { return Templates.current.hasOwnProperty('size') ? Templates.current.size(size) : size; } ``` -------------------------------- ### Get component by path Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/nested/NestedComponent.js.html Performs a deep search to find a component based on its path. ```javascript getComponent(path, fn, originalPath) { originalPath = originalPath || getStringFromComponentPath(path); if (this.componentsMap.hasOwnProperty(originalPath)) { if (fn) { return fn(this.componentsMap[originalPath]); } else { return this.componentsMap[originalPath]; } } path = getArrayFromComponentPath(path); ``` -------------------------------- ### Initialize FormioEmbed with FormioCore Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Formio.js.html This line initializes FormioEmbed using FormioCore, likely to establish the connection or set up initial states. It's a crucial step after FormioCore has been configured. ```javascript FormioEmbed._formioReady(FormioCore); ``` -------------------------------- ### Get Page Index by Key Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Wizard.js.html Finds the index of a page based on its component key. ```javascript getPageIndexByKey(key) { let pageIndex = this.page; this.pages.forEach((page, index) => { if (page.component.key === key) { pageIndex = index; return false; } }); return pageIndex; } ``` -------------------------------- ### Wizard Initialization and Lifecycle Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Wizard.js.html Initialization logic for wizard settings, breadcrumbs, and sub-wizard event handling. ```javascript init() { // Check for and initlize button settings object this.options.buttonSettings = _.defaults(this.options.buttonSettings, { showPrevious: true, showNext: true, showSubmit: true, showCancel: !this.options.readOnly }); this.options.breadcrumbSettings = _.defaults(this.options.breadcrumbSettings, { clickable: true }); this.options.allowPrevious = this.options.allowPrevious || false; this.page = 0; const onReady = super.init(); this.setComponentSchema(); if (this.pages?.[this.page]) { this.component = this.pages[this.page].component; } this.on('subWizardsUpdated', (subForm) => { const subWizard = this.subWizards.find(subWizard => subForm?.id && subWizard.subForm?.id === subForm?.id); if (this.subWizards.length && subWizard) { subWizard.subForm.setValue(subForm._submission, {}, true); this.establishPages(); this.redraw(); } }); return onReady; } ``` -------------------------------- ### Get empty value for NestedDataComponent Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/nesteddata/NestedDataComponent.js.html Defines the empty value for this component, which is an empty object. ```javascript get emptyValue() { return {}; } ``` -------------------------------- ### setForm Method Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Webform.js.html Details on how to set the JSON schema for the form to be rendered, including an example. ```APIDOC ## POST /form ### Description Sets the JSON schema for the form to be rendered. This method can also apply component overrides and properties from the form schema. ### Method `setForm(form, flags = {})` ### Parameters #### Request Body - **form** (object) - The JSON schema of the form. See [Form.io Examples](https://examples.form.io/example) for an example JSON schema. - **flags** (object) - Optional flags to apply when setting the form. Defaults to an empty object. ### Request Example ```javascript import Webform from '@formio/js/Webform'; let form = new Webform(document.getElementById('formio')); form.setForm({ components: [ { type: 'textfield', key: 'firstName', label: 'First Name', placeholder: 'Enter your first name.', input: true }, { type: 'textfield', key: 'lastName', label: 'Last Name', placeholder: 'Enter your last name', input: true }, { type: 'button', action: 'submit', label: 'Submit', theme: 'primary' } ] }); ``` ### Response #### Success Response (200) - **Promise** (Promise) - The promise that is triggered when the form is set. #### Response Example (This method primarily modifies the form's internal state and returns a Promise. A direct JSON response example is not applicable for this method.) ``` -------------------------------- ### Form Initialization and Element Creation Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/Form.js.html Details on how a Formio instance is initialized, including handling of form elements and options, and the creation of DOM elements. ```APIDOC ## Constructor Initializes a new Formio instance with provided element, form options, and form data. ### Method Constructor ### Parameters - **element** (HTMLElement) - Optional - The HTML element to attach the form to. - **formOptions** (object) - Optional - Configuration options for the form. - **form** (object|string) - Optional - The form JSON schema or a URL to the schema. ### Request Body (Not applicable for constructor) ### Response (Not applicable for constructor) ## createElement Creates a new DOM element with specified tag, attributes, and children. ### Method createElement ### Parameters - **tag** (string) - The HTML tag for the element (e.g., 'div', 'span'). - **attrs** (object) - An object containing key-value pairs for element attributes. - **children** (array) - An array of child element definitions to append. ### Request Body (Not applicable) ### Response - **element** (HTMLElement) - The newly created DOM element. ## set loading Manages the display of a loading indicator on the form element. ### Method loading (setter) ### Parameters - **load** (boolean) - Set to true to display the loader, false to hide it. ### Request Body (Not applicable) ### Response (Not applicable) ``` -------------------------------- ### Initialize Providers Class Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/providers/Providers.js.html Imports necessary modules and defines the Providers class with static properties and methods for managing providers. ```javascript import _ from 'lodash'; import address from './address'; import auth from './auth'; import storage from './storage'; /** * @class Providers * @classdesc Represents a collection of providers. */ /** * Represents a collection of providers. */ export default class Providers { static providers = { address, auth, storage, }; /** * Adds a provider to the collection. * @param {string} type - The type of the provider. * @param {string} name - The name of the provider. * @param {Provider} provider - The provider object. */ static addProvider(type, name, provider) { Providers.providers[type] = Providers.providers[type] || {}; Providers.providers[type][name] = provider; } /** * Adds multiple providers to the collection. * @param {string} type - The type of the providers. * @param {{ [key: string]: Provider }} providers - The collection of providers. */ static addProviders(type, providers) { Providers.providers[type] = _.merge(Providers.providers[type], providers); } /** * Retrives a provider a provider from the collection. * @param {string} type - The type of the provider. * @param {string} name - The name of the provider. * @returns {Provider | void} The provider object. */ static getProvider(type, name) { if (Providers.providers[type] && Providers.providers[type][name]) { return Providers.providers[type][name]; } } /** * Retrives all providers of a given type. * @param {string} type - The type of the providers. * @returns {Provider[]} The collection of providers. */ static getProviders(type) { if (Providers.providers[type]) { return Providers.providers[type]; } } } ``` -------------------------------- ### Get View Representation Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Returns the string representation of the component value, respecting protected status. ```javascript getView(value, options) { Iif (this.component.protected) { return '--- PROTECTED ---'; } return this.getValueAsString(value, options); } ``` -------------------------------- ### Initialize Formio Modules with useModule Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/formio.form.js.html A factory function that returns a plugin registration handler, supporting both single plugins and arrays of plugins. ```javascript export function useModule(defaultFn = null) { return (plugins, options = {}) => { plugins = _.isArray(plugins) ? plugins : [plugins]; plugins.forEach((plugin) => { if (Array.isArray(plugin)) { plugin.forEach(p => registerModule(p, defaultFn, options)); } else { registerModule(plugin, defaultFn, options); } }); }; } ``` -------------------------------- ### Form.io Builder Initialization (Simplified) Source: https://github.com/formio/formio.js/blob/main/app/examples/customcomponent.md A simplified version of the Form.io builder initialization, demonstrating the core setup for creating a form builder instance and integrating it with a form renderer. This version omits some configuration options for brevity. ```javascript Formio.builder(document.getElementById('builder'), {}, { builder: { basic: false, advanced: false, data: false, layout: false, customBasic: { title: 'Basic Components', default: true, weight: 0, components: { checkmatrix: true } } } }).then(function(builder) { Formio.createForm(document.getElementById('formio'), builder.form).then(function(instance) { var json = document.getElementById('json'); instance.on('change', function() { json.innerHTML = ''; json.appendChild(document.createTextNode(JSON.stringify(instance.submission, null, 4))); }); builder.on('change', function(schema) { if (schema.components) { instance.resetValue(); instance.form = schema; } }); }); }); ``` -------------------------------- ### Get Container Components Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/WebformBuilder.js.html Provides a getter for the components within the webform's form container. ```javascript get container() { return this.webform.form.components; } ``` -------------------------------- ### Manage row index Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/nested/NestedComponent.js.html Get and set the row index, propagating the update to all child components. ```javascript get rowIndex() { return this._rowIndex; } set rowIndex(value) { this._rowIndex = value; this.eachComponent((component) => { component.rowIndex = value; }); } ``` -------------------------------- ### Wizard Initialization with Options Source: https://github.com/formio/formio.js/blob/main/app/examples/wizard.md Customize wizard behavior by passing an options object to Formio.createForm. This example disables clickable breadcrumbs and hides the 'Cancel' button. ```html
``` ```javascript Formio.createForm( document.getElementById('wizardWithOptions'), 'https://examples.form.io/wizard', { breadcrumbSettings: {clickable:false}, buttonSettings: {showCancel: false} }) .then(function(wizard) { wizard.on('nextPage', function(page) { console.log(page); }); wizard.on('submit', function(submission) { console.log(submission); }); }); ``` -------------------------------- ### Get component context for NestedDataComponent Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/nesteddata/NestedDataComponent.js.html Returns the data value of the component, used to establish context. ```javascript componentContext() { return this.dataValue; } ``` -------------------------------- ### Check Library Readiness Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Verifies if a specific library has been initialized and returns its readiness Promise. ```javascript Component.libraryReady = function(name) { Iif ( Component.externalLibraries.hasOwnProperty(name) && Component.externalLibraries[name].ready ) { return Component.externalLibraries[name].ready; } return Promise.reject(`${name} library was not required.`); }; ``` -------------------------------- ### Component readiness and string representation Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/components/_classes/component/Component.js.html Methods for checking component readiness and converting values to string format. ```javascript whenReady() { console.warn('The whenReady() method has been deprecated. Please use the dataReady property instead.'); return this.dataReady; } get dataReady() { return Promise.resolve(); } /** * Prints out the value of this component as a string value. * @param {*} value - The value to print out. * @returns {string} - The string representation of the value. */ asString(value) { value = value || this.getValue(); return (Array.isArray(value) ? value : [value]).map(_.toString).join(', '); } ``` -------------------------------- ### Get Parent Container Source: https://github.com/formio/formio.js/blob/main/coverage/lcov-report/src/PDFBuilder.js.html Retrieves the parent container and original component definition for a given component. ```javascript getParentContainer(component) { let container = []; let originalComponent = null; eachComponent(this.webform._form.components, (comp, path, components) => { Iif (comp.id === component.component.id) { container = components; originalComponent = comp; return true; } }, true); return { formioComponent: component.parent, formioContainer: container, originalComponent }; } ```