Update Field.JSLink using JSOM or REST
By Anatoly Mironov
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:
- A POST request
- with a header ‘X-HTTP-Method’: ‘MERGE’
- with __metadata: { type: SP.Field } and JSLink property in the payload
- and ‘X-RequestDigest’ header (but it is nicely handled by sharepoint-utilities)