Below you will find pages that utilize the taxonomy term “Csr”
Update Field.JSLink using JSOM or REST
Today I have just a little code snippet to share. This code snippet shows how to update the JSLink property for an existing field using JSOM and REST. For REST I use sharepoint-utilities. [code language=“javascript”] var updateJsLinkCsom = function(config) { var ctx = SP.ClientContext.get_current(); var web = ctx.get_web(); var lists = web.get_lists(); var list = lists.getByTitle(config.listTitle) var fields = list.get_fields(); var field = fields.getByInternalNameOrTitle(config.fieldTitle) field.set_jsLink(config.jsLink) field.update() ctx.executeQueryAsync() }; var updateJsLinkRest = function(config) { SP.SOD.registerSod(‘sputils.js’, ‘/sputils.min.js’) SP.SOD.executeFunc(‘sputils.js’, ‘’, function() { var url = _spPageContextInfo.webAbsoluteUrl + ‘/_api/web/lists/getbytitle(\’’ + config.listTitle + ‘\’)/fields/getbyinternalnameortitle(\’’+ config.fieldTitle + ‘\’)’; var payload = {’__metadata’: {’type’: ‘SP.Field’}, ‘JSLink’: config.jsLink}; var config = {‘headers’ : {‘X-HTTP-Method’: ‘MERGE’ }}; sputils.rest.post(url, payload, config); }); }; var config = { listTitle: ‘’, fieldTitle: ‘’, jsLink: ‘~site/’ }; updateJsLinkCsom(config); updateJsLinkRest(config); [/code] A couple of notes, to update a field we need:
Minimal Display Template
We want to use our own Display Templates on Non-publishing sites - our team sites. Without the Publishing Feature activated you have to create an own javascript file. Here is short and concise instructions how to install it: Display Templates on Non-publishing Sites. As described on that blog, you can make copy of an existing Item_Default.js and adjust to your needs. I also asked Elio Struyf and I got the same tip. I did create my starter template. Here I want to share this very minimal javascript based Display Template. The real Minimal Display Template is in the SPCSR github repository: Item_Minimal.js It has been improved by Elio Stuyf himself :) [code language=“javascript”] (function () { // Config contains variables that are defined in one place var config = { propertyMappings: { ‘Path’:null, ‘Title’:[‘Title’] } }; var templateUrl; var register = function () { if (“undefined” !== typeof (Srch) && “undefined” !== typeof (Srch.U) && typeof (Srch.U.registerRenderTemplateByName) === “function”) { Srch.U.registerRenderTemplateByName(templateUrl, render); } }; render = function (ctx) { // Display template data var cachePreviousTemplateData = ctx.DisplayTemplateData; ctx.DisplayTemplateData = { ‘TemplateUrl’: templateUrl, ‘TemplateType’: ‘Item’, ‘TargetControlType’: [‘SearchResults’, ‘Content Web Parts’], ‘ManagedPropertyMapping’: config.propertyMappings }; var cachePreviousItemValuesFunction = ctx.ItemValues; ctx.ItemValues = function(slotOrPropName) { return Srch.ValueInfo.getCachedCtxItemValue(ctx, slotOrPropName); }; // Retrieve managed property data var path = $getItemValue(ctx, ‘Path’); var title = $getItemValue(ctx, ‘Title’); // HTML markup for an item var htmlMarkup = String.format( ‘’ + ‘{1}’ + ‘’, path, title); // Caching ctx.ItemValues = cachePreviousItemValuesFunction; ctx.DisplayTemplateData = cachePreviousTemplateData; // Return the HTML markup return htmlMarkup; }; // Retrieve all the loaded scripts var allScripts = document.getElementsByTagName(“script”); // Get the last script file (this is the current DT file) var scriptUrl = allScripts[allScripts.length - 1].src; if (scriptUrl.indexOf(’/_catalogs/’) > 0) { // Remove the query string if (scriptUrl.indexOf(’?’) > 0) { scriptUrl = scriptUrl.split("?")[0]; } // Insert the site collection token templateUrl = ‘~sitecollection’ + scriptUrl.substr(scriptUrl.indexOf(’/_catalogs/’)) // Register the template to load register(); if (typeof (RegisterModuleInit) === “function” && typeof(Srch.U.replaceUrlTokens) === “function”) { RegisterModuleInit(Srch.U.replaceUrlTokens(templateUrl), register); } } })(); [/code]
Bypass all custom jslink
Client Side Rendering (CSR) and jslink are great for customizing lists and forms in SharePoint. In my current project we use it a lot of it. A disadvantage of that path, although, is that it might occur javascript errors, during the development phase, but also in production. We do, of course, our best to leverage the best jslink code, but unfortunately we have to live with the fact that errors can occur, especially when we use it for NewForm, EditForm, DisplayForm and View (in list and grid). If an error occurs, it won’t stop the rest of javascript (it is wrapped in try and catch by SharePoint), but the fields will still not function as intended. It can also be some “corrupt” or old data in the field value that will “break” the jslink code. I would like to suggest one little fix, an idea I’ve come up to in my jslink-heavy project:
Client Side Rendering with Async dependencies
Yesterday I asked a question on SharePoint StackExchange:
I also asked Elio Struyf on Twitter: https://twitter.com/eliostruyf/status/540473976255152128 Good idea, Elio Struyf! Now I want to try it out.
Preparations
In this case I’ll be using my example from my blog post yesterday: Drag and Drop Image using Client Side Rendering I have created a new list and added a lookup field to my previous list. What I get is a Title of the lookup item, but not my custom field called DragAndDrop. In my test I will try to load the DragAndDrop Image using an ajax call and rendering it after Client Side Rendering is done with my item. To be complete, I want to show some screenshots for my lookup field: It will result in this OOTB rendering:
Drag and Drop Image using Client Side Rendering
I continue my series about Client Side Rendering (CSR) and jsgrid. Today I want to try a custom field where users can drag and drop images. The inspiration comes from:
- AutoUpload field written by Anton Vishnyakov and
- Base64 Drag and drop written by oroboto
What I want to achieve is:
- A custom field that is rendered with jslink
- Users can drag and drop small pictures (thumbnails) into the field
- A base64 image representation is saved as the field value
- Optionally implement pasting images using Clipboard API
Step 1 Create a field with a custom jslink
Create a field of type Note. I am using the PnP Core Extensions to make it quickier: ’ My jslink file is very simple to begin with: [code language=“javascript”] (function () { ‘use strict’; function view(ctx, field) { return “hello”; } var overrideContext = {}; overrideContext.Templates = overrideContext.Templates || {}; overrideContext.Templates.Fields = { ‘DragAndDropImage’: { ‘View’: view, ‘DisplayForm’: view //‘EditForm’: verySimpleNewAndEdit, //‘NewForm’: verySimpleNewAndEdit } }; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext); })(); [/code] This will result in the following display form. Just outputting “hello” indicates that my field is jslink are registered correctly:
Disabling a column in Quick Edit
In my project I have a column called Request Status. This column is not shown in any forms, meaning users should not edit, because it is controlled through the app. Nevertheless it is editable in the Quick Edit. Yesterday I wrote about jsgrid in my blog. Now comes more. Today I’ll share a little practical solution how one can disable editing a field in Quick Edit. The field is edited in jsgrid, but to disable it, we only have set the property called AllowGridEditing to false on our column (not even touching the heavy jsgrid api). We can do in the OnPreRender event in our Client Side Rendering (CSR) registration. Having the context object we have access to the Fields (ContextInfo.ListSchema.Field): [code language=“javascript” highlight=“6,9”] (function () { var overrideContext = {}; overrideContext.Templates = overrideContext.Templates || {}; overrideContext.Templates.OnPreRender = function(ctx) { var statusField = ctx.ListSchema.Field.filter(function(f) { return f.Name === ‘Request_x0020_Status’; }); if (statusField) { statusField[0].AllowGridEditing = false; } } SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext); })(); [/code] Another way is to implement the display form: [code language=“javascript”] (function () { var view = function (ctx, field) { if (ctx.inGridMode) { field.AllowGridEditing = false; } return window.RenderFieldValueDefault(ctx); }; var overrideContext = {}; overrideContext.Templates = overrideContext.Templates || {}; overrideContext.Templates.Fields = { ‘Request_x0020_Status’: { ‘View’: view } }; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext); })(); [/code]