This object contains formcycle specific utility functions.

Hierarchy

  • XUtil

Index

Properties

ajaxUploadDialog

ajaxUploadDialog: AjaxUploadDialog

Simple modal overlay dialog that shows the pending uploads.

ajaxUploadManager

ajaxUploadManager: AjaxUploadManager

Manager for handling AJAX uploads, i.e. upload elements where the selected files are uploaded automatically in the background.

appointmentPicker

appointmentPicker: AppointmentPickerApi

The API of the appointment picker, which contains several functions to work with appointment pickers, such as getting the currently selected date or time, or changing the selected date or time.

The API is available via $.xutil.appointmentPicker.

hash

hash: Hash

Utilities for working with hashes (checksums).

inputElementCounter

inputElementCounter: InputElementCounter

The entry point for the character counter. It adds a simple character to input and textarea elements.

Optional onready

onready: function

A callback that is invoked when the form is rendered and completely initialized. This property only lets you set a single callbac. You can also add multiple listeners like this:

$("form.xm-form").on("ready", myListener);

Type declaration

    • Parameters

      Returns void

ready

ready: boolean

A flag that indicates whether the form is rendered and completly initialized. This is similar to the the onready callback which is invoked when the form becomes ready, but lets you query the status instead.

Methods

drawImagePreview

  • drawImagePreview(element: HTMLElement | JQuery, images: keyof PreviewImage[]): void
  • Given an upload element, updates the image preview with the given images.

    Parameters

    • element: HTMLElement | JQuery

      The file input element of the upload form element.

    • images: keyof PreviewImage[]

      List of preview images to draw. When empty, the preview images are all removed.

    Returns void

getDataQuery

  • getDataQuery(queryName: string, params?: SingleOrArrayLike<undefined | boolean | number | bigint | string | Node | JQuery>, success?: JQuery.TypeOrArray<JQuery.Ajax.SuccessCallback<any>>, error?: JQuery.TypeOrArray<JQuery.Ajax.ErrorCallback<any>>): Promise<object>
  • Performs an AJAX request to a database query created in the formcycle backend configuration interface. If the query contains any placeholders (question marks ?), exactly that number of parameters needs to be given or the query fails.

    // Callback when the query succeeded
    function successFunc(data) {
      // Do something with the returned data in JSON format
      console.log(data);
      if (data.result.length > 0) {
        $('[name=tfName]').val(data.result[0].name);
      }
    }
    
    // Callback when the query failed
    function errorFunc(jqXHR, textStatus, errorThrown) {
      // Handle error
      console.error(errorThrown);
    }
    
    function getData(paramID, paramMail) {
      $.xutil.getDataQuery('SampleDbQueryName', [paramID, paramMail],
        successFunc, errorFunc);
    }
    
    // Run database query with parameter values taken from form fields
    getData($('[name=tfId]').val(), $('[name=tfMail]').val());

    Parameters

    • queryName: string

      Name of the database query, as set in the formcycle backend configuration interface.

    • Optional params: SingleOrArrayLike<undefined | boolean | number | bigint | string | Node | JQuery>

      Additional parameters for the database query. Can be a single value or an array of values, all given values are transmitted as additional parameters. For undefined an empty value is transmitted. For a string, the string value itself is transmitted. For a number or boolean, the string representation of the number or boolean is transmitted. For a JQuery instance, the values of all elements in that JQuery selection are transmitted. For an HTML element: (1) if it is an input checkbox or radio element, transmits the value if the checkbox or radio button is checked, (2) if it is an input file element, transmits the name of each file, or an empty string if no files are selected, (3) if it an input element of another type, transmits the value of the input element, (4) if it is a textarea or select element, obtains the value via $.fn.val and transmits that value, (5) if it is any other element, searches for child elements that are input, textarea, or select elements and transmits those values.

    • Optional success: JQuery.TypeOrArray<JQuery.Ajax.SuccessCallback<any>>

      Callback called when the database query succeeds.

    • Optional error: JQuery.TypeOrArray<JQuery.Ajax.ErrorCallback<any>>

      Callback called when the database query fails.

    Returns Promise<object>

    A promise that is fulfilled with the data returned by the database query. Each item in the array corresponds to one row in the database.

