← Classic DFFS

Custom JS API reference

The functions, hooks and variables you can use in the Custom JS tab of Classic DFFS. Applies to Classic DFFS v5 (package 5.0.0.0) with SPJS-utility v1.357 and vLookup v2.2.171. Looking for SharePoint Online’s modern forms? That is Modern DFFS, which has its own API.

Basics

Where your code runs

Code in the Custom JS tab runs in the form page, after DFFS and its plugins have loaded. Functions and variables you declare at the top level become global (window), which is how DFFS finds the hooks and the functions named in rules.

  • DFFS loads its own jQuery as jQspjs. Use it instead of $ or jQuery, which may be another version or missing.
  • Fields are addressed by their FieldInternalName (written fin below), not the display name. The form row for a field has the id dffs_FieldInternalName.
  • Files listed above the Custom JS textarea load first. Add {inject} after a file path to paste the file’s contents into Custom JS instead of loading it with RequireJS. Paths can start with ~site or ~sitecollection.
  • Add debugger; in a function to stop there with the browser’s developer tools (F12) open.
  • Custom JS needs a Professional license; with Essentials it does not run.
  • With the central site and an Enterprise license, the tenant-wide GlobalCustomJS from the central settings list runs first, before the form’s own Custom JS.

Errors in development mode

Some errors that DFFS ignores silently in production are logged as console warnings while you test in development mode: e-mail recipients that cannot be resolved, errors while building an e-mail body, the required-fields banner, reading field values, the plugins (vLookup, Autocomplete, people pickers, cascading dropdowns) and the central GlobalCustomJS. Open the browser console (F12) in the test window to see them.

When the form is ready

Custom JS runs while the form is still being built: tabs exist, but rules have not run yet. Anything that depends on rules, tabs being selected or field values set by rules belongs in dffs_Ready. Calling spjs.dffs.triggerRule before the rules are processed shows an error that says exactly this.

Synchronous calls

The list functions in spjs.utility (queryItems, addItem, updateItem …) and the user and group functions call SharePoint’s web services synchronously: the browser waits for the answer and the function returns the result directly, with no callback or promise. That keeps code short, but the page is frozen while the request runs, so avoid them in loops over many items. Functions that return a jQuery Deferred are marked as such.

Hooks you define

DFFS calls these if a global function with the name exists. Define each one once.

dffs_Ready()

Called once when the form has finished loading: all rules have run, including rules triggered by The form is ready, and vLookup has started. dffs_ready (lower-case r) is also called, for older configurations.

function dffs_Ready() {
    if (spjs.dffs.data.isNewForm) {
        setFieldValue("Status", "Draft");
    }
}

dffs_PreSaveAction()

Called when the user saves. Return false to stop the save, true to allow it. Any other value lets the save continue and writes a warning to the save debug output.

The save runs in this order:

  1. Field validation rules. A failing one stops the save.
  2. Rules with the trigger The form is saved: their Set field value, Run these functions and Send or stop these E-Mails actions run.
  3. Required fields are checked. An empty required field stops the save.
  4. dffs_PreSaveAction(), then SharePoint’s own PreSaveAction() if defined.
  5. E-mails collected in step 2 are sent, then the save is triggered again. On that second pass dffs_PreSaveAction is not called again.

Returning false from a linked rule of a save-triggered rule does not stop the save; only this function can.

function dffs_PreSaveAction() {
    if (getFieldValue("EndDate") !== "" && getFieldValue("StartDate") === "") {
        spjs.dffs.alert({ "title": "Missing start date", "msg": "Fill in the start date before the end date." });
        return false;
    }
    return true;
}

saveAndStayInForm_PreSaveAction()

Called before Save and stay in form (Misc tab) saves. Return false to cancel. If you need to wait for something asynchronous, return false, and when your work is done call spjs.dffs.saveAndStayInForm(true), which saves without calling this function again.

Rule trigger: Custom JavaScript function

A rule with the trigger Custom JavaScript function calls the global function named in This value and treats its return value as the rule’s result. The function receives the rule’s friendly name. Prefix the name with ~ to reverse it (the rule matches when the function returns false).

The function is called when the rule is evaluated: on load, and when the rule is evaluated from code with spjs.dffs.evaluateRule or as a linked rule.

