Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

March 25, 2021

[Nintex Form]: How to setup auto populate value in dropdown

INTRODUCTION

We need to implement autocomplete dropdown feature using Nintex form in SharePoint 2019 custom list for hospitality company based out Saudi Arabia. Client has already acquired Nintex forms license for customizing SharePoint forms and wanted to set autocomplete dropdown feature for department field in Nintex form.

PROBLEM

Nintex form does not provide OOTB autocomplete dropdown control which can be utilized to meet client requirement. So, we thought of an alternate approach by setting "Department" field as lookup column in SharePoint custom list and set that column as dropdown in Nintex form, but the issue is lookup column also does not have auto suggest functionality.

SOLUTION

Nintex form provides an option to inject custom jQuery in Nintex forms. So, finally, we have decided to use custom jQuery Auto-complete combo box in Nintex form to achieve autocomplete dropdown functionality.

In the Nintex form, we need to set label control and inside that rendering the jQuery auto-complete combo box component programmatically. Also, we've implemented Ajax call to get list of department values from SharePoint list and binds to jQuery combo box component. To store selected values from combo box to SharePoint list, we've used other single line of text field in the Nintex form and set the selected values from the control to this field on save button click. We've hide the control using jQuery when form loads.

PROCESS

Step 1: Open Nintex Forms

Go to the list where you want to integrate this Nintex form, click on the list and select Nintex Forms.

Here, we have SharePoint custom list having column named Department with single line of text type.



Step 2: Setup Default Department.

You can see the default form already setup here; and we need to hide the department column that was already set with single line of text. It can be implemented using custom jQuery.

To open setting of this control, Select and open control setting from the top left side of the page.


It will open the control setting page, expand the formatting tab, Here, we need to add "formDepartmentField" class for both Control CSS class and CSS class.


Step 3: Setup Dropdown.

Now, We need to set our dropdown control in the label field. And to do that, we need to first add a label control in the Nintex form from left side panel.


Double click on the label OR click on Control setting, will open Control Settings - Label window.



Expand the Formatting tab, In CSS class, add “autoChoiceBox” class for custom dropdown and 

nf-form-input nf-section” class to apply CSS. Click on Save button.


Step 4: Setup Submit button.

Open submit button control setting and expand the Advance tab.


Now, on Client click, we have to write code for validation and store value from department field to SharePoint list. It can be achieved using custom jQuery.

Add below code in the Client click field.


 NWF$(document).ready(function () {  
 if (NWF$('.custom-combobox-input').val() == "") {  
 NWF$('.custom-combobox-input').addClass('nf-error-highlight');  
 } else {  
 NWF$('.custom-combobox-input').removeClass('nf-error-highlight');  
 }  
 NWF$(NWF$(".formDepartmentField").find('input')[0]).val($('.custom-combobox-input').val());  
 });  

The code must be written only on submit button client click event.

Step 5: Apply jQuery and Give code reference path.

Click on the form setting to apply CSS and custom jQuery code.


Expand Advanced tab, in Custom JavaScript Include section, set reference URLs of JS files containing our custom code, Here, we have stored these files in a Style library.

For Autocomplete dropdown, we need to add one jQuery plug-in called jQuery UI (1-12-1)

Reference URL for jQuery UI:- http://jqueryui.com/resources/download/jquery-ui-1.12.1.zip

We need to download it from the jQuery site and uploaded it to Style library. The path of this file must be added prior to our custom JS file link added in "Custom JavaScript Includes section as shown above.

