2

Is it possible to update the SPForm.JSLink property for the forms (Display, New, Edit) of an existing list in the when a feature is activated?

I have tried the code below, but it seems that the change is not being applied (i.e. the JSLink property is null on subsequent feature activations):

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    // ...
        someList.Forms.Cast<SPForm>().ToList().ForEach(form =>
        {
            form.JSLink = "~sitecollection/style library/myScript.js?v=" + Assembly.GetExecutingAssembly().FullName;
        });
    // ...
}

I have also tried calling someList.Update() after assigning the property, but still no effect.

1
  • Have you tried someList.Update(); after the foreach is done?
    – user2536
    Commented Oct 16, 2013 at 7:56

4 Answers 4

5

Here is the C# version of Anders answer as it was not as straightforward as I would have thought.

public static void SetFormJSLink(this SPList list, PAGETYPE formBaseView, string jsLinkUrl)
{
    var file = list.ParentWeb.GetFile(list.Forms[formBaseView].Url);
    file.CheckOut();

    using (var manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
    {
        var webPart = manager.WebParts.OfType<ListFormWebPart>().FirstOrDefault();
        if (webPart != null)
        {
            webPart.JSLink = jsLinkUrl ?? string.Empty;
            manager.SaveChanges(webPart);
        }
    }

    file.CheckIn("Added JSLink to the Form");
}
3

It seems that for JSLink to work on the display/new/edit forms you need to set the JSLink on the webpart used in the forms, not directly on the form itself.

The following PowerShell code works for the new form on a blog post and should be easy to adopt to your needs in C#:

$web = Get-SPWeb "http://myportal"
$file = $web.GetFile("Lists/Posts/NewPost.aspx")
$file.CheckOut()

$webPartManager = $web.GetLimitedWebPartManager("Lists/Posts/NewPost.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpart = $webPartManager.WebParts[0]
$webpart.JSLink = "YOUR JS URL HERE"

$webPartManager.SaveChanges($webpart)
$file.CheckIn("")
0

Have you tried setting the JSLink property on the SPView rather than the form?

And call Update() on the view.

Note: I am also having problems with JSLink loading inconsistently!

0

yes, setting property on view works!

var docwp = (XsltListViewWebPart)wpm.WebParts.Cast<System.Web.UI.WebControls.WebParts.WebPart>().FirstOrDefault(wp => wp.Title.Equals("Documents"));
    docwp.View.JSLink = "~sitecollection/_layouts/15/styles/dscs/fancyDates.js";
    docwp.View.Update();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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