getFormParam

  • getFormParam(name: string, defaultValue?: string): string | undefined
  • Retrieves the value of the URL parameter for the given name. Returns the default if no such parameter exists.

    If a parameter name occurs multiple times, all values are returned, separated with a comma (,).

    If the URL is as follows:

    https://formcloud.de/formcycle/form/provide/9999?name=James&preview&mode=&name=John

    Then this function returns:

    $.xutil.getFormParam("name") // => "James,John"
    $.xutil.getFormParam("preview"); // => undefined
    $.xutil.getFormParam("mode"); // => undefined
    $.xutil.getFormParam("owner", "anonymous"); // => "anonymous"

    Parameters

    • name: string

      Name of the URL parameter to retrieve.

    • Optional defaultValue: string

      Default value in case the URL parameter is not set.

    Returns string | undefined

    The value of the given parameter name, or the default value if no such parameter exists.

getFormUrl

  • getFormUrl(name: FormUrlType, defaultValue?: string): string | undefined
  • Finds a FORM-specific URL of a certain type. If you need to access a formcycle resource, use this function as the URLs may change in future versions.

    The following types of URLs are available:

    • attachment: Base URL for accessing attachments uploaded via upload elements.
    • context: The current context path of the web application, eg. /formcycle.
    • dataquery_db: Base URL for accessing database queries as configured in the formcycle backend.
    • dataquery_ldap: Base URL for accessing LDAP queries as configured in the formcycle backend.
    • datasource_csv: Base URL for accessing CSV data sources as configured in the formcycle backend.
    • datasource_db: (deprecated) Use dataquery_db instead.
    • datasource_json: Base URL for accessing JSON data sources as configured in the formcycle backend.
    • datasource_xml: Base URL for accessing XML data sources as configured in the formcycle backend.
    • keepalive: URL for keeping the current session alive. Similar to a ping.
    • plugin: URL for executing servlet plugins.
    • previewAction: URL for requesting a preview of a form. A preview cannot be submitted.
    • submitAction: URL to which the form data is submitted.
    // This returns "/formcycle/datenquellecsv/"
    $.xutil.getFormUrl("datasource_csv", undefined);

    Parameters

    • name: FormUrlType

      Type of the form URL to be retrieved.

    • Optional defaultValue: string

      Default value to be returned when no URL was found.

    Returns string | undefined

    The form URL of the given type. If no such type exists, the given default value.

getLdapQuery

  • getLdapQuery(queryName: string, params?: SingleOrArrayLike<undefined | boolean | number | bigint | string | Node | JQuery>, success?: JQuery.TypeOrArray<JQuery.Ajax.SuccessCallback<any>>, error?: JQuery.TypeOrArray<JQuery.Ajax.ErrorCallback<any>>): Promise<Record<string, any>[]>
  • Performs an AJAX request to an LDAP query created in the formcycle backend configuration interface. If the query contains any placeholders (question marks ?), exactly that number of parameters needs to be given or the query fails.

    // Callback when the query succeeded
    function successFunc(data) {
      // Do something with the returned data in JSON format
      console.log(data);
      if (data.length > 0) {
        $('[name=tfName]').val(data[0].name);
      }
    }
    
    // Callback when the query failed
    function errorFunc(jqXHR, textStatus, errorThrown) {
      // Handle error
      console.error(errorThrown);
    }
    
    function getData(paramID, paramMail) {
      $.xutil.getDataQuery('SampleDbQueryName', [paramID, paramMail],
        successFunc, errorFunc);
    }
    
    // Run LDAP query with parameter values taken from form fields
    getData($('[name=tfId]').val(), $('[name=tfMail]').val());

    Parameters

    • queryName: string

      Name of the LDAP query, as set in the formcycle backend configuration interface.

    • Optional params: SingleOrArrayLike<undefined | boolean | number | bigint | string | Node | JQuery>

      Additional parameters for the LDAP query. Can be a single value or an array of values, all given values are transmitted as additional parameters. For undefined an empty value is transmitted. For a string, the string value itself is transmitted. For a number or boolean, the string representation of the number or boolean is transmitted. For a JQuery instance, the values of all elements in that JQuery selection are transmitted. For an HTML element: (1) if it is an input checkbox or radio element, transmits the value if the checkbox or radio button is checked, (2) if it is an input file element, transmits the name of each file, or an empty string if no files are selected, (3) if it an input element of another type, transmits the value of the input element, (4) if it is a textarea or select element, obtains the value via $.fn.val and transmits that value, (5) if it is any other element, searches for child elements that are input, textarea, or select elements and transmits those values.

    • Optional success: JQuery.TypeOrArray<JQuery.Ajax.SuccessCallback<any>>

      Callback called when the LDAP query succeeds.

    • Optional error: JQuery.TypeOrArray<JQuery.Ajax.ErrorCallback<any>>

      Callback called when the LDAP query fails.

    Returns Promise<Record<string, any>[]>

    A promise that is fulfilled with the data returned by the database query. Each item in the array corresponds to one entry in the active directory.

