SharePoint JS Link file reference globally - sharepoint

I would like to ask that I have one document library with more than 20 views. I have implemented one JS link file to render required changes in the view.
My query is that is there any way to declare this JS link file globally for all the Document library views instead of adding reference in each view.
Thanks in advance

You could Update JS Link of list views Using PowerShell. Put all view links into an array and then iterating the links.
Sample script:
$webpartPages = "/Lists/Tickets/AllItems.aspx","/document%20li/Forms/1.aspx","/document%20li/Forms/2.aspx","/document%20li/Forms/AllItems.aspx";
$web = Get-SPWeb http://url;
foreach($webpartPage in $webpartPages ){
$file = $web.GetFile($webPartPage)
$file.CheckOut()
$webPartManager = $web.GetLimitedWebPartManager($webPartPage, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpart = $webPartManager.WebParts[0]
$webpart.JSLink = "~sitecollection/SiteAssets/test12.js"#If you have placed your JS inside SiteAssets library of some CHILD site, you should use ~site/SiteAssets/... url.If you have placed your JS inside SiteAssets library of root site of site collection, you should use ~sitecollection/SiteAssets/... url.
$webPartManager.SaveChanges($webpart)
$file.CheckIn("Awesomeness has been delivered")
}
Or you could upload the js file to the SharePoint library, then modify the master page in sharepoint designer, add <script type = "text/javascript" src = "http://url/SiteAssets/test12.js"> </script> to import the js file ,
You need to pay attention to determine whether current view is target view based on the URL in the js file, otherwise it may affect other pages.
Sample script :
if (window.location.href.toLowerCase().indexOf('document%20li') > 0) {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPostRender: function (ctx) {
var rows = ctx.ListData.Row;
for (var i = 0; i < rows.length; i++) {
var isApproved = rows[i]["testColumn"] == "Arvind Kushwaha1575353984864";
if (isApproved) {
var rowElementId = GenerateIIDForListItem(ctx, rows[i]);
var tr = document.getElementById(rowElementId);
tr.style.backgroundColor = "#ada";
}
}
}
});
}

Related

SharePoint hide spfieldurl column description(Type of description)

