Friday, July 21, 2017

Client Side rendering (CSR) in SharePoint

Client Side rendering (CSR) in SharePoint.

1. Priority color
2. Substring long text
3. Confidential Documents
4. HTML5 number input
5. Percent Complete
6. Accordion
7. Email Regex Validator
8. Read-Only SP Controls
9. Hidden Field
10. Hide Empty Column
11. Form Tabs
12. Repeater
13. Fully customized forms with CSRListForm
14. Dependent Fields

1. Priority color:
==================

1. Create a Task list named as 'CSRPriorityColor'.
2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
PriorityColor.js:

------------------
(function () {
    // Create object that has the context information about the field that we want to render differently
    var priorityFiledContext = {};
    priorityFiledContext.Templates = {};
    priorityFiledContext.Templates.Fields = {
        // Apply the new rendering for Priority field in List View
        "Priority": { "View": priorityFiledTemplate }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(priorityFiledContext);
})();

// This function provides the rendering logic for list view
function priorityFiledTemplate(ctx) {

    var priority = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];

    // Return html element with appropriate color based on priority value
    switch (priority) {
        case "(1) High":
            return "<span style='color :#f00'>" + priority + "</span>";
            break;
        case "(2) Normal":
            return "<span style='color :#ff6a00'>" + priority + "</span>";
            break;
        case "(3) Low":
            return "<span style='color :#cab023'>" + priority + "</span>";
    }
}
------------------
4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and copy JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
2. Substring long text:
=======================
1. Create a Announcements list named as 'CSRSubstringlongtext'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
SubstringLongText.js
------------------
(function () {
    // Create object that has the context information about the field that we want to render differently
    var bodyFiledContext = {};
    bodyFiledContext.Templates = {};
    bodyFiledContext.Templates.Fields = {
        // Apply the new rendering for Body field in list view
        "Body": { "View": bodyFiledTemplate }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(bodyFiledContext);
})();

// This function provides the rendering logic
function bodyFiledTemplate(ctx) {
    var bodyValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    //This regex expression use to delete html tags from the Body field
    var regex = /(<([^>]+)>)/ig;
    bodyValue = bodyValue.replace(regex, "");
    var newBodyValue = bodyValue;
    if (bodyValue && bodyValue.length >= 100)
    {
        newBodyValue = bodyValue.substring(0, 100) + " ...";
    }
    return "<span title='" + bodyValue + "'>" + newBodyValue + "</span>";      

}
------------------
4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and copy JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
3. Confidential Documents:
=======================
1. Create a Document Library list named as 'CSRConfidentialDocuments'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
ConfidentialDocuments.js
------------------
(function () {
    // Create object that has the context information about the field that we want to render differently
    var linkFilenameFiledContext = {};
    linkFilenameFiledContext.Templates = {};
    linkFilenameFiledContext.Templates.Fields = {
        // Apply the new rendering for LinkFilename field in list view
        "LinkFilename": { "View": linkFilenameFiledTemplate }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFilenameFiledContext);
})();

// This function provides the rendering logic
function linkFilenameFiledTemplate(ctx) {

    var confidential = ctx.CurrentItem["Confidential"];
    var title = ctx.CurrentItem["FileLeafRef"];

    // This Regex expression use to delete extension (.docx, .pdf ...) form the file name
    title = title.replace(/\.[^/.]+$/, "")

    // Check confidential field value
    if (confidential && confidential.toLowerCase() == 'yes') {
        // Render HTML that contains the file name and the confidential icon
        return title + "&nbsp;<img src= '" + _spPageContextInfo.siteServerRelativeUrl + "/Style%20Library/JSLink-Samples/imgs/Confidential.png' alt='Confidential Document' title='Confidential Document'/>";
    }
    else {
        return title;
    }

}
------------------
4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and copy JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5.

------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
4. HTML5 number input:
=======================
1. Create a custom list named as 'HTML5NumberInputList'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
HTML5NumberInput.js
------------------
(function () {
    // Create object that have the context information about the field that we want to change it's output render 
    var ageFiledContext = {};
    ageFiledContext.Templates = {};
    ageFiledContext.Templates.Fields = {
        // Apply the new rendering for Age field on New and Edit forms
        "Age": {
            "NewForm": ageFiledTemplate,
            "EditForm": ageFiledTemplate
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ageFiledContext);
})();

// This function provides the rendering logic
function ageFiledTemplate(ctx) {
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        return document.getElementById('inpAge').value;
    });
    // Render Html5 input (number)
    return "<input type='number' id='inpAge' min='18' max='110' value='" + formCtx.fieldValue + "'/>";

}
------------------
4. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