isStatus

  • isStatus(stateName: string | undefined): boolean
  • Helper function to check the current state of the form. States can be created and managed in the workflow configuration.

    // When the form is opened for the first time (no state set), set
    // the default value for the form element "tfMail".
    if ($.xutil.isStatus(undefined)) {
       $("[data-name='tfMail']").val("default@mail.com");
    }
    
    // Check for a certain state
    var isArchived = $.xutil.isStatus("Archived");

    Parameters

    • stateName: string | undefined

      Name of the state to check against the current state. You may pass undefined to check whether no state is set, ie. whether the form has not yet been submitted.

    Returns boolean

    true iff the current state of the form is the same as the given state, false otherwise.

load

  • Loads saved data into the form, filling all form elements with the saved values.

    Compared with loadFromString, this method uses the object instead of a serialized string.

    Parameters

    Returns void

loadFromString

  • loadFromString(data: string): void
  • Loads saved data into the form, filling all form elements with the saved values.

    Compared with load, this method uses the serialized string instead of an object.

    Parameters

    Returns void

off

  • off<K>(event: K, eventCallback: XUtilCallbacks[K]): void
  • Removes an event callback previously added via on.

    Type parameters

    • K: keyof XUtilCallbacks

      Type of the event name for which to remove a listener.

    Parameters

    • event: K

      Name of the event to for which to remove a listener.

    • eventCallback: XUtilCallbacks[K]

      Listener to remove.

    Returns void

offSubmit

  • Removes a callback that was added via onSubmit.

    deprecated

    Use $.xutil.off("submit")

    Parameters

    Returns void

on

  • on<K>(event: K, eventCallback: XUtilCallbacks[K]): Disposable
  • Register a callback function for one of the events issued during the lifecycle of a form.

    Uncaught errors in callbacks are caught, logged, and ignored otherwise.

    Type parameters

    • K: keyof XUtilCallbacks

      Type of the event name for which to register a listener.

    Parameters

    • event: K

      Name of the event to listen to.

    • eventCallback: XUtilCallbacks[K]

      Listener that is invoked when the event occurs.

    Returns Disposable

    A disposable that can be used to remove the listener.

onPrint

  • onPrint(callback: function): void
  • Registers a callback for the print service. The callbacks is invoked by the print service before the form is printed. You can use this callback to prepare the form for printing. When the callback returns a promise, the print service waits for the promise to fulfill before printing the form. When the promise is rejected, the error is logged, but does not prevent the print.

    deprecated

    Use $.xutil.on("print")

    Parameters

    • callback: function

      Callback to register.

        • (): void | Promise<void>
        • Returns void | Promise<void>

    Returns void

onReadyStateComplete

  • onReadyStateComplete(callback: function): void
  • Invokes the given callback function as soon as {@link document.readyState} changes to complete. When the ready state is already complete, the callback is run immediately (but still asynchronously during one of the next event loop cycles).

    This is similar to JQuery's on ready callback ($(function() { })), but that function makes use of DOMContentLoaded and may run the callback when the document's ready state is still loading. When you need the document to be fully loaded, use this function.

    For example, when you want to calculate the width or height of an element, you may get the wrong result when the document's ready state is still loading, since stylesheets or font faces inside stylesheets may not have loaded yet.

    Parameters

    • callback: function

      Callback to invoke once the document's ready state changes to complete.

        • (): void
        • Returns void

    Returns void

