Retrieving Various Field Types in SharePoint Custom Form using jQuery and SPServices

Ahamed Fazil Buhari
 
Senior Developer
July 5, 2016
 
Rate this article
 
Views
19095

Usage of having the custom form is that, we can do whatever we want i.e all the controls would be in our hand and we can easily modify the form, apply any conditions, and change the look and feel and many more.

First and foremost we need to know how to retrieve, populate and handle various field types available in the SharePoint list,

· Single Line of Text

· Multiple Line of Text

· Date

· People Picker

· Choice (Dropdown, Radio button, Checkbox)

· Lookup (Single and Multiple)

Let’s consider a List having all the types of columns which we mentioned above and the OOTB – New Form will be available as shown below,

clip_image002

To create a custom form using jQuery and SPServices, we need to have an empty aspx page (Pages -> aspx) or Web Part Page. Here, I’ve created an empty web part page as shown below using SharePoint Designer,

clip_image004

After the page creation, all the contents should be applied inside the ‘PlaceHolderMain’

<asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderMain" runat="server">

All your content goes here…

</asp:Content>

For ‘Single line of Text’ we can make use of,

<input type="text" ID="txtSingleLine" />

And for ‘Multiple line of text’,

<textarea id="txtMulti" placeholder="Enter Description…">

The rest of the operations on ‘Single line of Text’ and ‘Multiple line of Text’, I am leaving to the readers.

Let’s look into the other field types.

Date Column:

· In aspx page –

<input id="txtDate" type="text" />

· In JS file.

$(document).ready(function () {

$("#txtDate").datepicker({

dateFormat: ‘dd-M-yy’,

showOn: "button",

beforeShowDay: $.datepicker.noWeekends,

buttonImage: "../SiteAssets/images/calendar_icon.png",

});

});

Output:

clip_image006

Here, I’ve used the calendar_icon.png for icon and removed the weekends ($.datepicker.noWeekends).

For various operations on Date field, please refer jQuery User Interface

· To get the Date field value and changing the date format to ISOString format, so that it can be saved in SharePoint.

var date = $("#txtDate").datepicker("getDate") || ”;

//Converting Date format from dd-MMM-yyyy to ISOString format save in list

if (date != ”) {

var inputDate = new Date(date).toDateString();

var getCurrentTime = new Date().toLocaleTimeString();

var newDateTime = inputDate + " " + getCurrentTime;

date = new Date(newDateTime).toISOString();

}

People Picker Column:

· In aspx page use the below tag,

<SharePoint:PeopleEditor ID="ppVal" runat="server" MultiSelect="False" __MarkupType="xmlmarkup" WebPart="true"></SharePoint:PeopleEditor>

Output:

clip_image008

· To get the people picker value, use the below script.

var peoplePicker = $("[id$=’ppVal_upLevelDiv’]>span>div").attr("key") || ”;

if (peoplePicker != ”)

peoplePicker = PPLvalue(peoplePicker);

function PPLvalue(ppName) {

var userID = ”;

$().SPServices({

operation: "GetUserInfo",

async: false,

userLoginName: ppName,

completefunc: function (xData, Status) {

$(xData.responseXML).find("User").each(function () {

userID = $(this).attr("ID");

});

}

});

return userID;

}

Choice Column – Dropdown, Radio Button, Check-Box

· In aspx page –

<select id="ddlDropDown" title="Drop Down"></select>

<div id="divRadio" title="Radio Button"></div>

<div id="divCheckBox" title="Check Box"></div>

· In JS file and the function BindData(xData, Status) should be defined outside the document.ready

$(document).ready(function () {

$().SPServices({

operation: "GetList",

listName: "<<List Name where these columns are available>>",

completefunc: function(xData, Status) {

BindData(xData, Status);

},

async: false

});

});

 

function BindData(xData, Status) {

if (Status == ‘success’) {

//Append the value for Drop Down

appendField = $("#ddlDropDown");

$(xData.responseXML).find("Field[DisplayName=’Drop-Down Column’] CHOICE").each(function () {

$(appendField).append("<option value=’" + $(this).text() + "’>" + $(this).text() + "</option>");

});

//Append value for Radio Button

var activeField = "";

$(xData.responseXML).find("Field[DisplayName=’Radio-Button Column’] CHOICE").each(function () {

activeField += "<input name=’RadioBtn’ type=’radio’ value=’" + $(this).text() + "’><label>" + $(this).text() + "</label>";

});

$("#divRadio").html(activeField);

//Append value for Check Box

appendField = $("#divCheckBox");

$(xData.responseXML).find("Field[DisplayName=’Check-Box Column’] CHOICE").each(function () {

$(appendField).append("<input type=’checkbox’ name=’CheckBox’ value=’" + $(this).text() + "’/>" + $(this).text() + "<br/>");

});

}

}

 

