JavaScript framework basics of SharePoint Forms

On this page, you will find information about the form’s global variables, properties, methods, and events.

Globals

Framework variables are available globally and can be used directly from the JavaScript editor.

Tip

Add variable to the global window to make it available in the browser’s console:

window.fd = fd;
window.$ = $;

fd.spRendered(function() {
    //your custom code
});

fd

fd is a Form Manager that provides access to all events, containers, controls, fields, validators, and data of the form.

Whenever you want to manipulate your form, you must call the manager first.

// the form is ready
fd.spRendered(function() {
    // and its fields are available to get/set value
    fd.field('Title').value = 'New Title';
});

$

$ allows you to access jQuery library. It can be used to apply direct changes to DOM, hide and show fields, and much more.

// hide fields by CSS class
$('.field-to-hide').hide();

// change input background color
$(fd.field('Field1').$el).find('input').css('background-color', 'red');

Dialog

Allows to open any other form in dialog, pass parameters to it, detect if it was saved or not, and pass parameters back.

var listId = 'fc0bff2b-b78c-4aad-956d-b58af48b45fd';

//open New form in a dialog
Dialog.open('https://contoso.sharepoint.com/sites/mysite/_layouts/15/listform.aspx?PageType=8&ListId=' + listId, { args: 'something' });

Learn more about how to work with the Dialog variable in the Manage dialog window article.

pnp

PnPjs library for SharePoint REST services (within current site)

//get all items from a list
pnp.sp.web.lists.getByTitle('List Name').items.get().then(function(items){
    //log all items in the browser console
    console.log(items)
})

Web

Allows to create Web instances directly using with the URL to use as a base.

//specify your site URL
var siteURL = 'https://contoso.sharepoint.com/sites/Main/data';
let web = new Web(siteURL);

Site

Allows to create Site instances directly using with the URL to use as a base.

//specify your site URL
var siteURL = 'https://contoso.sharepoint.com/sites/Main/data';
let site = new Site(siteURL);

graph

Microsoft Graph API for calling Microsoft Graph rest services.

//get curent user profile information
graph.me().then(function(props) {
    console.log(props)
});

Find more code examples of getting user profile properties information here.

Properties

The global variable fd has the following properties:

itemId

Returns SharePoint item ID.

fd.itemId; //'15'

formId

Gets the ID of the form.

fd.formId; // 'b5257750-2483-4bea-ac1a-79ad7c670756'

formType

Returns the form type as a string.

fd.formType; // 'Display'

listUrl

Gets relative pass of the SharePoint list.

fd.listUrl; // '/Lists/Projects'

source

Gets the URL of the SharePoint list view.

fd.source; // 'https://contoso.sharepoint.com/sites/Main/Lists/Projects/AllItems.aspx'

spFormCtx

Returns an object that holds information about the current item and the SharePoint list.

//return all columns with values as an object
fd.spFormCtx.ListData

//return the SharePoint list ID as a string
fd.spFormCtx.ListAttributes.Id

culture

Gets the current culture name.

fd.culture; // 'en-US'

language

Gets the current language of the form.

fd.language; // 'en-US'

isValid

Checks if the form is valid or not.

Each time the property is called, it runs validators on all form elements recursively.

Returns true on success. Otherwise, returns false and error messages get displayed.

fd.isValid;

validators

Gets an array of form validators. Can be used to add new ones. These are more complex validators than Field validators and are used to check that multiple fields have appropriate values. If the fields do not match these criteria, the form will not submit.

// return form validators
fd.validators;

// add new form Validator
fd.validators.push({
    name: 'MyCustomValidator',
    error: 'Age must be 18 or over in order to subscribe',
    validate: function(value) {
        if (fd.field('Age').value < 18
            && fd.field('PaymentModel').value === 'Subscription')
            return false;

        return true;
    }
});

_vue

Get VueJS component of the form, so you can examine or modify it.

fd._vue;

messages

Gets language constants as an object. Can be used to set text for localization.

To change language constant, call the property inside fd.created event:

fd.created(function(vue) {
    fd.messages.PlumsailForm_Submission_Success = 'Thank you!';
});

