SPJS-Autocomplete

This page show all configuration options for the Autocomplete plugin for DFFS.

Last modified: July 30, 2023

What does it do?

This DFFS plugin lets you convert a single line of text field or a plain text multiline field (when using the “multichoice” option) into an autocomplete lookup column.

The function call is placed in the Custom JS tab in DFFS backend.

Please note that the value are stored as plain text in this field, and the values will NOT be linked to the original lookup item like in the built-in SharePoint lookup column.

This means that if you change the original lookup item, it will NOT update the value stored in the items that has already been saved to the database.

You can also use this plugin to create an autocomplete poeple picker in SharePoint 2010.

Images

Empty autocomplete

Single select autocomplete

Selected a valid option

Typed in an invalid option

Multiselect autocomplete

Selected options

Remove selections

Autocomplete in a text field

Example function call placed in Custom JS

spjs.ac.textField({
 "applyTo": "",
 "helpText": "",
 "loadText": "",
 "listGuid": "",
 "listBaseUrl": "",
 "showField": "",
 "searchFields": [],
 "filterCAML": "",
 "useREST": false,
 "preloadData":false,
 "filterREST": "",
 "optionDetailFields": [],
 "optionDetailPrefix": [],
 "enforceUniqueValues": true,
 "rowLimit": 15,
 "listOptionsOnFocus": false,
 "minLengthBeforeSearch": 3,
 "reValidateOnLoad": false,
 "allowAddNew": false,
 "addToFolder": null, "isLookupInSelf": false, "addNewAdditionalFields": [], "multiselect": false, "multiselectSeparator": "; ", "orderBy": [], "clearSetFieldsOnInvalidSelection": false, "setFields": [], "debug": false });

Configuration options explained

applyTo

Type: string

The FieldInternalName of the single line of text field to add autocomplete functionality to.

helpText

Type: string

The placeholder text in the autocomplete field when it is empty.

loadText

Type: string

Used with large REST datasets in combination with multiple searchFields to show a message when waiting for the data to load

listGuid

Type: string

The list GUID or the display name of the list you are pulling the options from. If you use different language packs and translate the list display name you must use the list GUID as identifier.

To find the list GUID, go to a list view or form in the source list, hit F12 to bring up the developer tools, select “Console” and type in this text:

_spPageContextInfo.pageListId

This will show you the list GUID in this format:

"{ea2a814f-3e82-467c-9c51-d2c98beacfa7}"

listBaseUrl

Type: string

The listBaseUrl of the source list. Go to the source list and look a the address field in your browser. For a subsite named “testsite”, this is the correct listBaseUrl :

/testsite

For the root site, use an empty string like this:

""

In case you have your site on a managed path, the listBaseUrl will most likely be like this:

/sites/testsite

You can find the listBaseUrl  the same way as you got the GUID. Go to a list view or form in the source list, hit F12 to bring up the developer tools, select “Console” and type in this text:

_spPageContextInfo.webServerRelativeUrl

showField

Type: string

This is the field to search by and show in the autocomplete text box. If you want to search by for example both a project name and number, you must create a calculated field in your source list that concatenates these values and then use this calculated fields here.

searchFields

Type: array of strings

Optional field to let you search in multiple fields in the dataset while showing a single field value in the “showField”.

filterCAML

Type: string

Prefilter the dataset with a CAML query. This example show all items where the loggen in user is the Author:

"filterCAML":"<Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'><UserID/></Value></Eq>"

You can use {function:yourCustomFunction} to get a “live” filter value for each search. This setup requires you to have a function in the Custom JS with the name specified in the filterCAML parameter, and this function must return a properly formatted CAML query.

useREST

Type: boolean

Only for SP2013+

Uses an asynchronous REST query to get the items.

preloadData

Type: boolean

Only for SP2013+

Used with the above “useREST” to ensure all data is preloaded for better search perfomance. Using this setting will also give you two more filter options in addition to the default method where space between two or more text strings means “and”:

  • Use double quotes around a string to match the exact text.
  • Use upper case “OR” between two search strings to use “or”.

filterREST

Type: string

Prefilter the dataset with a REST query.

You can use {function:yourCustomFunction} to get a “live” filter value for each search. This setup requires you to have a function in the Custom JS with the name specified in the filterREST parameter, and this function must return a properly formatted REST filter – like this example that selects all items where Title starts with the letter “t”:

startswith(Title,'t')

optionDetailFields

Type: array of strings

Additional fields to show more details in the drodown. These fields are information that ensures the user picks the correct item from the dropdown, but this additional information will not be saved in the automplete field when you save the form.