function isWeekend(ruleName) {
    var d = spjs.utility.getDateFieldAsDateObject("StartDate");
    return d !== "" && (d.getDay() === 0 || d.getDay() === 6);
}

Rule action: Run these functions / evaluate these rules

Comma-separated names. For each name DFFS calls the global function with that name, passing the friendly name of the calling rule. If no such function exists and the name is a rule’s friendly name, that rule is evaluated instead. Start the field with {inline} to write the code directly in the rule; the calling rule’s name is then available as the parameter of the generated function.

{inline}
setFieldValue("Title", "Set by a rule");

Results of these functions do not feed back into the rule. Use Linked rules and functions for that.

Field values

getFieldValue(fin, dispform, delimiter, key)

Returns the current value of a field in the form. Returns "" if the field is not in the form. dispform is ignored (DispForm is detected from the URL); it is kept so older code still works.

  • delimiter: join multi-value results (multi choice, people, multi lookup, managed metadata) into one string with this separator instead of returning an array.
  • key: people fields only. "loginName" returns login names, "isResolved" returns true/false per entry; leave it out for display names.
Field typeReturns (NewForm / EditForm)
Single line, number, currency, file namestring, as typed in the form (numbers keep the user’s decimal separator; see strToNum)
Choicestring: the selected choice, or the fill-in text
Multiple choicearray of checked choices (string with delimiter)
Yes/No, all-day event, recurrencetrue / false
Date and timestring as shown in the form: the date, plus " HH:MM" (with AM/PM on 12-hour sites) when the field has a time
Lookupstring: the selected item’s text, "" when none
Multi lookuparray of the selected items’ text
Person or grouparray of display names (see key)
HyperlinkHTML link <a href='…' target='_blank'>description</a>. For the URL only: spjs.utility.getFieldValue({ "fin": "Link", "onlyUrl": true })
Multiple lines, plain textstring
Multiple lines, rich / enhanced rich textHTML string
Managed metadataarray of term labels
Attachments ("Attachments")array of HTML links to the attached files; empty in NewForm
"ID"the item ID from the URL

In DispForm the value is read from the displayed text: most fields return a trimmed string, multiple people return an array of names, multiple lines return HTML, and Yes/No returns true/false.

var status = getFieldValue("Status");
var people = getFieldValue("Reviewers", false, "; ");          // "Ann Lee; Bo Berg"
var logins = getFieldValue("Reviewers", false, ",", "loginName");

setFieldValue(fin, value)

Sets a field in NewForm or EditForm. Does nothing if the field is not in the form. The field’s change event fires, so rules triggered by the field run. A third argument is accepted for older code and ignored. Line breaks are only kept in multiple-lines fields.

Field typeValue
Single line, number, currencystring
Choicethe choice text. In a fill-in choice field a value that matches no choice is written as fill-in text
Multiple choicearray of choices, or a comma-separated string
Yes/Notrue, "true", 1 or "1" checks it; anything else clears it
Date and timedate string in the format the form shows, or an array [date, hour, minute]. hour is the position in the hour dropdown (0–23); minutes are rounded down to 5. "" or null clears
Lookupthe item ID or the item’s text. "" clears
Multi lookuparray, or comma-separated string, of IDs or texts. "" clears
Person or grouplogin name(s): array, or a string separated by , or ;. "" clears
Hyperlink"url,description" or [url, description]
Multiple linestext, or HTML for rich text fields
Managed metadataterm label, or array of labels
External data (BCS)not supported

People and lookup fields are not ready the moment the form loads. A value set in the first 1–2 seconds is applied after a short delay, so read it back in dffs_Ready or later, not on the next line.

setFieldValue("Title", "New request");
setFieldValue("Category", ["Hardware", "Network"]);
setFieldValue("DueDate", "15.11.2025");
setFieldValue("AssignedTo", "i:0#.w|contoso\\ann");
setFieldValue("Customer", 12);          // lookup by ID

Date fields as Date objects

spjs.utility.getDateFieldAsDateObject(fin) returns the field as a JavaScript Date, or "" when empty. Date-only fields get the time 12:00. spjs.utility.setDateFieldFromDateObject(fin, date, offsetDays) writes a Date into the field using the field’s own date format, optionally adding offsetDays. Note that the offset is added to the Date object you pass in.