onStatus

  • onStatus(stateName: string | undefined, callback: function): void
  • onStatus(callback: function): void
  • Helper function to run code when the form is currently in a given state. States can be created in the workflow configuration.

    // When the form is opened for the first time (no state set),
    // set the default value for the form element "tfMail"
    $.xutil.onStatus(undefined, function() {
      $("[data-name='tfMail']").val("default@mail.com");
    });
    
    $.xutil.onStatus('Archiv', function() {
      // Do something when form is archived
    });

    Parameters

    • stateName: string | undefined

      Name of the state to check against the current state. You may pass undefined to check whether no state is set, ie. whether the form has not yet been submitted.

    • callback: function

      Function that is executed immediately (synchronous to the caller) in case the current state of the form matches the given state.

        • (): void
        • Returns void

    Returns void

  • Helper function to run code when the form has got no state currently, ie. when it has not been submitted yet. States can be created in the workflow configuration.

    // When the form is opened for the first time (no state set), set
    // the default value for the form element tfMail.
    $.xutil.onStatus(function() {
      $("[data-name='tfMail']").val("default@mail.com");
    });

    Parameters

    • callback: function

      Function that is executed immediately (synchronous to the caller) in case the current state of the form matches the given state.

        • (): void
        • Returns void

    Returns void

onSubmit

  • Registers a callback for when the form is submitted. Can be used e.g. to run additional actions or to prevent the submission.

    The callback is called after the form was validated, if the submit button requires validation.

    $.xutil.onSubmit(() => doSomething())
    
    $.xutil.onSubmit(({submissionBlocked}) => {
      // Check if the submission is already blocked
      if (submissionBlocked) {
        return;
      }
    
      // Custom code to be run on submission
      // Custom logic to check whether the form submission should be cancelled.
       const preventSubmission = customLogic();
    
       return { preventSubmission };
    });
    deprecated

    Use $.xutil.on("submit")

    Parameters

    • callback: OnSubmitCallback

      Callback to invoke when the form is about to be submitted.

    Returns Disposable

    A disposable that can be used to remove the callback. This is equivalent to calling offSubmit with the callback passed to this method.

onsubmit

  • onsubmit(isFormValid: boolean): boolean | undefined
  • A function that is called when the form is submitted. The default implementation simply returns true, so you can override this function without calling the original function. When you would like to cancel the submission of the form, return false from this method.

    $.xutil.onsubmit = function(isFormValid) {
      // Custom code to be run on submission.
      // ...
    
      // Custom logic to check whether the form submission should be cancelled.
       return isFormValid;
    };
    deprecated

    This can be used only once to register a single listener. When you add a listener it will overwrite the previous listener. Use on instead.

    Parameters

    • isFormValid: boolean

      Whether the form is currently valid (eg. if all required fields have been filled out etc.)

    Returns boolean | undefined

    true to proceed with form submission, false or undefined to prevent the form's submission.

parseFloat

  • parseFloat(value: string | undefined): number
  • Parses the given value as a decimal number and returns the value. Accepts both a period and a comma as the decimal separator.

    Parameters

    • value: string | undefined

      Value to parse.

    Returns number

    The string parsed as a number, 0 if undefined was passed.

save

  • Creates an object with all data from the current form, including all repeated form fields and all uploaded files.

    Compared with save, this returns an object instead of a serialized string.

    Returns LegacyFormSaveData

    An object with the form data.

saveAsString

  • saveAsString(): string
  • Creates a string with a serialized representation of all data from the current form, including all repeated form fields and all uploaded files.

    Compared with save, this returns a serialized string instead of an object.

    Returns string

    A serialized string with the form data.

trigger

  • trigger<K>(event: K, eventData: Parameters<XUtilCallbacks[K]>): ReturnType<XUtilCallbacks[K]>[]
  • Fires an event of the given types, invoking all listeners that were registered via on.

    Type parameters

    • K: keyof XUtilCallbacks

      Type of the event name to trigger.

    Parameters

    • event: K

      Name of the event.

    • eventData: Parameters<XUtilCallbacks[K]>

      Data to pass to the event listeners.

    Returns ReturnType<XUtilCallbacks[K]>[]