I am trying not to have the column description for field type "URL" in SharePoint 2016. I want to use this OOTB column URL, but not get "Type the description". The only work around i saw is using JavaScript. I wanted to know, is there any other way remove it?
Programmatically, or some property in schema.xml?
Any suggestions and help is appreciated.
Thanks,
Menon
Sample JSlink script for you.
You could upload jQuery library and the custom jslink library to SharePoint library, I upload to layouts folder just for easy testing.
script:
(function () {
var JSHyperlinkFieldCtx = {};
JSHyperlinkFieldCtx.Templates = {};
JSHyperlinkFieldCtx.Templates.Fields = {
"JSHyperlink": {
"NewForm": HideJSHyperlinkTemplate
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(JSHyperlinkFieldCtx);
})();
function HideJSHyperlinkTemplate(ctx) {
var result = SPFieldUrl_Edit(ctx);
var $f = $(result);
$f.find('span:eq(1)').css('display', 'none');
$f.find('input:eq(1)').css('display', 'none');
return $f.html();
}
use the script:
~sitecollection/_layouts/15/jslinks/jquery-1.12.4.js|~sitecollection/_layouts/15/jslinks/HyperlinkField.js

ServiceStack InMemoryVirtualPathProvider for Razor - GetViewPage null

I tested this with the default out of the box implementation and GetViewPage retrieves the view from the file system without a problem.
I swapped out the RazorFormat's VirtualFileSource for the inmemory one:
Plugins.Add(new RazorFormat() {
VirtualFileSources = new InMemoryVirtualPathProvider(this),
});
In the service I'm writing a view if it doesn't exist:
var helloView = razor.GetViewPage(email.BlastId.ToString());
if (helloView==null)
{
((InMemoryVirtualPathProvider)razor.VirtualFileSources)
.WriteFile("~/views/"+email.BlastId + ".cshtml", email.Blast);
// .WriteFile(email.BlastId + ".cshtml", email.Blast); doesn't work
}
helloView = razor.GetViewPage(email.BlastId.ToString());
//helloView is always null
I've confirmed that the RazorFormat's VirtualFileSource has the file, the GetViewPage just doesn't retrieve it.
Screenshot of the file located in the VirtualFileSource: https://db.tt/8oirKd9Msi
Furthermore this returns true: razor.VirtualFileSources.FileExists("~/views/"+email.BlastId + ".cshtml") I've tried it without the views folder/etc. It doesn't seem to make an impact.
The RazorFormat loads compiled views on Startup, so the view needs to exist in the VirtualFileSources before RazorFormat is registered in order for it to be available with GetViewPage().
To add a file after RazorFormat has loaded, you need to call AddPage() after it's written to the Virtual File System, e.g:
razorFormat.VirtualFileSources.WriteFile(filePath, contents);
var razorView = razorFormat.AddPage(filePath);
If you only wanted to create a temporary Razor View you can call CreatePage() to create the view:
var razorView = razorFormat.CreatePage(razorHtml);
And render it with:
razorFormat.RenderToHtml(razorView, model);
Or if both the Razor Page and model is temporary, it can be condensed in the 1-liner:
var html = razorFormat.CreateAndRenderToHtml(razorHtml, model);
Working Example
const string template = "This is my sample view, Hello #Model.Name!";
RazorFormat.VirtualFileSources.WriteFile("/Views/simple.cshtml", template);
var addedView = RazorFormat.AddPage("/Views/simple.cshtml");
var viewPage = RazorFormat.GetViewPage("simple"); //addedView == viewPage
var html = RazorFormat.RenderToHtml(viewPage, new { Name = "World" });
html.Print(); //= "This is my sample view, Hello World!"

Customizing the sharepoint document set

I have to customize sharepoint 2013 document set welcome page(document set properties web part) and
I am not able to find the document set home aspx page
Can I use any client context model to fetch the data and display doc set properties.
Just create a new content type inheriting from Document Set, add the extra columns and set which ones need to be shown on the welcome page via the Document Set settings link when editing the Content Type. Also under the Document Set settings page you can click on 'Customize the Welcome Page' which allows you to edit the page just like any other web part page.
On the second point the client context will need to be connected to the web that contains the list and specific document set you're after, the identity used to connect will need permissions to the document set.
Edit:
To customize the look and feel by injecting JavaScript/CSS you'll need to make use of the ScriptLink custom action.
This lets you inject a custom piece of JavaScript into all pages. In the script you'll need logic to determine if the custom CSS should be applied, and if so Inject it.
The C# for injecting a script block via ScriptLink Custom Action:
public void AddJsLink(ClientContext ctx, Web web)
{
string scenarioUrl = String.Format("{0}://{1}:{2}/Scripts", this.Request.Url.Scheme,
this.Request.Url.DnsSafeHost, this.Request.Url.Port);
string revision = Guid.NewGuid().ToString().Replace("-", "");
string jsLink = string.Format("{0}/{1}?rev={2}", scenarioUrl, "injectStyles.js", revision);
StringBuilder scripts = new StringBuilder(#"
var headID = document.getElementsByTagName('head')[0];
var");
scripts.AppendFormat(#"
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '{0}';
headID.appendChild(newScript);", jsLink);
string scriptBlock = scripts.ToString();
var existingActions = web.UserCustomActions;
ctx.Load(existingActions);
ctx.ExecuteQuery();
var actions = existingActions.ToArray();
foreach (var action in actions)
{
if (action.Description == "injectnavigation" &&
action.Location == "ScriptLink")
{
action.DeleteObject();
ctx.ExecuteQuery();
}
}
var newAction = existingActions.Add();
newAction.Description = "injectnavigation";
newAction.Location = "ScriptLink";
newAction.ScriptBlock = scriptBlock;
newAction.Update();
ctx.Load(web, s => s.UserCustomActions);
ctx.ExecuteQuery();
}
Then your JavaScript would have something like:
if(window.location.href.indexOf(patternToMatchToDocSetpage)>-1) {
var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
}
I'd advise you to take a look at the relevant PnP sample on script link injection

Making jslink target specific list

Background
I got a page where I’m showing two list views from two separate lists which both have Custom List as their ListTemplate. They got their separate jslink file cause I don’t want them to look alike.
Problem
The js link file targets both listviews since they use the same Template.
Code
(function () {
var listContext = {};
listContext.Templates = {};
listContext.ListTemplateType = 100;
listContext.Templates.Header = "<div><ul>";
listContext.Templates.Footer = "</ul></div>";
listContext.Templates.Item = LinkTemplate;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(listContext);
})();
Question
Is there any way to make the js only target a specific list?
Ended up going with Paul Hunts solution that he writes about on myfatblog.co.uk. http://www.myfatblog.co.uk/index.php/2013/09/listview-web-part-issues-with-jslink-and-display-templates-a-solution/
The script ended up looking like this and I pasted it into the jslink function where I define what listContext to override.
// Override the RenderListView once the ClientTemplates.JS has been called
ExecuteOrDelayUntilScriptLoaded(function(){
// Copy and override the existing RenderListView
var oldRenderListView = RenderListView;
RenderListView = function(ctx,webPartID)
{
// Check the title and set the BaseViewId
if (ctx.ListTitle == "List")
ctx.BaseViewID = "list";
//now call the original RenderListView
oldRenderListView(ctx,webPartID);
}
},"ClientTemplates.js");

Accessing Page datafolder data from C#

I defined a Page datafolder in the Data view and created data for one of my pages.
How can I access this data from an ASP.NET usercontrol placed on the page?
Here is a small code sample for getting page folder data for a given page folder type. Change the type Martin.MyPageFolder to your type and it should work just fine.
using (DataConnection connection = new DataConnection())
{
var pageFolderData =
from d in connection.Get<Martin.MyPageFolder>()
where d.PageId == SitemapNavigator.CurrentPageId
select d;
foreach (var item in pageFolderData)
{
// Use the item here as you need
}
}

Resources