Sunday, July 06, 2014

Create mandatory Form Popup for users when access SharePoint Site using REST

Hi all, 

This is a Sunday afternoon article about SharePoint on how we can create a mandatory form popup when a user opens a SharePoint Site.

The Idea behind is a common task in Business requests, Collect data for some type of reason and use SharePoint Portals for communication and collaboration since all users should use it for their daily work.

Here is the the final output of the Form Popup.



Architecture example for mandatory form popup



How to Configure 

This Solution is base in the following items:

  • SharePoint List "Contacts"
  • Files
    • Jquery.js
    • LoadForm.js
    • CustomForm.aspx
SharePoint List Contacts

Create a Out of the Box SharePoint List from type "Contacts", this list will be used to collect data from users from the Mandatory Form.




Include the Code to Load Mandatory Form Popup

The following code validates if the user fill out the Mandatory Form, if he didn't fill out a popup appears in all SharePoint page except the support page "CustomForm.aspx" where is located the Form Design.
Create a Javascript file call "LoadForm.JS" and include the following code.

****************Code Example****************
var path = window.location.pathname;
var page = path.split("/").pop();
var waitForm;
$(document).ready(function () {
//Validation of the Form Page to dont loop the modal Dialog
 if (page!=="CustomForm.aspx")
{
LoadCustomForm();
}
  });
function GetCurrentWebUrl() {
                return _spPageContextInfo.webServerRelativeUrl + ((_spPageContextInfo.webServerRelativeUrl.indexOf('/', _spPageContextInfo.webServerRelativeUrl.length - 1) !== -1) ? '' : '/');
}
function LoadCustomForm()
{
//Method to validate if user already add any item using REST
//Code from reference "Get list items created by logged in user with REST api"
getCurrentUser(function(userData){
$.ajax({
            url: GetCurrentWebUrl() + "_api/web/lists/GetByTitle('Contacts')/items?$select=Id&$filter=AuthorId eq '"+userData.Id+"'",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data){
if (data.d.results.length==0)
{
var options = {
title: "Welcome "+userData.Title ,
autoSize: true,
showClose:false,
url: GetCurrentWebUrl()+"SiteAssets/CustomForm.aspx" };
SP.UI.ModalDialog.showModalDialog(options);
}
},
            error: function (error){alert(error.status)}
        });
});
}
//Method to Add item in contact List by REST
function Save(Firstname,lastName){
ShowWaitForm();
var item = {
            "__metadata": { "type": 'SP.Data.ContactsListItem' },
            "FirstName": Firstname,
            "Title": lastName
        };
$.ajax({
            url: GetCurrentWebUrl() + "_api/web/lists/getbytitle('Contacts')/items",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function(data) {
CloseWaitForm();
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK);
            },
            error: function (error){alert(error.status);CloseWaitForm();}
        });
}
//Get Current User Info
function getCurrentUser(complete)
{    
$.ajax({
url: GetCurrentWebUrl() + "_api/web/currentUser?$select=Title,id",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data.d); 
},
  error: function (error){alert(error.status);CloseWaitForm();}
});
}

function ShowWaitForm() {
    if (waitForm == null) {
        waitForm = SP.UI.ModalDialog.showWaitScreenWithNoClose("Processing", "Your request is being processed. Please wait while this process completes.");
    }
}
function CloseWaitForm() {
    if (waitForm != null) {
        waitForm.close(0);
        waitForm = null;
    }
}

CustomForm

A support page was created for the Custom Form "CustomForm.aspxwhere is added the html design and files refences to support the Mandatory Form.



You can see the aspx example in the following Link: http://1drv.ms/1n3JgUZ .


Include Files in Site Assets

After the File "LoadForm.js" and Page "CustomForm.aspx" are created you can include in the support Library "Site Assets" .



Add ScripLink to support Files

I use the  RibbonManager App, to include the Scriplinks in the Host Web Site to became accessible in all SharePoint Pages.
If you like to use Visual Studio and Declarative code you can use the following XML.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="Global Jquery" Title="Global Jquery" Description="" Location="ScriptLink"ScriptSrc="~Site/SiteAssets/jquery-1.10.2.min.js" Sequence="1" > </CustomAction>
</Elements>

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="LoadForm" Title="LoadForm" Description="" Location="ScriptLink"ScriptSrc="~Site/SiteAssets/LoadForm.js" Sequence="2" > </CustomAction>
</Elements>

After this the ScripLinks are included. 
When the users accessed a SharePoint Page the Popup appear with the Mandatory Form.


After the content is created, you can access the List and validate if data is there, after that the Popup will not appear to end user.


Done, made in a very easy way, here a video will all the steps:



Support articles/links:
getCurrentUser Method

Hope you like this article,
Kind regards, 
André Lage

Post a Comment