pdfFileName

Get or set the name of the exported PDF file.

//set file name to current item's Title
fd.pdfFileName = fd.field('Title').value;

pdfOptions

Specifies various options for exported PDF file, such as paper size, margin, orientation, etc. More info about all the options here.

fd.pdfOptions = {
    paperSize: 'A4',
    landscape: true,
    multiPage: true
};

toolbar

Property holds parameters of the form toolbar.

fd.toolbar;

Learn more about customizing the form toolbar here.

Methods

fd has the following methods:

save

Saves the form.

fd.save();

data

Gets data from all fields on the form. Can be also used to set multiple values at the same time.

// get data as an object
fd.data();
// set field values
fd.data({Field1: value1, Field2: value2});

field

Returns a field by its Name.

fd.field('Field1')

fields

Returns all fields available on the form.

fd.fields();

control

Returns a control by its Name.

fd.control('Control1')

controls

Returns all controls available on the form.

fd.controls();

container

Returns a container by its Name.

fd.container('Container1')

containers

Returns all containers available on the form.

fd.containers();

clear

Clears the form.

fd.clear();

exportToPDF

Exports the current form to a PDF file. Accepts the following arguments:

file – a filename of the file.

options – options for the PDF file, such as paper size, margin, orientation, etc.

fd.exportToPDF('contacts-form', {
    paperSize: 'A4',
    landscape: false,
    multiPage: true
});

Find more about PDF options in How to save form as PDF for printing.

Events

The global variable fd has the following events:

beforeCreate

Occurs prior to the form creation.

vueConfig passed as an argument to the handler is a configuration of the main vue-component. You can register your own child components. You can read more about it here.

Asynchronous event

Can return a Promise and the corresponding operation will not continue until the promise is resolved.

fd.beforeCreate(function(vueConfig) {
    console.log('beforeCreate');
    console.log(vueConfig);
});

created

Occurs as soon as the form is created.

vue passed as an argument to the handler is a Vue instance of the form.

It is also available from fd variable this way: fd._vue

fd.created(function(vue) {
    console.log('created');
    console.log(vue);
});

spBeforeRender

Occurs before mounting the vue-component to DOM.

vue passed as an argument to the handler is a Vue instance of the form.

It is also available from fd variable this way: fd._vue

Asynchronous event

Can return a Promise and the corresponding operation will not continue until the promise is resolved.

fd.spBeforeRender(function(vue) {
    console.log('beforeRender');
    console.log(vue);
});

spRendered

Occurs after mounting the vue-component to DOM.

Best place to run your JavaScript since all elements are mounted.

vue passed as an argument to the handler is a Vue instance of the form.

It is also available from fd variable this way: fd._vue

fd.spRendered(function(vue) {
    console.log('rendered');
    console.log(vue);
});

spBeforeSave

Occurs before submitting the form.

spForm passed as an argument to the function is a SharePoint client form.

Here, you can modify form’s data with code before sending it to the server.

Asynchronous event

Can return a Promise and the corresponding operation will not continue until the promise is resolved.

fd.spBeforeSave(function(spForm) {
    console.log('spBeforeSave');
    console.log(spForm);
});

//async check
fd.spBeforeSave(function() {
    return new Promise(function(resolve, reject) {
        // do something async
        resolve();
    });
});

//async check with pnpjs
fd.spBeforeSave(function() {
    return pnp.sp.web.lists.getByTitle('FieldTestList').items.getById(1).get().then(function(item) {
        console.log(item);

        if(item.Title == fd.field('Title').value) {
            throw new Error('Title is invalid!');
        }
    });
});

spSaved

Occurs after the data is submitted.

Can be used to display confirmation messages after the form is saved or perform some other actions.

result passed as an argument to the function. It is an object that contains additional fields of the SharePoint item:

  • Id — returns the ID of the item.

  • FileLeafRef — returns the name of the document or document set.

  • RedirectUrl - holds the URL of a page where a user will be redirected after saving. This field can be changed. RedirectUrl is ignored inside a panel.

fd.spSaved(function(result) {
    console.log('spSaved');
    console.log(result);
});