Versions: SharePoint 2013
Definitions: SharePoint custom list, SharePoint list GUID, SharePoint list item, SharePoint field, SharePoint field internal name
References:
Tags: #JavaScript, #JQuery, #SharePoint
A huge function that separates and rearranges the fields in a New and Edit forms (of a list that have a lot of fields) into sections.
// Steps before using the function :
// [1] - Create a SharePoint custom list for administration with 4 fields :
// 1. - text field : "List GUID" for example
// 2. - checkbox field : "Apply theme to New"
// 3. - checkbox field : "Apply theme to Edit"
// 4. - multiple lines of text field : "Config"
// [2] - Create a list item, fill the create form with :
// 1. - "List GUID" : GUID of the target business custom list which the display form to stylize belongs (see How to get list GUID(link))
// 2. - "Apply theme to New" : Yes/No to apply or not the theme/style to the new form of the target list
// 3. - "Apply theme to Edit" : Yes/No to apply or not the theme/style to the edit form of the target list
// 4. - "Config" : JSON string that contains the names of tabs to create and theirs fields.
// [3] - See 'Admin list and JSON config' below for better understanding
/**
* Separates and rearranges the fields of a New and Edit forms (of a list) into sections.
* - this function need to be loaded with the new/edit forms to stylize
* - very useful with lists that have a lot of fields
* @requires jQuery
* @param {string} adminListName - Name of the 'administration list' (created)
* @param {string} listGuidField - Internal name of the "List GUID" field in the 'administration list' (see How to get field internal name(link))
* @param {string} applyNewFormField - Internal name of the field "Apply theme to New"
* @param {string} applyEditFormField - Internal name of the field "Apply theme to Edit"
* @param {string} configField - Internal name of the field "Config"
*/
// Set administration list's informations here (needed in the HTTP get request)
var adminListName = "";
var listGuidField = "";
var applyNewFormField = "";
var applyEditFormField = "";
var configField = "";
(function sectionsForForms(adminListName, listGuidField, applyNewFormField, applyEditFormField, configField)
{
var currentListGuid = _spPageContextInfo.pageListId; // GUID of the current list used to get associated item in the administration list if any !
var newForm = false;
var editForm = false;
var configInfos = {};
var itemId = 0;
var secsNames = []; // for creating HTML elements
var secFields = []; // to search fields' HTML elements and attach them to "their" sections (as indicated in the user's config)
var htmlTabs = "";
var i = 0;
var NewOrEdit = _spPageContextInfo.serverRequestPath.indexOf('NewForm') > -1 ? "New" : "Edit" ; // check what is the current form
// // You would have notice that not the entire code is inside $(document).ready() because for perf is better to avoid this when not needed
// looking for our item in the administration list. Our item contains the user's configuration infos needed, target list and whether or not he would to apply the style .
// 1 - Get all the items of the administration list, we use the list's title
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(\'"+ adminListName +"\')/items",
method: "GET",
headers: { "Accept" : "application/json; odata=verbose" },
success: onSuccess,
error: function (data) {}
});
function onSuccess(data) // put all the code to exec in a callback function (async)
{ // 2 - Get the item's informations from the the administration list
var items = data.d.results;
for(var i=0; i < items.length; i++)
{
if( currentListGuid == items[i][listGuidField] || currentListGuid.toUpperCase() === items[i][listGuidField] || currentListGuid.replace(/{|}/g,"") === items[i][listGuidField] || currentListGuid.toUpperCase().replace(/{|}/g,"") === items[i][listGuidField] )
{
itemId = items[i]['ID']; // not really needed
newForm = items[i][applyNewFormField]; // user's Y/N for applying the theme/style for the NewForm
editForm = items[i][applyEditFormField]; // user's Y/N for applying the theme/style for the EditForm
configInfos = JSON.parse(items[i][configField]); // parsing user's configuration infos
//return;
i = items.length;
}
}
if( (NewOrEdit == "New" && newForm) || (NewOrEdit == "Edit" && editForm) ) // check if the user set ON for applying the theme/style according to the current form
{
// for sections names
secsNames = configInfos.onglets; //ou configInfos['onglets']
// for section's fields
secFields = configInfos.champs;
// creating HTML elements to use for sections
htmlTabs = "<div id='sections'>";
for(i = 0; i < secsNames.length; i++)
{
htmlTabs += "<div style='background-color:#B73C3E; border-radius:2px; padding:5px; text-align:center; margin:10px 0px 10px 0px'><h3 style='color:white !important'>"+ secsNames[i] +"</h3></div>"; //modifier le style de la barre ici
htmlTabs += "<div style='padding: 0px 10px 0px 10px'><table cellpadding='0' cellspacing='0' id='sec-"+ (i+1) +"'><tbody></tbody></table></div>"; // ne pas supprimer tbody pour que la fonction append() fonctionne (champs date:table)
}
htmlTabs += "</div>";
$(document).ready(function(){
// adding the HTML elements created to the DOM
var slc = ".ms-formtable"; //or = "#WebPartWPQ2 > table > tbody > tr:nth-child(3) > td > table > tbody"; // see Comments [1].1 below
$(htmlTabs).insertAfter(slc);
// array of fields' names
var arrTab = secFields;
// call a function getFieldsByIN
var fields = getFieldsByIN();
var currField ;
// put the fields in the correct section
$.each(arrTab,function(idx,item)
{
var split = item.split('|');
var tabID = split[0];
var fieldName = split[1];
if(fields[fieldName] != undefined)
{
currField = $(fields[fieldName]);
currField.appendTo('#sec-'+tabID);
}
});
// if there is an "Attachments" field, put it in the last section
$("#idAttachmentsRow").appendTo('#sec-'+ (secsNames.length)).find('.ms-formlabel').attr('width','165px');
});
}
}
// // Utility functions
// Gets fields (tr elements of the form) by their internal names (more robust) and creates/returns an "object"
function getFieldsByIN()
{
var res = {};
$("td.ms-formbody").each(function()
{
if($(this).html().indexOf('FieldInternalName="') > -1)
{
if($(this.parentNode).css('display') != 'none')
{
var str = $(this).html().indexOf('FieldInternalName="')+19;
var stp = $(this).html().indexOf('FieldType="')-6;
var fin = $(this).html().substring(str,stp);
res[fin] = this.parentNode;
}
}
});
return res;
}
// Gets fields (tr elements of the form) by their display names (see Comments [1].2 below) and creates/returns an "object"
/*
function getFieldsByDN(){
var res = {};
$("h3.ms-standardheader").each(function(){
var fdn = $(this).text();
res[fdn] = $(this).parents(':eq(1)');
});
return res;
}
*/
})(adminListName, listGuidField, applyNewFormField, applyEditFormField, configField);
// Comments:
// [1] - in case of user created forms where :
// .1 - there is no .ms-formtable class
// .2 - there are no internal names
// Admin list and JSON config:
// [1] - List GUID field accepts those (examples) format :
// . {40c34602-d8b2-4fae-9f48-a1c96d27dd25} or
// . {40C34602-D8B2-4FAE-9F48-A1C96D27DD25} or
// . 40c34602-d8b2-4fae-9f48-a1c96d27dd25 or
// . 40C34602-D8B2-4FAE-9F48-A1C96D27DD25 or
// [2] - Config field contains JSON string as follow :
// {
// "onglets": [
// "tab 1 name",
// "tab 2 name",
// "tab 3 name"
// ],
// "champs": [
// "tab index|field internal name",
// "tab index|field internal name",
// "tab index|field internal name",
// "tab index|field internal name",
// "tab index|field internal name",
// "tab index|field internal name",
// ]
// }
// . no order in "champs" array in the JSON string, but it's recommended to keep things organized
// . note that '|' symbol is used to separate a field and his tab, there is no risk to find this symol in an internal name