var start = spjs.utility.getDateFieldAsDateObject("StartDate");
if (start !== "") {
    spjs.utility.setDateFieldFromDateObject("EndDate", new Date(start.getTime()), 14);
}

Rules

spjs.dffs.triggerRule(rules)

Runs a rule’s actions straight away, without checking its trigger or its linked rules. rules is a friendly name or index, a comma-separated string of them, or an array. Prefix a name with ~ to run the rule’s reversed actions. Disabled rules are skipped. Call it from dffs_Ready or later.

spjs.dffs.triggerRule(["ShowApproval"]);
spjs.dffs.triggerRule("~ShowApproval");   // reverse: undo what the rule does

Use a rule’s Rule friendly name rather than its index; indexes change when rules are reordered.

spjs.dffs.evaluateRule(rule, initiator)

Evaluates a rule as if its trigger had fired: checks the trigger value and the linked rules, then runs the actions (or reverses them) and returns the result, true or false. rule is the friendly name or index; initiator is an optional label shown in the rule debug output. Rules set to validate on change only cannot be evaluated this way.

var approved = spjs.dffs.evaluateRule("IsApproved", "My button");

Read-only, required, visible

These are the functions the rule actions use. A rule that runs later can undo what you set, and the other way round.

spjs.dffs.doReadOnly(fields) / spjs.dffs.undoReadOnly(fields)

Show fields as read-only text, or editable again. fields is an array of FieldInternalNames; vLookup fields are named vLookup…. Does nothing in DispForm. An empty field that is also required is left editable.

spjs.dffs.doReadOnly(["Title", "Customer"]);

spjs.dffs.flag_Mandatory(fields) / spjs.dffs.clear_Mandatory(fields)

Make fields required (marked with a star and checked on save), or not required. clear_Mandatory never removes fields that are required in the list settings. A read-only field made required is made editable again if it is empty.

spjs.dffs.flag_Mandatory(["Reason"]);
spjs.dffs.clear_Mandatory(["Reason"]);

spjs.dffs.check_Mandatory(fields)

Checks the given required fields (when called without an argument: all required fields, or the fields in overrideRequiredFields if it is not empty), shows the validation message under each empty one and highlights the tabs they are in. Returns true when all are filled in. The message text can be changed with dffsRequiredFieldValidation.

spjs.dffs.data.overrideRequiredFields

An array of FieldInternalNames that replaces the required fields when the form is saved. While it is not empty, saving checks only these fields; all required fields keep their star, so users still see what will be needed. Set it back to an empty array to check all required fields again. Fields in the array are checked even if they are not starred.

Use it to show fields as required early but enforce them only at a certain point. For example, an EditForm with ten required fields that must all be filled in only when the status is Completed:

function enforceRequiredByStatus() {
    if (getFieldValue("Status") === "Completed") {
        spjs.dffs.data.overrideRequiredFields = [];   // check all required fields
    } else {
        spjs.dffs.data.overrideRequiredFields = ["Title", "Customer", "DueDate"];
    }
}
function dffs_Ready() {
    enforceRequiredByStatus();
    jQspjs("#dffs_Status").on("change", "select, input", enforceRequiredByStatus);
}

Fields that are required in the list settings are also checked by SharePoint itself when the item is saved, whatever this array holds.

spjs.dffs.hideFieldsByRule(fields) / spjs.dffs.unhideFieldsByRule(fields)

Hide or show fields, as the Hidden fields and Visible fields rule actions do. A field that is hidden by its tab or by an expand/collapse section stays hidden until that is opened. A required field that is empty is not hidden, so the form can still be saved.

spjs.dffs.setFieldLabel({ fin, label, css })

Changes a field’s label text, and optionally its style (a jQuery CSS object). Works for side-by-side labels too.

spjs.dffs.setFieldLabel({ "fin": "Title", "label": "Request title", "css": { "color": "green" } });

Tabs and buttons

spjs.dffs.toggleSelectedTab(tab)

Selects a tab, as if the user clicked it. tab is the tab’s index or its Tab unique ID.

spjs.dffs.toggleVisibleTab(tabs, show)

Shows (show = true) or hides tabs. tabs is a comma-separated string of tab indexes or unique IDs, or "*" for all tabs. If the selected tab is hidden, the first visible tab is selected.

spjs.dffs.toggleVisibleTab("approval,history", false);