Add below code for autocomplete dropdown in the script file - INF_Autocomplete.js and Save the changes.

 NWF$(document).ready(function () {  
   NWF$("#s4-ribbonrow").attr("style", "display:none !important;");  
 });  
 var userDep = "";  
 NWF.FormFiller.Events.RegisterAfterReady(function () {  
   var isNewMode = document.location.pathname.indexOf("/NewForm.aspx") >-1;  
   var isDisplayMode = document.location.pathname.indexOf("/DisplayForm.aspx") >-1;  
   NWF$('.nameOfUser').change(function () {  
     var userName = NWF$("[data-val]").attr("data-val");  
     if (userName) {  
       var userName2 = userName.slice(7);  
       var userName1 = userName2.replace("\\", "\\\\");  
       var valToSet = onUserNameChange(userName2);  
 setValToDropdown(valToSet);  
       NWF$('.custom-combobox-input').val(valToSet);  
     }  
   });  
 userDep = getUserDepartment();  
   var htmlForCombo = '<div class="ui-widget"><select id="combobox"><option value>Select one...</option></select></div>';  
   NWF$('.autoChoiceBox').html(htmlForCombo);  
   var allDep = getDepartmentData();  
   var departmentArray = [];  
 allDep.forEach(function (item, index) {  
 departmentArray.push(item.DepartmentName);  
     NWF$('#combobox').append(NWF$('<option>', {  
       value: item.DepartmentName,  
       text: item.DepartmentName  
     }));  
   });  
   if (isNewMode) {  
 setValToDropdown(userDep);  
   } else {  
     var valToSet1 = NWF$(NWF$(".formDepartmentField").find('input')[0]).val();  
 setValToDropdown(valToSet1);  
   }  
   if (isDisplayMode) {  
 setTimeout(function () {  
       NWF$('.ui-widget').attr("disabled", "disabled");  
       NWF$('a.ui-button').unbind('click').removeAttr('title');  
     }, 100);  
   }  
   NWF$(function () {  
 NWF$.widget("custom.combobox", {  
       _create: function () {  
 this.wrapper = NWF$("<span>").addClass("custom-combobox").insertAfter(this.element);  
 this.element.hide();  
         this._createAutocomplete();  
         this._createShowAllButton();  
       },  
       _createAutocomplete: function () {  
         var selected = this.element.children(":selected"),  
           value = selected.val() ? selected.text() : "";  
 this.input = NWF$("<input>").appendTo(this.wrapper).val(value).attr("title", "").addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left").autocomplete({  
           delay: 0,  
 minLength: 0,  
           source: NWF$.proxy(this, "_source")  
         }).tooltip({  
           classes: {  
             "ui-tooltip": "ui-state-highlight"  
           }  
         });  
 this._on(this.input, {  
 autocompleteselect: function (event, ui) {  
 ui.item.option.selected = true;  
 this._trigger("select", event, {  
               item: ui.item.option  
             });  
           },  
 autocompletechange: "_removeIfInvalid"  
         });  
       },  
       _createShowAllButton: function () {  
         var input = this.input,  
 wasOpen = false;  
         NWF$("<a>").attr("tabIndex", -1).attr("title", "Show All Items").tooltip().appendTo(this.wrapper).button({  
           icons: {  
             primary: "ui-icon-triangle-1-s"  
           },  
           text: false  
         }).removeClass("ui-corner-all").addClass("custom-combobox-toggle ui-corner-right").on("mousedown", function () {  
 wasOpen = input.autocomplete("widget").is(":visible");  
         }).on("click", function () {  
 input.trigger("focus"); /*Close if already visible*/  
           if (wasOpen) {  
 return;  
           } /*Pass empty string as value to search for, displaying all results*/  
 input.autocomplete("search", "");  
         });  
       },  
       _source: function (request, response) {  
         var matcher = new RegExp(NWF$.ui.autocomplete.escapeRegex(request.term), "i");  
         response(this.element.children("option").map(function () {  
           var text = NWF$(this).text();  
           if (this.value&& (!request.term || matcher.test(text))) return {  
             label: text,  
             value: text,  
             option: this  
           };  
         }));  
       },  
       _removeIfInvalid: function (event, ui) {  
         /*Selected an item, nothing to do*/  
         if (ui.item) {  
 return;  
         } /*Search for a match (case-insensitive)*/  
         var value = this.input.val(),  
 valueLowerCase = value.toLowerCase(),  
           valid = false;  
 this.element.children("option").each(function () {  
           if (NWF$(this).text().toLowerCase() === valueLowerCase) {  
 this.selected = valid = true;  
             return false;  
           }  
         }); /*Found a match, nothing to do*/  
         if (valid) {  
 return;  
         } /*Remove invalid value*/  
 this.input.val("");  
 this.element.val("");  
 this.input.autocomplete("instance").term = "";  
       },  
       _destroy: function () {  
 this.wrapper.remove();  
 this.element.show();  
       }  
     });  
     NWF$("#combobox").combobox();  
   });  
   NWF$('.formDepartmentField').hide();  
 });  
 function getUserDepartment() {  
   var dataToReturn = "";  
   var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";  
   $.ajax({  
     url: reqUrl,  
     type: "GET",  
     headers: {  
       "accept": "application/json;odata=verbose"  
     },  
     async: false,  
     success: function (data) {  
       if (data.d&&data.d.UserProfileProperties&&data.d.UserProfileProperties.results) {  
 dataToReturn = data.d.UserProfileProperties.results[11].Value;  
       }  
     }  
   });  
   return dataToReturn;  
 }  
 function getDepartmentData() {  
   var dataToReturnDep = [];  
   var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Lists%20Of%20Departments')/items?$select=DepartmentName&$top=1000";  
   $.ajax({  
     url: reqUrl,  
     type: "GET",  
     headers: {  
       "accept": "application/json;odata=verbose",  
       "content-type": "application/json;odata=verbose"  
     },  
     async: false,  
     success: function (data) {  
       if (data &&data.d&&data.d.results) {  
 dataToReturnDep = data.d.results  
       }  
     }  
   });  
   return dataToReturnDep;  
 }  
 function onUserNameChange(dataFun) {  
   var dataToReturn = "";  
   var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='" + dataFun + "'";  
   $.ajax({  
     url: reqUrl,  
     type: "GET",  
     headers: {  
       "accept": "application/json;odata=verbose"  
     },  
     async: false,  
     success: function (data) {  
       if (data.d&&data.d.UserProfileProperties&&data.d.UserProfileProperties.results) {  
 dataToReturn = data.d.UserProfileProperties.results[11].Value;  
       }  
     }  
   });  
   return dataToReturn;  
 };  
 function setValToDropdown(valueToSet) {  
   NWF$('#combobox').val(valueToSet);  
   NWF$('#combobox').change();  
 };  

