1

How to update/set web part properties for example JSLink using CSOM JavaScript.

2
UpdateWebPartProperty();

function UpdateWebPartProperty()
{
    var listName = "list1";
    var jslinkURL = "~sitecollection/SiteAssets/testjslink.js";
    var pageUrl = "/Lists/" + listName + "/NewForm.aspx";

    var clientContext = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
    console.log(_spPageContextInfo.webServerRelativeUrl);
    var oFile = clientContext.get_web().getFileByServerRelativeUrl(_spPageContextInfo.webServerRelativeUrl + pageUrl); 
    var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    var collWebPart = limitedWebPartManager.get_webParts();

    clientContext.load(collWebPart);
    clientContext.executeQueryAsync(function () 
    {
        var webPartDef = null;
        for (var x = 0; x < collWebPart.get_count() && !webPartDef; x++) {
            var temp = collWebPart.get_item(x);
            console.log(temp.get_id().toString());
        }
        webPartDef = collWebPart.get_item(0);
        if (!webPartDef) {
            console.log("Web Part: " + wpId + " not found on page: " + _spPageContextInfo.webServerRelativeUrl);
            return;
        }
        var webPartProperties = webPartDef.get_webPart().get_properties();
        clientContext.load(webPartProperties);
        clientContext.executeQueryAsync(
            function () {
                var webpartprops = webPartProperties;
                console.log(webpartprops.get_item('JSLink'));
                webpartprops.set_item("JSLink", jslinkURL);
                webPartDef.saveWebPartChanges();
                clientContext.load(webPartDef);
                clientContext.executeQueryAsync(
                function () {
                    console.log("Web part properties saved.");
                },
                function() 
                {
                    console.log("Failed save Web part Properties"); 
                });
            }, 
            function () 
            { 
                console.log("Failed to load web part properties"); 
            });
    }, 
    function () { 
        console.log("Failed to load web part collection"); 
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.