Selects the previous (0) or next (1) visible tab, wrapping around at the ends. This is what the Previous / Next tab buttons do.

spjs.dffs.getSelectedTabId()

Returns the index of the selected tab. spjs.dffs.data.selectedTab holds the same value.

spjs.dffs.toggleSaveBtnByRule / toggleCancelBtnByRule / toggleEditBtnByRule(show)

Show (true) or hide (false) the Save buttons, the Cancel buttons or the Edit item button (ribbon and form). Hiding Save also hides Save and stay in form.

Messages and dialogs

spjs.dffs.alert({ title, msg, ok, cancel, okBtnLabel, cancelBtnLabel, noBtn, width })

Shows a DFFS dialog over the form and returns its id. msg can be HTML. ok and cancel are functions; each one adds its button, and the dialog closes after the function runs. With neither, the dialog has a single OK button. noBtn: true shows no buttons; close it with spjs.dffs.closeDlg(id), or spjs.dffs.closeDlg() to close all.

spjs.dffs.alert({
    "title": "Delete the attachment?",
    "msg": "This cannot be undone.",
    "okBtnLabel": "Delete",
    "ok": function () { /* … */ },
    "cancel": function () { }
});

spjs.modal.add(options)

A larger dialog that can be moved, resized and maximised. Returns the dialog id. Run spjs.modal.help() in the browser console to see every option with its default. The main ones are title, html, width, height, autosize, ok and cancel (functions, each adds its button), okBtnLabel, cancelBtnLabel, closeOnOK, showClose, allowMaximize, showMaximized, resizable, footer, onInit and onResize.

Close a dialog with spjs.modal.close(id); change its title with spjs.modal.setDlgTitle(id, html).

var id = spjs.modal.add({
    "title": "Order lines",
    "html": "<div id='orderLines'>Loading…</div>",
    "width": 600,
    "ok": function (id) { /* … */ }
});

spjs.dffs.dffs_notification(text, milliseconds)

Shows a short message in SharePoint’s notification area, for 3 seconds unless you give another duration. Tokens such as {Title} are filled in.

spjs.dffs.dffs_statusBanner(heading, text, color, milliseconds)

Shows a yellow banner across the top of the page: heading in bold, then text (HTML; tokens such as {Title} and MUI are filled in). It stays for milliseconds, 10 seconds when left out, or until it is replaced when null. A new banner replaces the previous one. color is not used.

spjs.dffs.dffs_statusBanner("Note", "This request is waiting for approval.", "", null);

spjs.utility.setDlgTitle(text)

Replaces the title of the SharePoint dialog the form is open in. Does nothing when the form is not in a dialog. The text is cleaned with sanitizeHTML, so formatting is kept but scripts do not run.

Save and redirect

spjs.dffs.triggerSave()

Clicks the form’s Save button, so the normal save runs, including required fields, rules on save and dffs_PreSaveAction.

spjs.dffs.saveAndStayInForm(bypass)

Saves and reopens the item, as the Save and stay in form button does: a NewForm opens the new item in DispForm or EditForm according to the redirect settings in the Misc tab (the list needs the _DFFSID column), and an EditForm reopens on the same tab. bypass = true skips saveAndStayInForm_PreSaveAction.

spjs.dffs.redirect(url, dialog) / spjs.dffs.cancelRedirect()

Sends the user to url after the form is saved, instead of back to the list. dialog = true opens the URL in a dialog, which only works when the form itself is in a dialog. cancelRedirect() removes a redirect set earlier; DFFS calls it when a save is stopped.

Set the redirect just before saving, not on load: outside a dialog it replaces SharePoint’s navigation function, so a redirect set on load would also send Cancel to that URL.

function dffs_PreSaveAction() {
    spjs.dffs.redirect("/sites/hr/SitePages/Thanks.aspx", false);
    return true;
}

E-mail and print

spjs.dffs.processEmailTemplate(templates)

Sends the e-mail templates configured in the E-Mail and Print tab, now, without saving. templates is a template ID, a comma-separated string or an array. Prefix an ID with stop: to stop a pending (delayed or recurring) e-mail of that template. A template whose To resolves to nobody shows an error and sends nothing. Each template is sent once per visit to the form: calling it again for the same template does nothing until the form is opened again, which stops double sending.

