Introduction

This blog is mainly focused on SharePoint
I will use this to store and share all the tips and tricks about SharePoint and the related products
List of all posts

Using JSLink


Topic Using JSLink
OutputClient side rending

Desc : JSLink files have the ability to quickly and easily change how a views and forms are rendered.
this can be done at field or item level.
Step Description
1 We will register our namespace
Type.registerNamespace('TZ');
2 Now we will create our CrsModule
which will modify 3 rendering of fields
  • Description : only the rendering for the view
  • Percent : View and Form
  • email : Form only
TZ.CsrModule = function(){
	var itemCtx = {};
	itemCtx.Templates = {};
	itemCtx.Templates.Fields = {
		'Description': { 
			'View' : TZ.CsrModule.DescriptionView 
		},
		'Percent': { 
            'View': TZ.CsrModule.PercentView,
            'DisplayForm': TZ.CsrModule.PercentView,
            'NewForm': TZ.CsrModule.PercentEdit,
            'EditForm': TZ.CsrModule.PercentEdit
        },
		'email': {
            'NewForm': TZ.CsrModule.EmailEdit,
            'EditForm':  TZ.CsrModule.EmailEdit
        }
	};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
}

3 Adding the view rendering function for the Field 'Description'
TZ.CsrModule.DescriptionView = function(ctx){
	var bodyDesc = ctx.CurrentItem.Description;
	var regex = /(<([^>]+)>)/ig;
	bodyDesc = bodyDesc.replace(regex, "");
	if (bodyDesc && bodyDesc.length >= 100)
	 {
	 var newDesc = bodyDesc.substring(0,100);
	 }
	return "<span title='" + bodyDesc + "'font style='color:green'>" + newDesc + "</font></span>";
}
we display only the first 100 character of the description in the view, the full description is show onmousover using the Title attribute.
4 Adding the view rendering function for the Field 'Percent'
TZ.CsrModule.PercentView = function (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;'> \
             </div></div> " + percentComplete;

}
5 Adding the edit rendering function for the Field 'Percent'
TZ.CsrModule.PercentEdit = function (ctx) {

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

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

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

}
Currently the output tag doesn't work with IE, so in Edit Form the text of the % is not updated.
6 Adding the edit rendering function for the Field 'email'
TZ.CsrModule.EmailEdit = function (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 TZ.CsrModule.EmailValidator());

    // Validation failure handler.
    formCtx.registerValidationErrorCallback(formCtx.fieldName, TZ.CsrModule.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
TZ.CsrModule.EmailValidator = function () {
    TZ.CsrModule.EmailValidator.prototype.Validate = function (value) {
        var isError = false;
        var errorMessage = "";

        //Email format Regex expression
        var emailRejex = /\S+@\S+\.\S+/;
        
        if (!emailRejex.test(value) && value.trim()) {
            isError = true;
            errorMessage = "Invalid email address";
        }

        //Send error message to error callback function (emailOnError)
        return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
    };
};
Add error message to spnError element under the input field element
TZ.CsrModule.EmailOnError = function (error) {
    document.getElementById("spnError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
}
7 The complete file
Type.registerNamespace('TZ');
RegisterModuleInit("/_catalogs/masterpage/jslink/CsrModule.js", TZ.CsrModule); // CSR-override for MDS enabled 

TZ.CsrModule = function(){
	var itemCtx = {};
	itemCtx.Templates = {};
	itemCtx.Templates.Fields = {
		'Description': { 'View' : TZ.CsrModule.DescriptionView },
		'Percent': { 
            'View': TZ.CsrModule.PercentView,
            'DisplayForm': TZ.CsrModule.PercentView,
            'NewForm': TZ.CsrModule.PercentEdit,
            'EditForm': TZ.CsrModule.PercentEdit
        },
		'email': {
            'NewForm': TZ.CsrModule.EmailEdit,
            'EditForm':  TZ.CsrModule.EmailEdit
        }
	};

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
}

TZ.CsrModule.DescriptionView = function(ctx){
	var bodyDesc = ctx.CurrentItem.Description;
	var regex = /(<([^>]+)>)/ig;
	bodyDesc = bodyDesc.replace(regex, "");
	if (bodyDesc && bodyDesc.length >= 150)
	 {
	 var newDesc = bodyDesc.substring(0,100);
	 }
	return "<span title='" + bodyDesc + "'font style='color:green'>" + newDesc + "</font></span>";
}

// This function provides the rendering logic for View and Display form
TZ.CsrModule.PercentView = function (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;'> \
             </div></div> " + percentComplete;

}

// This function provides the rendering logic for New and Edit forms
TZ.CsrModule.PercentEdit = function (ctx) {

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

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

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

}

TZ.CsrModule.EmailEdit = function (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 TZ.CsrModule.EmailValidator());

    // Validation failure handler.
    formCtx.registerValidationErrorCallback(formCtx.fieldName, TZ.CsrModule.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
TZ.CsrModule.EmailValidator = function () {
    TZ.CsrModule.EmailValidator.prototype.Validate = function (value) {
        var isError = false;
        var errorMessage = "";

        //Email format Regex expression
        var emailRejex = /\S+@\S+\.\S+/;
        
        if (!emailRejex.test(value) && value.trim()) {
            isError = true;
            errorMessage = "Invalid email address";
        }

        //Send error message to error callback function (emailOnError)
        return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
    };
};

// Add error message to spnError element under the input field element
TZ.CsrModule.EmailOnError = function (error) {
    document.getElementById("spnError").innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
}

TZ.CsrModule();

No comments:

Post a Comment

by Category