formio.js

repository·main·Indexed 24 days ago

https://github.com/formio/formio.js

A plain JavaScript form renderer and SDK for Form.io (version 5.5.0) that allows developers to render JSON schema-based forms and interact with Form.io APIs without framework dependencies. It includes a JSON form builder via Formio.builder(), support for multi-step wizards, and a programmatic SDK for loading and saving submissions. Key features include conditional select components, reCAPTCHA integration, save-as-draft functionality, and WYSIWYG editor support for textarea components using Quill.

Tokens
11.6K
Snippets
20
Records
64
Agent score
83%

What's inside @formio/js

  1. Configure the reCAPTCHA component

    main

    The reCAPTCHA component in Form.io can be configured to trigger based on different events: formLoad or buttonClick.

    To use reCAPTCHA, you must provide a siteKey within the form's settings.recaptcha object and set isEnabled to 'true'.

    Trigger Types

    • formLoad: The reCAPTCHA challenge is triggered automatically when the form is loaded. Set eventType: 'formLoad' in the component configuration.
    • buttonClick: The reCAPTCHA challenge is triggered when a specific button is clicked. Set eventType: 'buttonClick' and provide the buttonKey of the target button.
    const formJSON = {
      components: [
        {
          eventType: 'buttonClick',
          type: 'recaptcha',
          key: 'reCaptcha',
          label: 'reCAPTCHA',
          buttonKey: 'test', // The key of the button that triggers the reCAPTCHA
        },
        {
          eventType: 'formLoad',
          type: 'recaptcha',
          key: 'reCaptcha2',
          label: 'reCAPTCHA',
        }
      ],
      name: 'testRecaptchaForm',
      settings: {
        recaptcha: {
          isEnabled: 'true',
          siteKey: 'YOUR_GOOGLE_SITE_KEY',
        },
      },
    };
  2. Render a form wizard

    main

    The library supports multi-step wizards. A form is automatically rendered as a wizard if its JSON schema has the display property set to wizard. You use the same Formio.createForm() method used for standard forms.

    <script type="text/javascript">
      Formio.createForm(document.getElementById('formio'), 'https://examples.form.io/wizard');
    </script>
  3. Quickstart with CDN (Embed version)

    main

    For a simple implementation without a build step, you can include the embedded script via CDN and use the global Formio object.

    <html
      >
      <head
        <meta charset="utf-8" />
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css"
        />
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css"
        />
        <script src="https://cdn.form.io/js/formio.embed.js"></script>
      </head>
      <body>
        <div id="formio"></div>
        <script type="text/javascript">
          Formio.createForm(document.getElementById('formio'), 'https://examples.form.io/example');
        </script>
      </body>
    </html>
  4. Embed a form using a single script tag

    main

    For quick embedding, you can use a single <script> tag that points to the formio.embed.min.js endpoint. Use the src query parameter to specify the form URL and libs=true to include necessary libraries.

    <script src="https://cdn.form.io/js/formio.embed.min.js?src=https://examples.form.io/example&libs=true"></script>
  5. Implement Custom Wizards using custom events

    main

    Standard wizard navigation can be overridden to create custom workflows, such as adding 'Review' or 'Thank you' pages.

    To implement a custom wizard:

    1. Build the Form: Create a form containing custom buttons that trigger specific events (e.g., gotoNextPage, gotoPreviousPage, or wizardSave).
    2. Hide Default Buttons: When calling Formio.createForm, use the buttonSettings option to hide the default wizard navigation buttons (showCancel, showPrevious, showNext, showSubmit).
    3. Listen for Events: Use the .on() method on the returned form instance to listen for your custom button events and manually invoke the corresponding navigation methods like .nextPage(), .prevPage(), or .submit().
    Formio.createForm(document.getElementById('wizard'), 'https://examples.form.io/customwizard', {
      buttonSettings: {
        showCancel: false,
        showPrevious: false,
        showNext: false,
        showSubmit: false,
      },
    }).then(function (wizard) {
      wizard.on('gotoNextPage', function () {
        wizard.nextPage();
      });
      wizard.on('gotoPreviousPage', function () {
        wizard.prevPage();
      });
      wizard.on('wizardSave', function () {
        wizard.submit().then(function () {
          wizard.onChange();
          wizard.nextPage();
        });
      });
    });
  6. Enable the Save as Draft feature

    main

    The saveDraft feature allows you to periodically or manually save a submission in "draft" mode. This enables a "save and return" capability where a user can leave the page and resume their progress later.

    Requirements:

    • The user must be authenticated. Anonymous draft submissions are not supported because the platform cannot associate the draft with a specific user.
    • You must use a Form.io authentication module (e.g., the Angular module) to establish a user session.
    • You must not explicitly set the form.submission object after rendering, as manually setting the submission will disable the draft mode.
    // Enable periodic draft saving (defaults to every 5 seconds)
    Formio.createForm(document.getElementById('formio'), 'https://examples.form.io/example', {
      saveDraft: true,
    });
    
    // Ensure a user is set so the draft can be associated with them
    Formio.setUser({
      _id: '123',
    });
  7. Configure Save as Draft timing

    main

    By default, the saveDraft feature triggers a save every 5 seconds. You can adjust this frequency using the saveDraftThrottle parameter, which accepts a value in milliseconds.

    // Save a draft every 10 seconds.
    Formio.createForm(document.getElementById('formio'), 'https://examples.form.io/example', {
      saveDraft: true,
      saveDraftThrottle: 10000,
    });
  8. Configure the embed via script URL parameters

    main

    The embed() function supports configuration via query parameters attached to the Form.io script tag's src. This allows for zero-code configuration by simply modifying the <script> tag in the HTML.

    Supported URL Parameters:

    • script: Path to the JS file.
    • styles: Path to the CSS file.
    • cdn: CDN base URL.
    • project: Form.io project.
    • base: API base URL.
    • submit: Custom submission endpoint.
    • return or redirect: Redirect URL after submission.
    • success: Success message.
    • debug: Set to 'true' or '1' to enable debug mode.
    • libs: Set to 'true' or '1' to include libraries.
    • shadow: Set to 'false' or '0' to disable shadow DOM.
  9. Implement a custom AddressProvider

    main

    To implement a custom address lookup service (e.g., integrating with Google Maps or a custom API), extend the AddressProvider class. You must implement the getRequestUrl method to define how the search query is sent to your endpoint.

    Key properties to override for proper data mapping:

    • queryProperty: The key used in the request parameters for the search string (defaults to 'query').
    • responseProperty: The path within the API response to the array of address results (e.g., 'results').
    • displayValueProperty: The path within an address object to the string used for display (e.g., 'formatted_address').
    • defaultOptions: An object containing default configuration for the provider.

    Once implemented, you can use the search(query, options) method to perform lookups, which returns a Promise resolving to an array of Address objects.

  10. Configure buttonSettings in Formio.createForm

    main
    The buttonSettings object within the Formio.createForm options allows you to control the visibility of default wizard navigation buttons. This is useful when you want to replace standard navigation with custom logic or custom-built buttons within the form schema.
  11. Enable WYSIWYG editor in Textarea components

    main

    You can transform a standard textarea component into a WYSIWYG (What You See Is What You Get) editor by setting the wysiwyg property to true within the component configuration. This implementation uses the Quill editor.

    Formio.createForm(document.getElementById('formio'), {
      components: [
        {
          type: 'textarea',
          label: 'Content',
          wysiwyg: true,
          validate: {
            required: true
          },
          key: 'content',
          input: true,
          inputType: 'text'
        }
      ]
    });