<input type="button" value="Notify the owner" onclick="spjs.dffs.processEmailTemplate('NotifyOwner')">

spjs.dffs.printCurrentTab()

Prints the selected tab with the print header and footer from the E-Mail and Print tab, as the print button does. Elements with the class dffs_noPrint are left out.

Tokens in text

Text in rules (Set field value, messages, alerts), headings, HTML sections, e-mail templates, tab banners and the print header and footer can contain tokens that DFFS replaces with live values.

Token list

TokenReplaced with
{FieldInternalName}the field’s current value
{{FieldInternalName}}the field’s value, kept up to date while the user edits the field
{Author}, {Editor}, {Created}, {Modified}the item’s stored values (empty in NewForm)
{currentUser}the logged-in user’s name
{currentUserEmail}a mailto link with the user’s name
{currentUser:Property}a property from the site’s user information list, for example {currentUser:Department}
{userProfile:Property}a property from the user profile service, for example {userProfile:Manager}
{timestamp}the current date and time in the browser’s format
{timestamp[format]}the current date and time in a formatDate format, for example {timestamp[dd.MM.yyyy HH:mm]}
{url:Key}the value of a URL query string parameter
{var:name}a global variable (dots allowed: {var:myObj.status}). If it does not exist yet, it is filled in when it appears
{{var:name}}a global variable, updated on screen whenever it changes

Set field value has extra formats ([today], prepend:, append:, calc:); see the user manual. E-mail templates also accept {viewitemlink}, {edititemlink} and {usergroup:Name}.

spjs.dffs.buildValStr(text)

Returns text with all tokens above replaced.

var subject = spjs.dffs.buildValStr("Request {ID} from {currentUser}");

Translated text (MUI)

Wherever DFFS shows text from your configuration, a JSON object in curly braces is replaced by the entry for the user’s language (LCID), or by "default":

{"1033":"Approved","1031":"Genehmigt","default":"Approved"}

spjs.dffs.translateStringWithJSON(text) does the same for your own text.

Users and groups

spjs.utility.userInfo(loginOrId, extraFields)

Reads a user from the site’s user information list by ID or login name. Returns an object with success and the fields ID, Name (login), Title, EMail, Department, JobTitle, Notes, Picture, IsSiteAdmin, Created, Author, Modified, Editor, SipAddress, plus any field names given in extraFields (string or array). Synchronous. The current user’s ID is _spPageContextInfo.userId.

var me = spjs.utility.userInfo(_spPageContextInfo.userId, "MobilePhone");
if (me.success) { setFieldValue("Phone", me.MobilePhone); }

spjs.utility.userProfile(accountName)

Reads a user profile from the user profile service and returns an object of property name → value. Leave out accountName for the current user. Returns the text "The user profile is not accessible." if the service does not answer. Synchronous.

spjs.dffs.verifyGroupMembership(groups)

Returns true if the current user is a member of at least one of the SharePoint groups given by ID or name (array or comma-separated string). Synchronous on first use, then cached.

if (spjs.dffs.verifyGroupMembership(["Approvers", 12])) { /* … */ }

spjs.dffs.getGroupCollectionFromUser(login) / getUserCollectionFromGroup(groupName)

getGroupCollectionFromUser returns [{ groupId, groupName }] for a user. getUserCollectionFromGroup returns [{ loginName, displayName, id, email }] for a SharePoint group; the group’s members must be visible to the user. Both synchronous.

Reading and writing lists

These use SharePoint’s lists.asmx web service and are synchronous. listName is the list’s display name or GUID; listBaseUrl is the server-relative URL of its site and defaults to the current site. Field names are FieldInternalNames.

spjs.utility.queryItems({ listName, listBaseUrl, query, viewFields, rowLimit, viewName, folder, scope, pagingInfo })

Runs a CAML query. query is the inner CAML (<Where> and optionally <OrderBy>); viewFields is an array of field names, and ID is always added. Returns { count, items, nextPagingInfo }, where each item is an object of the requested fields as strings (null when empty). Lookup and person values come back in SharePoint’s raw format, such as 12;#Ann Lee. rowLimit defaults to 100,000. If the list view threshold blocks the query, it is retried automatically with queryItemsThrottled.