Step 6: Apply CSS.

On form setting, expand the Custom CSS tab.



You can add below code for designing the dropdown as per business need.

 .nf-form-input {       
   border: 1px solid #d4dbe0;  
 }  
 .nf-form-label .nf-filler-control-inner{    
   top: 1px;  bottom: 1px; line-height: 1.2;  
 }  
 .custom - combobox - input {  
   width: 90 %  
 }  
 .custom - combobox {  
   padding: 10 px;  
 }.custom - combobox {  
   height: 34 px; margin: 10 px; padding: 0 px; display: block; border: 1 px solid #ababab;  
 }.custom - combobox> input {  
   height: 29 px; background: #ffffff; border: 0 px; margin - top: 2 px!important; width: 93 % ;  
 }       

Conclusion

This is how Autocomplete dropdown cab be setup in Nintex Form.

 If you have any questions you can reach out our SharePoint Consulting team here.

June 16, 2017

How to escape a special character in filter parameter using REST API

Scenario: 
Recently working with REST API to get items from SharePoint list filtered by title field, I got stuck. it was working fine while having data without special character. But having special character - single quote/apostrophe (') in filter parameter was giving an error. I tried by passing value using EncodeURIComponent, but it didn't work either and getting the error as shown below:


Reason: 
EncodeURIComponent, Escape or EncodeURI functions can’t escape few special characters: - _ . ! ~ * ' ( )
 
Solution:
For such special characters as filter parameter, we should double the character (2 single quotes) and use it.

Example:
Non-working REST API:
https://{Site URL} /_api/web/lists/GetByTitle('listname')/items? select=ID&$filter=Title eq 'what's up'

Working REST API:
https://{Site URL} /_api/web/lists/GetByTitle('listname')/items? select=ID&$filter=Title eq 'what''s up'

If you have any questions you can reach out our SharePoint Consulting team here.

July 28, 2016

Client Side People Picker with JSOM in Office 365/SharePoint 2013

Requirement:
In one of the project, I had a requirement to use people picker in Client side HTML which should have same features as SharePoint OOTB people picker provides.

PeoplePicker.png

Approach/Solution:
Follow below steps to achieve client side people picker functionality using JSOM.

1. Below mentioned JS files are required to load client side people picker using JSOM. All
JS
files are OOTB SharePoint JS files which are available under "_layouts/15" folder in
SharePoint.
- clienttemplates.js
- clientforms.js
- clientpeoplepicker.js
- autofill.js
- sp.js
- sp.runtime.js
- sp.core.js
2. Put reference of all JS files into HTML file for which you want to create Client Side People
Picker.
3. Add below Div tag in your HTML file.
<div id="peoplePickerDiv"></div>
4. Add below code in your custom JS file (custompeoplepicker.js) and also put reference of this file into HTML file.
        // Initialize People Picker.   
 $(document).ready(function() {  
 // Specify the unique ID of the DOM element where the  
 // picker will render.  
 initializePeoplePicker('peoplePickerDiv');  
  });  
 // Render and initialize the client-side People Picker.  
 function initializePeoplePicker(peoplePickerElementId) {  
  // Create a schema to store picker properties, and set the properties.  
  var schema = {};  
  schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
  //This value specifies where you would want to search for the valid values
  schema['SearchPrincipalSource'] = 15;             
  //This value specifies where you would want to resolve for the valid values
  schema['ResolvePrincipalSource'] = 15;  
schema['AllowMultipleValues'] = true;  
  schema['MaximumEntitySuggestions'] = 50;  
  schema['Width'] = '280px';  
  // Render and initialize the picker.  
// Pass the ID of the DOM element that contains the picker, an array of initial   
// PickerEntity objects to set the picker value, and a schema that defines  
// picker properties.    
this.SPClientPeoplePicker_InitStandaloneControlWrapper(
peoplePickerElementId, null, schema);  
                        }
                         // Get user information from client side people picker.
  // Query the picker for user information.

 function getUserInfo() {
  // Get the people picker object from the page.
  var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
for (var i = 0; i < users.length; i++) {
var user = users[i];
for (var userProperty in user) {
userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
}
}
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
// Get the first user's ID by using the login name.
getUserId(users[0].Key);
}
// Get the user ID.
function getUserId(loginName) {
var context = new SP.ClientContext.get_current();
this.user = context.get_web().ensureUser(loginName);
context.load(this.user);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccess),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccess() {
console.log(this.user.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}

// Below code sets values into client side people picker.
var divPeople = SPClientPeoplePicker.SPClientPeoplePickerDict.PeoplePickerDiv_TopSpan;
PeoplePickerDiv_TopSpan - Specify the unique ID of the DOM element where the picker will render.
var userObj = { 'Key': "sample@sample.com" };
divPeople.AddUnresolvedUser(userObj, true);

If you have any questions you can reach out our SharePoint Consulting team here.

January 7, 2013

Tabs in SharePoint 2010 Using Jquery

First Create Simple aspx page in Sharepoint Designer. Add two placeholder First one additional page head Its holding any css and jQuery Scripts. Second one "> Place the Css and jQuery Script in additional Head Here is Script and Css :
Note: you have to give​ jquery.js file reference in head

<script type="text/javascript" src="/Style Library/js/jquery.js"></script>

Tab Structure :

<ul class="div-nav">
<li class="choice show-hs activated">High School</li>
<li class="choice show-ms">Middle School</li>
<li class="choice show-es">Elementary School</li>
</ul>
Hide and Show Div Structure :

<div class="content">
<div class="calendar">
<div class="webpart hs"></div>
​<div class="webpart ms"></div>
​​​<div class="webpart es"></div>
</div></div>

Additional Script :

For Hide All Divs.
 
    $("#daily-wrapper .webpart").hide();
 
Show First Div when loading page.
 
   $("#daily-wrapper .hs").fadeIn('slow');
 
Tab Selected Class.
 
   $("ul.div-nav li.choice").click(function(){$(this).toggleClass("activated")});
 
Remove Class when other one select.
 
   $("ul.div-nav li.choice").click(function(){$(this).siblings('ul.div-nav li').removeClass('activated')});
Here is the Full Code
you have to add Style & script in additional Head :

<style type="text/css">
#daily-wrapper{ border:solid 4px#999;width:500px;}
#daily-wrapper ul.div-nav li {font-size:1.2em;margin:0px;border-right:1px solid #fff;}
#daily-wrapper .calendar {position:relative;border:0px solid #333;float:left;}
#daily-wrapper .calendar {margin-right:19px;}
#daily-wrapper .content .calendar h2 {color:#000;margin-bottom:20px;}
ul.div-nav {width:100%;background:#999;float:left;text-align:center;padding:0px;margin:0px;}
ul.div-nav li {display:block;float:left;color:#fff;text-decoration:none;padding:10px;}
ul.div-nav li:hover {background:#b80000;cursor:pointer;}
ul.div-nav li.activated {background:#b80000;}
</style>


<script type="text/javascript">
$("ul.div-nav").ready(function(){
 
 $("#daily-wrapper .webpart").hide();
 $("#daily-wrapper .hs").fadeIn('slow');
 $("ul.div-nav li.choice").click(function(){$(this).toggleClass("activated")});
 $("ul.div-nav li.choice").click(function(){$(this).siblings('ul.div-nav li').removeClass('activated')});
 $("ul.div-nav li.choice").click(function(){$("#daily-wrapper .webpart").fadeOut('fast')});
 $("ul.div-nav li.show-hs").click(function(){$("#daily-wrapper .webpart.hs").fadeIn('slow')});
 $("ul.div-nav li.show-ms").click(function(){$("#daily-wrapper .webpart.ms").fadeIn('slow')});
 $("ul.div-nav li.show-es").click(function(){$("#daily-wrapper .webpart.es").fadeIn('slow')});
 
}); 
</script>

Structure :

<div id="daily-wrapper">
<ul class="div-nav">
<li class="choice show-hs activated">High School</li>
<li class="choice show-ms">Middle School</li>
<li class="choice show-es">Elementary School</li>
</ul>
<div class="content">
<div class="calendar">
<div class="webpart hs">
<h2>div first</h2>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
<div class="webpart ms">
<h2>div Secoond</h2>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
 
</div>
<div class="webpart es"><h2>div Third</h2>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</div>
</div>
</div>
</div>

If you have any questions you can reach out our SharePoint Consulting team here.