I had the requirement to change the JSLink for my custom list for all the subsites of a site collection. You would normally do this via PowerShell. My customer is using Office365 (what all customers should do…) and therefore are the possibilities of PowerShell limited. I found quite some examples on how to update a JSLink of a Web Part via the UI. However I wanted to update the JSLink via code.
I started with the project Contoso.ApplyBranding.Console from the Office App Model Samples which is btw a great starting point for working with SharePoint Apps. The example I used is a console app project which has a settings.xml file in which you can add all the sites that have to be updated.
//Loop through all sites from the settings.xml
foreach (var site in branding.Element(“sites”).Descendants(“site”))
{
var siteUrl = url.TrimEnd(trimChars) + “/” + site.Attribute(“url”).Value.TrimEnd(trimChars);
using (ClientContext clientContext = new ClientContext(siteUrl))
{
//Connect to the SharePoint Online site
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = credentials;
clientContext.Load(clientContext.Web);
clientContext.ExecuteQuery();
//Get the list
List list = clientContext.Web.Lists.GetByTitle(“Listtest”);
clientContext.Load(list);
clientContext.Load(list.Forms);
clientContext.ExecuteQuery();
//Get all the forms
foreach (var spForm in list.Forms)
{
//Get the edit form
if (spForm.ServerRelativeUrl.Contains(“EditForm.aspx”))
{
File file = clientContext.Web.GetFileByServerRelativeUrl(spForm.ServerRelativeUrl);
LimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
clientContext.Load(wpm.WebParts,
wps => wps.Include(
wp => wp.WebPart.Title));
clientContext.ExecuteQuery();
//Set the properties for all web parts
foreach (WebPartDefinition wpd in wpm.WebParts)
{
WebPart wp = wpd.WebPart;
wp.Properties[“JSLink”] = “~/sitecollection/Style Library/customer/customization.js”;
wpd.SaveWebPartChanges();
clientContext.ExecuteQuery();
}
}
}
}
}
So this is the result:
If you want you can of course also add your site collections to the settings.xml file and loop through them as well.