var res = spjs.utility.queryItems({
    "listName": "Tasks",
    "query": "<Where><Eq><FieldRef Name='Status' /><Value Type='Text'>Open</Value></Eq></Where>",
    "viewFields": ["Title", "AssignedTo"]
});
jQspjs.each(res.items, function (i, item) { console.log(item.ID, item.Title); });

spjs.utility.queryItemsThrottled(args, errorFunc)

The same as queryItems for lists above the view threshold: it queries the list in ID ranges of 5,000 and merges the results. Slower; the query must have a <Where>.

spjs.utility.getItemByID({ listName, listBaseUrl, id, viewFields })

Returns one item as an object, or null when it does not exist.

spjs.utility.addItem({ listName, listBaseUrl, data })

Creates an item. data is an object of field name → value in SharePoint’s text format (for a lookup or person: the ID, or ID;#text). Returns { success, id, errorText, errorCode }.

var r = spjs.utility.addItem({ "listName": "Log", "data": { "Title": "Opened", "RelatedID": spjs.dffs.data.thisItemID } });
if (!r.success) { console.log(r.errorText); }

spjs.utility.updateItem({ listName, listBaseUrl, id, data })

Updates one item, or several when id is an array or a comma-separated string of IDs. Returns { success, errorText, errorCode } (and id for a single item).

spjs.utility.deleteItem({ listName, listBaseUrl, id, docFullUrl })

Deletes items by ID. For a document, also give docFullUrl, the file’s full URL; only one document can be deleted per call.

spjs.utility.getListByUrlName(baseUrl, urlName)

Looks up a list by the name in its URL and resolves a jQuery Deferred with { success, id, path, title, baseUrl, defaultView, fields, type, … }, where fields maps each FieldInternalName to { fin, disp, type, choices }.

spjs.utility.getListByUrlName("/sites/hr", "Requests").done(function (list) {
    if (list.success) { console.log(list.id); }
});

Older function names

Kept so older code keeps working: spjs_QueryItems, spjs_getItemByID, spjs_addItem, spjs_updateItem, spjs_deleteItem, spjs_UpdateListItem, getUserInfo_v2 (= spjs.utility.userInfo), spjs_wrapSoapRequest, spjs_AddList, spjs_UpdateList and init_fields_v2. They take the same arguments as the functions above.

Utilities

spjs.dffs.formatDate(date, format)

Formats a Date. Format codes: yyyy, yy, MMMM (month name), MMM (short month name), MM, M, dddd (weekday), ddd (short weekday), dd, d, HH (0–23), hh (1–12), mm, ss and am/pm. Month and weekday names come from the DFFS language file. Returns "" if date is not a Date. Every matching letter is replaced, so keep words out of the format string and add them around the result instead.

spjs.dffs.formatDate(new Date(), "dddd d. MMMM yyyy HH:mm");

spjs.dffs.strToNum(text)

Converts a number typed with the site’s thousand and decimal separators (for example "1 234,50") to a JavaScript number. Returns 0 for an empty string.

spjs.utility.urlKeyValue(key, url)

Returns the value of a query string parameter from the current URL, or from url if given; "" when missing.

spjs.utility.sanitizeHTML(html) / spjs.utility.escapeHTML(text)

Use these when you put user input or list data into the form as HTML. sanitizeHTML returns the HTML cleaned with DOMPurify, which DFFS loads: formatting is kept, but script tags and event handlers are removed. If DOMPurify is not available, the string is escaped instead and shows as text. escapeHTML escapes plain text (& < > " ') so it can go into HTML or a quoted attribute value. DFFS cleans field values the same way in read-only fields, headings, HTML sections, e-mails and vLookup tables.

var comment = getFieldValue("Comments");
jQspjs("#lastComment").html(spjs.utility.sanitizeHTML(comment));
jQspjs("#requester").html("<b>" + spjs.utility.escapeHTML(getFieldValue("Title")) + "</b>");

spjs.utility.currencyLcid

Read-only currency fields and vLookup currency columns show the currency symbol of the field’s currency setting (its LCID), using this table of LCID → [culture, currency code]. A currency that is not in the table shows the number without a symbol. Add it in Custom JS:

spjs.utility.currencyLcid["1044"] = ["nb-NO", "NOK"];

spjs.dffs.showLoadTime()

Writes DFFS’s load-time log to the console. Opening the form with showLoadTime=1 in the URL does the same automatically.

vLookup

spjs.vLookup.refresh(fin)

Reloads one vLookup table, given the name of its vLookup field (for example "vLookupTasks").

spjs.vLookup.dataObj

The data behind every vLookup table, by vLookup field name and then parent item ID: items, count, fields (field name → label), fieldsArr and the totals (tot, totFormatted). Read it in vLookupIsLoadedCallback, when it is complete.

function vLookupIsLoadedCallback(fin) {
    if (fin === "vLookupTasks") {
        var d = spjs.vLookup.dataObj[fin][spjs.dffs.data.thisItemID];
        if (d) { setFieldValue("OpenTasks", d.count); }
    }
}

vLookup callbacks

DefineCalled when
vLookupIsLoadedCallback(fin)a vLookup table has loaded or reloaded
vlookupAddChildPreCheck(fin)the user clicks Add new. Return false to stop the child form from opening
vlookupChildAddedCallback()a child item was saved from the Add new dialog
vlookupChildNotAddedCallback()the Add new dialog was closed without saving
vlookupChildViewOrEditCallback(fin, result)a child item’s view or edit dialog closed. result is SharePoint’s dialog result (1 = saved)
vLookupPresetFromUrlDone(fin)in a child form opened from vLookup, a field has been prefilled from the parent

Autocomplete, cascading dropdowns, lookup

These are set up in their own tabs in the DFFS backend. From Custom JS you can also start, stop and react to them. The full list of options for each is on its built-in feature page.

spjs.ac (Autocomplete)

  • spjs.ac.textField(options) / spjs.ac.peoplePicker(options): turn a text field or people picker into an autocomplete; options.applyTo is the field.
  • spjs.ac.setFieldValue(fin, value): set the value of a field that has autocomplete.
  • spjs.ac.destroy(fin): remove the autocomplete from a field.
  • Callbacks you can define: spjs_ac_validSelectionCallback(fin, value), spjs_ac_invalidSelectionCallback(fin, value) and spjs_ac_clearSelectionCallback(fin).

spjs.casc (Cascading dropdowns)

  • spjs.casc.init(options): start a set of cascading dropdowns from code.
  • spjs.casc.kill(fin): remove them from a field.
  • Callback you can define: spjs_casc_ready(id, fin, level), called when each dropdown has been filled.
  • A parseFunction named in the Set field values option receives the value and returns the value to write.

spjs.lookup (SPJS-Lookup)

  • spjs.lookup.init(options): turn a text field into a dropdown fed by a list query.
  • spjs.lookup.kill(fin): remove it.

Form state and variables

spjs.dffs.data

Read these; do not change them.

PropertyValue
isNewForm, isEditForm, isDispFormtrue in that form
thisItemIDthe item ID (empty in NewForm)
_DFFSIDthe item’s _DFFSID value, when the list has that column
currUserIDthe current user’s ID
selectedTabindex of the selected tab
tabConfigObjthe tab configuration, by index and by unique ID
requiredFieldsthe fields currently required
isMobiletrue on a mobile browser
bypassAllRulestrue when the current user is listed under Bypass all rules in the Misc tab
dffs_email_baseUrlthe site that holds the DFFS_EMail list (may be set; see below)

Variables you can set

VariableEffect
spjs.dffs.data.dffs_email_baseUrl = "/sites/x"use the DFFS_EMail list on another site (set in Custom JS of every form, or as dffs_email_baseUrl in the loader)
var dffsRequiredFieldValidation = "…"the text under an empty required field; may be a MUI JSON string
var DFFS_noPageRefresh = true(in the parent page) do not reload the page when a form dialog closes after a redirect
emailCurrentTabFormLabelCSS, emailCurrentTabFormBodyCSS, emailCurrentTabHeadingCSSinline CSS for labels, values and headings in E-mail active tab
vLookupHeaderCSS, vLookupBodyCSSinline CSS for vLookup tables in E-mail active tab

Variables that choose which configuration loads (dffs_formIdOverride, dffs_formTypeSwitch) and the loader settings are in the installation manual, since they must be set before DFFS loads.

CSS classes

  • dffs_noPrint: the element is left out of printouts.
  • dffs_noEmail: the element is left out of E-mail active tab.
  • Each field’s row has the id dffs_FieldInternalName; read-only fields have the class dffs-readonly. The styling page lists the rest.