You can however use the “setFields” functionality to pull these values from the selected option and write then to one or more fields in the list item.

optionDetailPrefix

Type: array of strings

Optional prefix for the fields in “optionDetailFields”. If  for example “optionDetailFields” is specified as [“ProjectNumber”, “Responsible”] you would use this in the optionDetailPrefix parameter: [“Project number: “, “Responsible: “].

The length of this array must be the same as “optionDetailFields”

enforceUniqueValues

Type: boolean

Determines whether or not to show only unique values from the lookup list.

rowLimit

Type: integer

This is the max number of items to pull back. Use a low number to keep the query lightweight.

listOptionsOnFocus

Type: boolean

Determines whether or not to pull in the first batch when the field gets focus. Setting this to true will mimic a dropdown with an arrow to the right.

minLengthBeforeSearch

Type: integer

This settings controls how many characters the user needs to enter before the search is triggered.

reValidateOnLoad

Type: boolean

This setting does not apply if you use the “multiselect” option below.

Determines whether or not to validate the selection when opening the list item in EditForm by running a query against the source list to ensure the selection is still valid.

If this is set to true, you cannot have duplicates in the lookup list as this will not validate because it doesn’t find an exact match.

If you delete an item in the lookup list, the selected value will be invalid.

allowAddNew

Type: boolean

Determines whether or not to allow adding new values to the “dataset”. If you set the below “isLookupInSelf” parameter to false, you MUST use the GUID in the parameter “listGuid” above.

addToFolder

Type: object or null

New in v1.6.45

If you use “allowAddNew” and not “isLookupInSelf” and you want items to be added to a specific folder you can specify it like this:

"addToFolder": {"rootFolder":"/Sites/ProjcetSite/Lists/ProjectList", "folderName": "Folder A"},

You can use a variable instead of the “Folder A” text, and if that folder does not exist it will be automatically created the first time someone tries to add an item to it.

isLookupInSelf

Type: boolean

This setting is used with the “allowAddNew” parameter. This specifies whether or not the autocomplete is a lookup in the the current list.

Please note that using “allowAddNew” with “isLookupInSelf” set to false is only supported in SharePoint 2013.

addNewAdditionalFields

Type: array of objects

{
 "fromFIN":"ProjectNumber",
 "toFIN":"PNumber"
},
{
 "fromFIN":"Created",
 "toFIN":"ProjectCreatedDate"
}

multiselect

Type: boolean

Use this to enable selecting multiple items.

multiselectSeparator

Type: string

When using “multiselect” = true your choices will be separated by this character. The default value is a semicolon.

orderBy

Type: array of objects

The field you want to order the options by.

[{
"fin": "Created",
"ascending": true,
"numeric": true,
"parseFunction": ""
}]

fin is the FieldInternalName, and ascending is either true or false. The numeric option is new in v1.6.38 and lets you sort numerical and not alphabetical on number fields like ID or another number column.

The parseFunction option is new in v1.6.42 and can be used like this:

Add this to your spjs.ac function call.

[{
"fin": "Created",
"ascending": true,
"numeric": true,
"parseFunction": "parseDate"
}]

Then add this to your Custom JS over the spjs-ac function call.

function parseDate(str, fin) {
var r = str;
if (str !== null) {
r = new Date(str.split(" ").join("T")).valueOf();
}
return r;
}

clearSetFieldsOnInvalidSelection

Type: boolean

This setting determines whether or not to clear the setFields when interacting with the applyTo field and not selecting a valid option.

setFields

Type: array of objects

{
 "fromFIN":["ProjectNumber"],
 "joinBy":"",
 "toFIN":"PNumber",
 "parseFunction":"",
 "skipIfEmpty":false
},
{
 "fromFIN":["Created"],
 "joinBy":"",
 "toFIN":"DateColumn1",
 "parseFunction":"",
 "skipIfEmpty":false
}