Lookup Column – Single, Multiple

· For Lookup Single, in aspx page –

<select id="ddlLookupSingle" title="Look up single"></select>

· For Lookup Multiple, in aspx page –

<select id="LookupMul" multiple="multiple" ondblclick="GetSelectValues();" style="overflow:auto; width:150px !important; min-height:120px"></select>

<input type="button" id="btnAdd" onclick="GetSelectValues();" title="Add" value="Add &gt;" name="Add" />

<br />

<input type="button" id="btnRemo" onclick="RemoveSelectValues();" title="Remove" value="Remove &lt;" name="Remove" />

<select id="LookupMulSelected" multiple="multiple" ondblclick="RemoveSelectValues();" style="overflow:auto; width:150px !important; min-height:120px"></select>

· Lookup Single, in JS file–

$(document).ready(function () {

$().SPServices({

operation: "GetListItems",

async: false,

listName: "<<Lookup list name>>",

CAMLViewFields: "<ViewFields><FieldRef Name=’Title’ /><FieldRef Name=’ID’ /></ViewFields>",

completefunc: function (xData, Status) {

if (Status == ‘success’) {

$(xData.responseXML).SPFilterNode("z:row").each(function () {

var title = $(this).attr("ows_Title");

var ID = $(this).attr("ows_ID"); $(‘#ddlLookupSingle’).append($(‘<option></option>’).val(ID).html(title));

})

}

}

});

});

· Lookup Multiple, in JS file and the function GetSelectValues() & RemoveSelectValues() should be defined outside the document.ready –

$(document).ready(function () {

$().SPServices({

operation: "GetListItems",

async: false,

listName: "<<Lookup list name>>",

CAMLViewFields: "<ViewFields><FieldRef Name=’Title’/><FieldRef Name=’ID’ /></ViewFields>",

completefunc: function (xData, Status) {

if (Status == ‘success’) {

$(xData.responseXML).SPFilterNode("z:row").each(function () {

var title = $(this).attr("ows_Title");

var ID = $(this).attr("ows_ID"); $(‘#LookupMul’).append($(‘<option></option>’).val(ID).html(title));

})

}

}

});

});

function GetSelectValues() {

$("#LookupMul option:selected").each(function () {

var $this = $(this);

if ($this.length) {

var selText = $this.text();

var selVal = $this.val();

$(‘#LookupMulSelected’).append($(‘<option></option>’).val(selVal).html(selText));

$("#LookupMul option[value=" + selVal + "]").remove();

}

});

}

function RemoveSelectValues() {

$("#LookupMulSelected option:selected").each(function () {

var $this = $(this);

if ($this.length) {

var selText = $this.text();

var selVal = $this.val();

$(‘#LookupMul’).append($(‘<option></option>’).val(selVal).html(selText));

$("#LookupMulSelected option[value=" + selVal + "]").remove();

}

});

}

Though this is very straight forward, this will save a lot of development effort for sure. To save the retrieved values into a SharePoint list using SPServices, please refer to my another article on CRUD Operation on various field Types in SharePoint List using SPServices

 

Happy Coding

Ahamed Buhari

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

How to retrieve SharePoint List details by Content Query Webpart

Tarun Kumar Chatterjee
 
Net – Technology Specialist
February 26, 2016
 
Rate this article
 
Views
9109

Content search WebPart is used to fetch the data but it is fully depending on the Crawl. I mean to say, that the data will be available to the content search WebPart after crawl gets completed. In one of our requirement we had to fetch the data real time, so we decided to use Content Query WebPart.

Let see how we can fetch the data by using Content Query Webpart.

First let’s add 5 site columns named as EmpName, EmpEmail, EmpDept, EmpSalary & Emp Check

Create a list named as CQWebPartList

Add the 5 site columns to the newly created list & add few data into the list

clip_image002

Now create a SharePoint site page named as CQWebPartPage

Add a content query WebPart within the newly created page, Edit WebPart & add title as My Content Query.

Under query select the created list

clip_image004

Select the list type as below

clip_image006

Now export the content query WebPart

Create a sandbox solution

Add a module within the sandbox solution named as CQWebPartModule

Add the exported content query WebPart file under CQWebPartModule module

Go to the Style library — > XSL Style Sheet

Download the default main & Item Style XSL files named as: ContentQueryMain & ItemStyle

Rename the downloaded XSL file as CQMain & CQItemStyle respectively. Add the files to the solution under a newly created folder named as “Style Library”

Now open Content Query.webpart which we have added already under the module and modify the below properties to link with the XSL files

<property name="ItemXslLink" type="string" >/sites/Site1/Style Library/XSL Style Sheets/CQItemStyle.xsl</property>

<property name="MainXslLink" type="string" >/sites/Site1/Style Library/XSL Style Sheets/CQMain.xsl</property>

Add the following field mapping

<property name="CommonViewFields" type="string" >Title, Text;EmpName, Text;EmpEmail, Text;EmpDept, Text;Emp_x0020_Check, Text;EmpSalary</property>

Replace Elements.xml by the below code snippet

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Module Name="CQWebPartModule" Url="_catalogs/wp">

<File Path="CQWebPartModule\My Content Query.webpart" Url="My Content Query.webpart" >

<Property Name="Group" Value="Custom" />

</File>

</Module>

</Elements>

Now add the below template within CQItemStyle.xsl

 <xsl:template name="Employee-Details" match="Row[@Style='Employee-Details']" mode="itemstyle">
     <html>
       <table width="100%" cellspacing="4" cellpadding ="4">
         <xsl:if test="count(preceding-sibling::*)=0">
           <tr>
             <td width="20%" valign="top">
               <b>Title</b>
             </td>
             <td width="20%" valign="top">
               <b>Employee Name</b>
             </td>
             <td width="20%" valign="top">
               <b>Employee Email</b>
             </td>
             <td width="20%" valign="top">
               <b>Employee Department</b>
             </td>
             <td width="10%" valign="top">
               <b>Employee Salary</b>
             </td>
             <td width="10%" valign="top">
               <b>Employee Check</b>
             </td>
           </tr>
         </xsl:if>
         <tr>
           <td width="20%" valign="top">
             <xsl:value-of select="@Title" />
           </td>
           <td width="20%" valign="top">
             <xsl:value-of select="@EmpName" />
 
           </td>
           <td width="20%" valign="top">
             <xsl:value-of select="@EmpEmail" />
           </td>
           <td width="20%" valign="top">
             <xsl:value-of select="@EmpDept" />
           </td>
           <td width="10%" valign="top">
             <xsl:value-of select="@EmpSalary" />
           </td>
           <td width="10%" valign="top">
             <xsl:value-of select="@Emp_x005F_x0020_Check" />
           </td>
         </tr>
         
       </table>
     </html>
   </xsl:template>
 

The field names in these are very sensitive and if we miss _x005f in the field name will break it. Make sure to include the correct field names, which is different from internal name.

Refer the below examples for various fields.

Field NameXSL Field NameInternal Name
Vendor Description@Vendor_x005F_x0020_DescriptionVendor_x0020_Description
Go-live@Go_x005F_x002d_liveGo_x002d_live
IT HelpDesk #@IT_x005F_x0020_HelpDesk_x005F_x0020__x005F_x0023_IT_x0020_HelpDesk_x0020__x0023_

Use this in an itemstyle to output a header:

<xsl:if test="count(preceding-sibling::*)=0">

</xsl:if>

Use this in an itemstyle to output footer:

<xsl:if test="count(following-sibling::*)=0">

</xsl:if>

Add the below line of code in CQMain.xsl

<xsl:variable name="ItemStylePrefix" select="’Employee-‘" />

Rebuild the sandbox solution and deploy

Under the Style Library add the two modified XSL files

Now from the Site Page delete the WebPart and add it again

Under presentation select the Item style “Employee-Details”

clip_image008

Save the WebPart & the output will be looking like

clip_image010

 

Hope this artifact will help the basic use & implementation of Content query WebPart.

Happy Coding

Tarun Kumar Chatterjee

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment