Let's explore customizing SharePoint Forms using JSLink. Let's say we want to customize the New Form of a custom list.
Since I am using a SharePoint online environment, I will create a SharePoint Hosted App. This step is not necessary. Let's add a Custom List called Demo to the solution. Add two fields, Available
and YTD
of type single line of text to the list.
Now, open the schema.xml search for the <Forms>
section and update the NewForm
element as:
<Form Type="NewForm"
Url="NewForm.aspx" SetupPath="pages\form.aspx"
WebPartZoneID="Main"
JSLink="~site/Scripts/jquery-1.9.1.min.js|~site/Scripts/NewFormScript.js" />
Notice that we are loading two scripts, one is the JQuery library and the other is our custom script. We can do this by separating the script parts with a ‘|
’ character.
Now, right click on the Scripts module and add a JavaScript file NewFormScript.js.
Add the following code to this file:
(function () {
var ctx = {};
ctx.OnPostRender = updateDOM;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();
function updateDOM(ctx) {
(function ($) {
$(document).ready(function () {
var current = 1;
var newTable ='<table class="ms-formtable" style="margin-top: 8px;"
border="0" cellpadding="0"
cellspacing="0" width="100%"><tr>';
$(".ms-formtable td").each(function (i) {
if (current == 2 || current == 6) {
newTable = newTable + $('<div>').append
($(this).clone()).remove().html() + '</tr><tr>';
}
else {
newTable = newTable + $('<div>').append($(this).clone()).remove().html();
}
current = current + 1;
});
newTable = newTable + '</tr></table>';
$(".ms-formtable").html(newTable);
});
})(jQuery);
}
Here, we are creating a new object and adding a property OnPostRender
with the function we want to execute. Then, we call the SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
method which registers this object. This will execute our function on post render, i.e., when the DOM is ready.
Within this function, we modify the rendered DOM to look the way we want it. Here, we are grabbing td
elements in the table which has our columns. Then, we build a new table similar to the existing one. When we reach the specific td
when we want to start a new row, we are creating a new tr
.
Here, I have hard coded 2 and 6 columns. But you can put some logic like current%4
to start a new row every 2 columns.
Deploy the solution. Navigate to the Demo list. In the case of the SharePoint hosted app, you need to specify the url, /Lists/Demo after the app name. Now, when you create a new item, the form should look like:
I have uploaded the solution to github at JSLinkDemo.
The post Customizing SharePoint Forms using JSLink appeared first on The SharePoint Guide.