This in an array of objects containing additional fields to pull in and set based on the selection. It has these properties:

  • fromFIN: The FieldInternalName of the field in the list you are pulling from. If you use an array of fields, they are concatenated into a string and adde to the field specified in the “toFIN”.
  • joinBy: Used in case the “fromFIN” is an array and specifies the value to join the values from the fields. Use “<br>” if you write the value to a rich text multiline field, or “\n” if you write it to a plain text multiline field.
  • toFIN: The FieldInternalName of the field in the list you are writing to.
  • parseFunction: This is used to parse the returned value before inserting it in the “toFIN” field. See example on parsing a date value in the change log in the top of this page (February 19, 2016).
    function parseDateFunc(a, fin){
     // Set the desired format in the variable "f"
     var f = "MM/dd/yyyy hh:mm" , d = new Date(a);
     f = f.replace("MM",(d.getMonth()+1) < 10 ? "0"+(d.getMonth()+1) : (d.getMonth()+1));
     f = f.replace("dd",d.getDate() < 10 ? "0"+d.getDate() : d.getDate());
     f = f.replace("yyyy",d.getFullYear());
     f = f.replace("yy",d.getFullYear().toString().substring(2));
     f = f.replace("hh",d.getHours() < 10 ? "0"+d.getHours() : d.getHours());
     f = f.replace("mm",d.getMinutes() < 10 ? "0"+d.getMinutes() : d.getMinutes());
     return f.split(/ |:/);
    }
  • skipIfEmpty: true or false determines whether or not to omit this option if this field is empty.

debug

Type: boolean

If you have trouble setting up this plugin you can set this parameter to true to show debug information.

Autocomplete in a people picker

This is not intended used in SP 2013 or SharePoint online because you already have an autocomplete people picker. You can however use the “forceOn2013” if you want to use it.

Please note that this does NOT support multi choice people pickers.

spjs.ac.peoplePicker({
 "applyTo":"Responsible",
 "forceOn2013":false,
 "helpText":"Enter name or email address...",
 "showField":"Title",
 "enforceUniqueValues":true,
 "chooseFromUserGroup":"",
 "showUsersOnly":true,
 "rowLimit":5,
 "listOptionsOnFocus":false,
 "reValidateOnLoad":false,
 "setFields":[]
});

Options explained

The shared options are explained in the previous section.

forceOn2013

Type = boolean

If you want to use this autocomplete on a peoplepicker in SP 2013 you must set this to true.

chooseFromUserGroup

Type = number or string or array of number or string (from v 1.6.49)

If you want to limit the selection to a specific user group, add the name or the ID here. The ID must be added as an integer. Leave as null to search all users. Please note that you cannot let the autocomplete search among all users while the people picker itself (in the list settings) is restricted to a certain group.

Add multiple values in an array format if you like to search more than one group.

showUsersOnly

Type = boolean

Determines whether or not to show users and groups, or users only.

Override the labels and text

Add this to the CustomJS above the function call to spjs.ac.peoplePicker or spjs.ac.textField to override the standard texts. Translate as you like.

spjs.ac.text = {
 "noItems":"No items match your search",
 "addNewItem":"Add {0} to the list?",
 "noValidItems":"No valid items match your search",
 "invalid":"Invalid value",
 "moreItemsLabel":"Showing the first {0} items",
 "moreItemsMouseover":"Continue typing to narrow your search",
 "searching":"Searching for: "
};

Remove the autocomplete

You can destroy / remove the autocomplete functionality by calling this if Custom JS:

spjs.ac.destroy("FieldInternalNameOfField");

Set the value in the autocomplete programatically

In v1.6.33 released with DFFS verion 4.4.4.0 on July 21, 2019 I added a function to let you set the value of the autocomplete like this from Custom JS:

spjs.ac.setFieldValue("AutocompleteFieldInternalName","The_Selected_Value");

Add a callback function to Custom JS

New in v1.6.41

If you like to run some code when a valid, invalid or empty value is added, you can add these functions to your Custom JS:

function spjs_ac_validSelectionCallback(fin,val){
     console.log("valid:");
     console.log(fin+":"+val);
 }
 function spjs_ac_invalidSelectionCallback(fin,val){
     console.log("invalid:");
     console.log(fin+":"+val);
 }
 function spjs_ac_clearSelectionCallback(fin){
     console.log("clear:");
     console.log(fin);
 }

Alternative filter method for large lists

New in v1.6.54

If your list has over 5000 items and you cannot filter it in the query you can add these additional parameters to the function call: loadAdditionalFields and postPreloadFilterFn.

These new arguments requires that you set “preloadData”: true and “useREST”: true

The parameter loadAdditionalFields is used to add additional information to the data object that can be used in a filter function that runs after all data has been loaded. Use it like this:

"loadAdditionalFields": {"select": ["Author/Id"], "expand": ["Author"]}

The parameter postPreloadFilterFn is used to do the actual filtering after the data has been fetched from the list. It loops over all the items and applies the filter – returning true to keep and false to skip. Here is an example:

"postPreloadFilterFn": function(item){
  return item.Author.Id === _spPageContextInfo.userId; // Return true or false to include or exclude an item
}