6. Test now
This below image showing 'NewForm.aspx' and 'EditForm.aspx' page before apply 'HTML5NumberInput.js' code.

This below image showing 'NewForm.aspx' and 'EditForm.aspx' page after apply 'HTML5NumberInput.js' code.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
5. Percent Complete:
=======================
1. Create a Task list named as 'CSRTasksPercentComplete'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
PercentComplete.js
------------------
(function () {
    // Create object that has the context information about the field that we want to render differently
    var percentCompleteFiledContext = {};
    percentCompleteFiledContext.Templates = {};
    percentCompleteFiledContext.Templates.Fields = {
        // Apply the new rendering for PercentComplete field in List View, Display, New and Edit forms
        "PercentComplete": {
            "View": percentCompleteViewFiledTemplate,
            "DisplayForm": percentCompleteViewFiledTemplate,
            "NewForm": percentCompleteEditFiledTemplate,
            "EditForm": percentCompleteEditFiledTemplate
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(percentCompleteFiledContext);
})();

// This function provides the rendering logic for View and Display form
function percentCompleteViewFiledTemplate(ctx) {

    var percentComplete = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    return "<div style='background-color: #e5e5e5; width: 100px;  display:inline-block;'> \
            <div style='width: " + percentComplete.replace(/\s+/g, '') + "; background-color: #0094ff;'> \
            &nbsp;</div></div>&nbsp;" + percentComplete;

}

// This function provides the rendering logic for New and Edit forms
function percentCompleteEditFiledTemplate(ctx) {

    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        return document.getElementById('inpPercentComplete').value;
    });

    return "<input type='range' id='inpPercentComplete' name='inpPercentComplete' min='0' max='100' \
            oninput='outPercentComplete.value=inpPercentComplete.value' value='" + formCtx.fieldValue + "' /> \
            <output name='outPercentComplete' for='inpPercentComplete' >" + formCtx.fieldValue + "</output>%";

}
------------------
4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and copy JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5.

------------------------------------------------------------------------------------------------------------
6. Accordion:
=======================
1. Create a custom list named as 'CSRAccordion'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
Accordion.js
------------------ 
(function () {
    // jQuery library is required in this sample
    // Fallback to loading jQuery from a CDN path if the local is unavailable
    (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>'));

    // Create object that has the context information about the field that we want to render differently
    var accordionContext = {};
    accordionContext.Templates = {};

    // Be careful when adding the header for the template, because it will break the default list view render
    accordionContext.Templates.Header = "<div class='accordion'>";
    accordionContext.Templates.Footer = "</div>";

    // Add OnPostRender event handler to add accordion click events and style
    accordionContext.OnPostRender = accordionOnPostRender;

    // This line of code tells the TemplateManager that we want to change all the HTML for item row rendering
    accordionContext.Templates.Item = accordionTemplate;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(accordionContext);
})();

// This function provides the rendering logic
function accordionTemplate(ctx) {
    var title = ctx.CurrentItem["Title"];
    var description = ctx.CurrentItem["Description"];

    // Return whole item html
    return "<h2>" + title + "</h2><p>" + description + "</p><br/>";
}

function accordionOnPostRender() {

    // Register event to collapse and expand when clicking on accordion header
    $('.accordion h2').click(function () {
        $(this).next().slideToggle();
    }).next().hide();

    $('.accordion h2').css('cursor', 'pointer');

}
------------------
4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and copy JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
7. Email Regex Validator:
=======================
1. Create a custom list named as 'CSREmailRegexValidator'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
RegexValidator.js
------------------
(function () {
    // Create object that has the context information about the field that we want to render differently
    var emailFiledContext = {};
    emailFiledContext.Templates = {};
    emailFiledContext.Templates.Fields = {
        // Apply the new rendering for Email field on New and Edit Forms
        "Email": {
            "NewForm": emailFiledTemplate,
            "EditForm": emailFiledTemplate
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(emailFiledContext);
})();

// This function provides the rendering logic
function emailFiledTemplate(ctx) {
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        return document.getElementById('inpEmail').value;
    });

    //Create container for various validations
    var validators = new SPClientForms.ClientValidation.ValidatorSet();
    validators.RegisterValidator(new emailValidator());
    // Validation failure handler.
    formCtx.registerValidationErrorCallback(formCtx.fieldName, emailOnError);
    formCtx.registerClientValidator(formCtx.fieldName, validators);
    return "<span dir='none'><input type='text' value='" + formCtx.fieldValue + "'  maxlength='255' id='inpEmail' class='ms-long'> \
            <br><span id='spnError' class='ms-formvalidation ms-csrformvalidation'></span></span>";
}

// Custom validation object to validate email format
emailValidator = function () {
    emailValidator.prototype.Validate = function (value) {
        var isError = false;
        var errorMessage = "";
        if (!validateEmail(value)) {
            isError = true;
            errorMessage = "Invalid email address";
        }
        //Send error message to error callback function (emailOnError)
        return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
    };
};

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
// Add error message to spnError element under the input field element
function emailOnError(error) {
    document.getElementById("spnError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";

}
------------------
4. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

6. Test now
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
8. Read-Only SP Controls:
=======================
1. Create a Task list named as 'CSR-Read-only-SP-Controls'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
ReadOnlySPControls.js:
------------------

(function () {
    // Create object that has the context information about the field that we want to render differently
    var readonlyFiledContext = {};
    readonlyFiledContext.Templates = {};
    readonlyFiledContext.Templates.Fields = {
        // Apply the new rendering for Title, AssignedTo, and Priority fields on Edit forms
        "Title": {
            "EditForm": readonlyFieldTemplate
        },
        "AssignedTo": {
            "EditForm": readonlyFieldTemplate
        },
        "Priority": {
            "EditForm": readonlyFieldTemplate
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(readonlyFiledContext);
})();

// This function provides the rendering logic
function readonlyFieldTemplate(ctx) {

    //Reuse SharePoint JavaScript libraries
    switch (ctx.CurrentFieldSchema.FieldType) {
        case "Text":
        case "Number":
        case "Integer":
        case "Currency":
        case "Choice":
        case "Computed":
            return SPField_FormDisplay_Default(ctx);

        case "MultiChoice":
            prepareMultiChoiceFieldValue(ctx);
            return SPField_FormDisplay_Default(ctx);

        case "Boolean":
            return SPField_FormDisplay_DefaultNoEncode(ctx);

        case "Note":
            prepareNoteFieldValue(ctx);
            return SPFieldNote_Display(ctx);

        case "File":
            return SPFieldFile_Display(ctx);

        case "Lookup":
        case "LookupMulti":
                return SPFieldLookup_Display(ctx);          

        case "URL":
            return RenderFieldValueDefault(ctx);

        case "User":
            prepareUserFieldValue(ctx);
            return SPFieldUser_Display(ctx);

        case "UserMulti":
            prepareUserFieldValue(ctx);
            return SPFieldUserMulti_Display(ctx);

        case "DateTime":
            return SPFieldDateTime_Display(ctx);

        case "Attachments":
            return SPFieldAttachments_Default(ctx);

        case "TaxonomyFieldType":
            //Re-use JavaScript from the sp.ui.taxonomy.js SharePoint JavaScript library
            return SP.UI.Taxonomy.TaxonomyFieldTemplate.renderDisplayControl(ctx);
    }
}

//User control need specific formatted value to render content correctly
function prepareUserFieldValue(ctx) {
    var item = ctx['CurrentItem'];
    var userField = item[ctx.CurrentFieldSchema.Name];
    var fieldValue = "";

    for (var i = 0; i < userField.length; i++) {
        fieldValue += userField[i].EntityData.SPUserID + SPClientTemplates.Utility.UserLookupDelimitString + userField[i].DisplayText;

        if ((i + 1) != userField.length) {
            fieldValue += SPClientTemplates.Utility.UserLookupDelimitString
        }
    }

    ctx["CurrentFieldValue"] = fieldValue;
}

//Choice control need specific formatted value to render content correctly
function prepareMultiChoiceFieldValue(ctx) {

    if (ctx["CurrentFieldValue"]) {
        var fieldValue = ctx["CurrentFieldValue"];

        var find = ';#';
        var regExpObj = new RegExp(find, 'g');

        fieldValue = fieldValue.replace(regExpObj, '; ');
        fieldValue = fieldValue.replace(/^; /g, '');
        fieldValue = fieldValue.replace(/; $/g, '');

        ctx["CurrentFieldValue"] = fieldValue;
    }
}

//Note control need specific formatted value to render content correctly
function prepareNoteFieldValue(ctx) {

    if (ctx["CurrentFieldValue"]) {
        var fieldValue = ctx["CurrentFieldValue"];
        fieldValue = "<div>" + fieldValue.replace(/\n/g, '<br />'); + "</div>";

        ctx["CurrentFieldValue"] = fieldValue;
    }

}

4. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Test now
This below image showing 'EditForm.aspx' page before apply 'ReadOnlySPControls.js' code.

This below image showing 'EditForm.aspx' page after apply 'ReadOnlySPControls.js' code.

------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
9. Hidden Field:
=======================
1. Create a task list named as 'CSR-Hide-Controls'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file 'HiddenField.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
HiddenField.js
------------------
(function () {
    // jQuery library is required in this sample
    // Fallback to loading jQuery from a CDN path if the local is unavailable
    (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>'));

    // Create object that has the context information about the field that we want to render differently
    var hiddenFiledContext = {};
    hiddenFiledContext.Templates = {};
    hiddenFiledContext.Templates.OnPostRender = hiddenFiledOnPreRender;
    hiddenFiledContext.Templates.Fields = {
        // Apply the new rendering for Predecessors field in New and Edit forms
        "Predecessors": {
            "NewForm": hiddenFiledTemplate,
            "EditForm": hiddenFiledTemplate
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(hiddenFiledContext);
})(); 

// This function provides the rendering logic
function hiddenFiledTemplate() {
    return "<span class='csrHiddenField'></span>";
}

// This function provides the rendering logic
function hiddenFiledOnPreRender(ctx) {
    jQuery(".csrHiddenField").closest("tr").hide();

}

4. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

6. Test now
This below image showing 'NewForm.aspx' and 'EditForm.aspx' page before apply 'HiddenField.js' code.

This below image showing 'NewForm.aspx' and 'EditForm.aspx' page after apply 'HiddenField.js' code.
------------------------------------------------------------------------------------------------------------
10. Hide Empty Column:
=======================
1. Create a task list named as 'CSR-Hide-Empty-Column '.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file 'HideEmptyColumn.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
HideEmptyColumn.js
------------------
(function () {      
       // jQuery library is required in this sample
    // Fallback to loading jQuery from a CDN path if the local is unavailable
    (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>'));

    // Create object that have the context information about the field that we want to change it's output render
    var linkFiledContext = {};
    linkFiledContext.Templates = {};
  
    // Add OnPostRender event handler to hide the column if empty
    linkFiledContext.OnPostRender = linkOnPostRender;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(linkFiledContext);
})();

function linkOnPostRender(ctx)
{
    var linkCloumnIsEmpty = 1;

    for (i = 0; i < ctx.ListData.Row.length; i++) {
        if (ctx.ListData.Row[i]["Link"])
        {
            linkCloumnIsEmpty = 0;
            break;
        }
    }

    //Hide "Link" column if it is empty
     if (linkCloumnIsEmpty) {
        var cell = $("div [name='Link']").closest('th');
        var cellIndex = cell[0].cellIndex + 1;

        $('td:nth-child(' + cellIndex + ')').hide();
        $('th:nth-child(' + cellIndex + ')').hide();
    }

}

4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and copy JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.
~sitecollection/Style Library/JSLink-Samples/HideEmptyColumn.js

5. Test now
Go to list page, check before apply 'HideEmptyColumn.js' code, "Link"Column hided.
------------------------------------------------------------------------------------------------------------
11. Form Tabs:
=======================
1. Create a custom list named as 'Form Tabs Custom List'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
Tabs.js
------------------
var currentFormUniqueId;
var currentFormWebPartId;

// Use "Multi String" javascript to embed the required css
var MultiString = function (f) {
    return f.toString().split('\n').slice(1, -1).join('\n');
}
var tabsStyle = MultiString(function () {/**
.tabs {
border-bottom: 1px solid #ddd;
content: " ";
display: table;
margin-bottom: 0;
padding-left: 0;
list-style: none;
width: 100%;
}
.tabs > li {
    float: left;
    margin-bottom: -1px;
    position: relative;
    display: block;
}
.tabs > li > a {
    margin-right: 2px;
    line-height: 1.42857143;
    border: 1px solid transparent;
    position: relative;
    display: block;
    padding: 10px 15px;
}
.tabs a {
    color: #428bca;
    text-decoration: none;
}
.tabs > li.active > a, .tabs > li.active > a:hover, .tabs > li.active > a:focus {
    color: #555;
    background-color: #fff;
    border: 1px solid #ddd;
    border-bottom-color: transparent;
    cursor: default;
}
**/
});

var tabsObj = [
    ["General", ["Title", "Column01", "Column02", "Column03", "Column04"]],
    ["Work", ["Column05", "Column06", "Column07"]],
    ["Other", ["Column08"]]
];

(function () {
    // jQuery library is required in this sample
    // Fallback to loading jQuery from a CDN path if the local is unavailable
    (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>'));

    var tabsContext = {};
    tabsContext.OnPreRender = TabsOnPreRender;
    tabsContext.OnPostRender = TabsOnPostRender;
    // accordionContext.OnPostRender = accordionOnPostRender;
    tabsContext.Templates = {};
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(tabsContext);
})();

function TabsOnPreRender(ctx) {
    if (!currentFormUniqueId) {
        currentFormUniqueId = ctx.FormUniqueId;
        currentFormWebPartId = "WebPart" + ctx.FormUniqueId;
        jQuery(document).ready(function () {
            var tabHTMLTemplate = "<li class='{class}'><a href='#{Index}'>{Title}</a></li>";
            var tabClass;
            var tabsHTML = "";
            for (var i = 0; i < tabsObj.length; i++) {
                tabClass = "";
                if (i == 0){ tabClass = "active";}
                tabsHTML += tabHTMLTemplate.replace(/{Index}/g, i).replace(/{Title}/g, tabsObj[i][0]).replace(/{class}/g, tabClass)
            }
            jQuery("#" + currentFormWebPartId).prepend("<ul class='tabs'>" + tabsHTML + "</ul>");
            jQuery('.tabs li a').on('click', function (e) {
                var currentIndex = jQuery(this).attr('href').replace("#","");
                showTabControls(currentIndex);
                jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
                e.preventDefault();
            });
            showTabControls(0);
            jQuery("#" + currentFormWebPartId).prepend("<style>" + tabsStyle + "</style>");
        });
    }
}

function TabsOnPostRender(ctx) {
    var controlId = ctx.ListSchema.Field[0].Name + "_" + ctx.ListSchema.Field[0].Id;
    jQuery("[id^='" + controlId + "']").closest("tr").attr('id', 'tr_' + ctx.ListSchema.Field[0].Name).hide();
}

function showTabControls(index)
{
    jQuery("#" + currentFormWebPartId + " [id^='tr_']").hide();
    for (var i = 0; i < tabsObj[index][1].length; i++) {
        jQuery("[id^='tr_" + tabsObj[index][1][i] + "']").show();
    }

}
------------------
4. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

6. Test now
This below image showing 'NewForm.aspx' page before apply 'Tabs.js' code.

This below image showing 'NewForm.aspx' page after apply 'Tabs.js' code.

This below image showing ''EditForm.aspx' page after apply 'Tabs.js' code.

This below image showing ''DispForm.aspx' page before 'Tabs.js' code.
Current 'Tabs.js' does not support 'DispForm.aspx' page.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
12. Repeater:
=======================
1. Create a custom list named as 'Repeater Custom List'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
BasicRepeater.js
------------------
var repeaterFormArr = [
    "<input type='text' id='nameInput' placeholder='Full Name' required class='ms-long ms-spellcheck-true'>",
    "<input type='number' id='ageInput' placeholder='Age' required style='padding: 2px 4px;' class='ms-long ms-spellcheck-true'>",
    "<input type='text' id='ssnInput' placeholder='SSN' pattern=\"^\\d{3}-\\d{2}-\\d{4}$\" title='###-##-####' class='ms-long ms-spellcheck-true'>",
];

var ControlRenderMode;
var repeaterFormValues = [];

(function () {
    // Create object that have the context information about the field that we want to change it's output render
    var repeaterFiledContext = {};
    repeaterFiledContext.Templates = {};
    repeaterFiledContext.Templates.Fields = {
        // Apply the new rendering for Age field on New and Edit forms
        "Dependents": {
            "View": RepeaterFiledViewTemplate,
            "DisplayForm": RepeaterFiledViewTemplate,
            "NewForm": RepeaterFiledEditFTemplate,
            "EditForm": RepeaterFiledEditFTemplate
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(repeaterFiledContext);
})();


// This function provides the rendering logic
function RepeaterFiledViewTemplate(ctx) {

    ControlRenderMode = ctx.ControlMode;

    if (ctx.CurrentItem[ctx.CurrentFieldSchema.Name] && ctx.CurrentItem[ctx.CurrentFieldSchema.Name] != '[]') {
        var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name].replace(/&quot;/g, "\"").replace(/(<([^>]+)>)/g, "");
        repeaterFormValues = JSON.parse(fieldValue);
    }

    return GetRenderHtmlRepeaterValues();
}
// This function provides the rendering logic
function RepeaterFiledEditFTemplate(ctx) {

    ControlRenderMode = ctx.ControlMode;

    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

    if (formCtx.fieldValue) {
        repeaterFormValues = JSON.parse(formCtx.fieldValue);
    }

    // Register a callback just before submit.
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        return JSON.stringify(repeaterFormValues);
    });

    var index;
    var HTMLViewTemplate = "<form id='innerForm' onsubmit='return AddItem();'>{Controls}<div><input type='submit' value='Add' style='margin-left:0'></div><br/><div id='divRepeaterValues'>{RepeaterValues}</div><br/></form>";
    var returnHTML = "";

    for (index = 0; index < repeaterFormArr.length; ++index) {
        returnHTML += repeaterFormArr[index];
    }

    returnHTML = HTMLViewTemplate.replace(/{Controls}/g, returnHTML);
    returnHTML = returnHTML.replace(/{RepeaterValues}/g, GetRenderHtmlRepeaterValues());

    return returnHTML;
}

function GetRenderHtmlRepeaterValues() {

    var index;
    var innerindex;
    var HTMLItemsTemplate = "<table width='100%' style='border:1px solid #ababab;'>{Items}</table>";
    var HTMLItemTemplate = "<tr>{Item}</tr>";
    var HTMLValueTemplate = "<td>{Value}</td>";

    if (ControlRenderMode == SPClientTemplates.ClientControlMode.EditForm || ControlRenderMode == SPClientTemplates.ClientControlMode.NewForm) {
        HTMLItemTemplate = "<tr>{Item}<td><a href='javascript:DeleteItem({Index});'>Delete</a></td></tr>";
    }

    var returnHTML = "";
    var tempValueHtml;


    for (index = 0; index < repeaterFormValues.length; ++index) {
        tempValueHtml = "";

        for (innerindex = 0; innerindex < repeaterFormValues[index].length; ++innerindex) {
            tempValueHtml += HTMLValueTemplate.replace(/{Value}/g, repeaterFormValues[index][innerindex]["Value"]);
        }

        returnHTML += HTMLItemTemplate.replace(/{Item}/g, tempValueHtml);
        returnHTML = returnHTML.replace(/{Index}/g, index);
    }

    if (repeaterFormValues.length) {
        returnHTML = HTMLItemsTemplate.replace(/{Items}/g, returnHTML);
    }

    return returnHTML;
}

function AddItem() {

    var innerForm = document.getElementById('innerForm');

    if (innerForm.checkValidity()) {

        var index;
        var tempRepeaterValue = [];

        for (index = 0; index < innerForm.length; index++) {

            if (innerForm[index].type != "submit" && innerForm[index].type != "button" && innerForm[index].type != "reset") {
                tempRepeaterValue.push(
                   {
                       "ID": innerForm[index].id,
                       "Value": innerForm[index].value
                   }
                   );

                innerForm[index].value = "";
            }
        }


        repeaterFormValues.push(tempRepeaterValue);

        document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValues();
    }
    return false;
}

function DeleteItem(index) {
    repeaterFormValues.splice(index, 1);
    document.getElementById("divRepeaterValues").innerHTML = GetRenderHtmlRepeaterValues();
}
------------------
4. Go to list and edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

6. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

7. Go to list and select an item and click on item to open item then 'DispForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

8. Test now.
This image show create item in list before apply 'BasicRepeater.js' code

This below image shown create new item in list after apply 'BasicRepeater.js' code.

This image showing item display view. 

This image showing item editing view.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
13. Fully customized forms with CSRListForm:
=======================
1. Create a custom list named as 'Fully customized forms with CSRListForm List'.

2. Create a list columns as shown below.

3. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
FullyCustomizedForm.js
------------------
(function () {
    // Create object that have the context information about the field that we want to change it's output render 
    var formTemplate = {};
    formTemplate.Templates = {};
    formTemplate.Templates.View = viewTemplate;
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(formTemplate);
 })();

// This function provides the rendering logic for the Custom Form
function viewTemplate(ctx) {   
    var formTable = "".concat("<table width='100%' cellpadding='5'>",
                                    "<tr>",
                                        "<td><div>Title</div></td>",
                                        "<td><div>{{TitleCtrl}}</div></td>",
                                        "<td><div>Date</div></td>",
                                        "<td><div>{{DateCtrl}}</div></td>",
                                    "</tr>",
                                    "<tr>",
                                        "<td><div>Category</div></td>",
                                            "<td><div>{{CategoryCtrl}}</div></td>",
                                        "<td><div>Active</div></td>",
                                        "<td><div>{{ActiveCtrl}}</div></td>",
                                    "</tr>",
                                    "<tr>",
                                        "<td></td>",
                                        "<td><input type='button' value='Save' id='btnsave' onclick=\"SPClientForms.ClientFormManager.SubmitClientForm('{{FormId}}')\" style='margin-left:0' ></td>",
                                    "</tr>",
                              "</table>");   
    //Replace the tokens with the default sharepoint controls
    formTable = formTable.replace("{{TitleCtrl}}", getSPFieldRender(ctx, "Title"));
    formTable = formTable.replace("{{DateCtrl}}", getSPFieldRender(ctx, "Date"));
    formTable = formTable.replace("{{CategoryCtrl}}", getSPFieldRender(ctx, "Category"));
    formTable = formTable.replace("{{ActiveCtrl}}", getSPFieldRender(ctx, "Active"));
    formTable = formTable.replace("{{FormId}}", ctx.FormUniqueId);
    return formTable;
}

//This function code set the required properties and call the OOTB (default) function that use to render Sharepoint Fields
function getSPFieldRender(ctx, fieldName){
    var fieldContext = ctx;
    //Get the filed Schema
    var result = ctx.ListSchema.Field.filter(function( obj ) {
        return obj.Name == fieldName;
    });
    //Set the field Schema  & default value
    fieldContext.CurrentFieldSchema = result[0];
    fieldContext.CurrentFieldValue = ctx.ListData.Items[0][fieldName];
    //Call  OOTB field render function
    return ctx.Templates.Fields[fieldName](fieldContext);

}
------------------
4. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

5. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

6. Go to list and select an item and click on item to open item then 'DispForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

7. Test now
This  below image showing before apply 'FullyCustomizedForm.js' code.

This below image showing after apply 'FullyCustomizedForm.js' code.
This is create new item view.

This below image is view item.

This below image is edit item view.
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
14. Dependent Fields:
=======================
1. Create a custom list named as 'CSRDependentFieldsCars'.

2. Create a list columns as shown below.

3. Create a custom list named as 'CSRDependentFields'.
4. Create a list columns as shown below.

As shown in below image, in this 'CSRDependentFields' list 'Car' column is lookup column and value is 'Title' column from 'CSRDependentFieldsCars' list.

5. Write below code in notepad save as JavaScript file '.js' and upload into SharePoint site assets library and copy this file URL for future reference.
------------------
DependentFields.js
------------------
(function () {
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
        Templates: {
            OnPostRender: function (ctx) {
                var colorField = window[ctx.FormUniqueId + "FormCtx"].ListSchema["Color"];
                var colorFieldControlId = colorField.Name + "_" + colorField.Id + "_$RadioButton" + colorField.FieldType + "Field";

                var f = ctx.ListSchema.Field[0];
                if (f.Name == "Car") {
                    var fieldControl = $get(f.Name + "_" + f.Id + "_$" + f.FieldType + "Field");

                    $addHandler(fieldControl, "change", function (e) {
                        // first, let's hide all the colors - while the information is loading
                        for (var i = 0; i < 5; i++)
                            $get(colorFieldControlId + i).parentNode.style.display = "none";

                        var newValue = fieldControl.value;
                        var newText = fieldControl[fieldControl.selectedIndex].text;
                        var context = SP.ClientContext.get_current();
                        // here add logic for fetching information from an external list
                        // based on newText and newValue
                        context.executeQueryAsync(function () {
                            // fill this array according to the results of the async request
                            var showColors = [];
                            if (newText == "Kia Soul") showColors = [0, 2, 3];
                            if (newText == "Fiat 500L") showColors = [1, 4];
                            if (newText == "BMW X5") showColors = [0, 1, 2, 3, 4];

                            // now, display the relevant ones
                            for (var i = 0; i < showColors.length; i++)
                                $get(colorFieldControlId + showColors[i]).parentNode.style.display = "";
                        },
                        function (sender, args) {
                            alert("Error! " + args.get_message());
                        });
                    });
                } else if (f.Name == "Color") {
                    // initialization: hiding all the choices. first user must select a car
                    for (var i = 0; i < 5; i++)
                        $get(colorFieldControlId + i).parentNode.style.display = "none";
                }
            }
        }
    });
})();
------------------
6. Go to list and click on 'New Item' to create new item then 'NewForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

7. Go to list and select an item and click on edit item then 'EditForm.aspx' form will be open, edit page and edit list view web part and expand 'Miscellaneous' section and paste JavaScript file reference URL into JS Link textbox. Click 'Ok' to save and close.

8. Test now
This below image showing before apply 'DependentFields.js code. 
so all colors are showing even nothing (none) selected in Car column.

This below image showing after apply 'DependentFields.js' code.
so if no Car select then no color will show.

This below showing for 'Chervolet Trax' car no color showing in Color column, this is not a error, this is done in coding to show no color in Color column.
------------------------------------------------------------------------------------------------------------

Featured Post

Sent Email in C#

Sent Email in C# : //Option 1: using S ystem; using System.Net.Mail; using System.Security; using System.Text; using System.Threading.T...

Popular posts