SharePoint JSLink: Multiple web parts on a page

With JSLink you have the ability to quickly and easily change how a list views and forms are rendered. Together with jQuery, CSS and even JavaScript you can present a SharePoint list in endless ways. JSLink works very well when you only one web part with a custom JSLink located on a page. The default behavior with multiple web parts on a page is that all web parts will use the JSLink. This is counter intuitive since we set the JSLink on one web part. With the solution below we can make sure that only the correct web part use the custom JSLink code. The solution is created in cooperation with Peter van Koesveld.

Solution

This solution works for a page where one web part needs to be modified by the JSLink.

  1. Create a JavaScript file with the following code: JSLinkMultipleWebParts.
  2. Change the if statements to match the name of the list.
    if (ctx.ListTitle == "ListTitle")
    
  3. Change the headerHtml, ItemHtml and footerHtml to show the list as required.
  4. In the example the Title field will be displayed, make sure this field is available.
  5. Save the JavaScript file to SharePoint.
  6. Set the JSLink property.

Explanation

  1. The JSLink overrides the default Templates (Header, Item and Footer).
  2. Then if the ListTitle equals the provided ListTitle the custom code is run for the header, Item and Footer.
  3. If the ListTitle does not match the default RenderTemplate will be used.
    function renderItem() {
        if (ctx.ListTitle == "ListTitle") {
            //CustomItemRender
        } else {
            //Return the default Item Template
        	return RenderItemTemplate(ctx);
        }
    }
    
    • RenderHeaderTemplate
      return RenderHeaderTemplate(ctx);
      
    • RenderItemTemplate
      return RenderItemTemplate(ctx);
      
    • RenderFooterTemplate
      return RenderFooterTemplate(ctx);
      

SharePoint JSLink: Accordion

With JSLink you have the ability to quickly and easily change how a list views and forms are rendered. Together with jQuery, CSS and even JavaScript you can present a SharePoint list in endless ways. In this example I will create a FAQ list with a accordion display style.

Solution

  1. Create a custom list called FAQ with a title and description field (Multiple Lines of Text).
  2. If required changed the fields to be shown.
  3. Create a page and add the FAQ web part to the page.
  4. Create the JSLink file called AccordionView.js
  5. Create the JavaScript file called accordion.js
  6. Create the CSS file called accordion.css
  7. Save the background image to SharePoint.
  8. Change the background-image URLs if needed.
  9. Link the JSLink to the web part to load the AccordionView.js.
  10. Add the accordion.js and accordion.css to the page, for example by using a Content Editor web part.
  11. Add jQuery to the page.
  12. Make sure that jQuery is loaded before the other JavaScript. Errors might otherwise be generated.

JavaScript / jQuery: Hide/show fields

With SharePoint we use a lot of lists and libraries to store and share information, we add and change this information with the help of forms. In most cases we create one form with all the information required for the content. Even if not all the information is required for all types of content or if it depends on a phase or status. With the help of jQuery and JavaScript we can create a more dynamic form that will hide/show fields based on selected values of fields. Make sure to disable the quick option, otherwise user will be able to edit the field outside of the provided solution.

SharePoint 2013/Online: Disable Quick edit

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Quick Edit to No

SharePoint 2010: Disable Datasheet editing

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Datasheet to No

JavaScript: New Form

  1. Open your favorite JavaScript Editor.
  2. Create a new JavaScript file called NewFormHideShow.js
  3. Add the following base code to the JavaScript file.

    $( document ).ready(function() {
       
    }
    );
  4. The first step is to hide the columns. Find the display names of the field that need to be hidden. Note that you need the name located in the HTML nobr tag.
  5. You can use a DOM explorer to find the correct names.
  6. For each field add the following code.
    $('nobr:contains("[Field Name]")').closest('tr').hide(); 
    
  7. In my example I hide two fields, Finalized Date and Finalized By. My example code for the document ready function is shown below.
    $(document).ready(function()
       {
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
       });
    
  8. The second step is to make the function that hides or shows the fields depended on the selected value.
  9. Add the following code to the JavaScript.
    (function($){
       function showHideRegionLocation() 
       {
          var FeedbackMatchingValue = 'Final';
    
          var thisDiv = $("select[title='Status']"); 
          var mmFieldValue = thisDiv.find("option:selected").text();
    		
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
    			
          if (mmFieldValue.indexOf(FeedbackMatchingValue) > -1) 
          {
             $('nobr:contains("Finalized Date")').closest('tr').show(); 
             $('nobr:contains("Finalized By")').closest('tr').show();
          } 					
       }
    
  10. Set the var FeedbackMatchingValue to the value which will show the hidden fields.
  11. Set the var thisDiv to the name of the Field that is used to show/hide the fields. Note that different types are just for different columns example Select or Input.
  12. Add the hide and Show codes. The code hides or show the table row (tr).
  13. Add the final function to the code. This part makes sure the functions runs when a users selects and/or reselects the option.
    $(document).ready(function() {
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });
    })(window.jQuery);
  14. Change the value after id^ to the field that contains the value on which field are being shown/hidden.
  15. The final code looks like this.
    $(document).ready(function()
       {
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
    });
    
    (function($){
       function showHideRegionLocation() 
       {
       var FeedbackMatchingValue = 'Final';
       
       var thisDiv = $("select[title='Status']"); 
       var mmFieldValue = thisDiv.find("option:selected").text();
    		
       $('nobr:contains("Finalized Date")').closest('tr').hide(); 
       $('nobr:contains("Finalized By")').closest('tr').hide();
    			
       if (mmFieldValue.indexOf(FeedbackMatchingValue) > -1) 
       {
          $('nobr:contains("Finalized Date")').closest('tr').show(); 
          $('nobr:contains("Finalized By")').closest('tr').show();
       } 	
    }
    
    $(document).ready(function() {
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });	
    })(window.jQuery);
    

JavaScript: Edit Form

  1. The edit form is almost completely the same, only the last function is different.
  2. Open your favorite JavaScript Editor.
  3. Create a new JavaScript file called EditFormHideShow.js
  4. Follow the steps 3 – 12 from the chapter JavaScript: New Form.
  5. Add the final function to the code. This part makes sure the functions runs when a users selects and/or reselects the option.
    $(document).ready(function() {
       setTimeout(function() {
          showHideRegionLocation();
       }, 1000);
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });	
    })(window.jQuery);
    
  6. Change the value after id^ to the field that contains the value on which field are being shown/hidden.
  7. The final code looks like this.
    $(document).ready(function()
       {
          $('nobr:contains("Finalized Date")').closest('tr').hide(); 
          $('nobr:contains("Finalized By")').closest('tr').hide();
    });
    
    (function($){
       function showHideRegionLocation() 
       {
       var FeedbackMatchingValue = 'Final';
       
       var thisDiv = $("select[title='Status']"); 
       var mmFieldValue = thisDiv.find("option:selected").text();
    		
       $('nobr:contains("Finalized Date")').closest('tr').hide(); 
       $('nobr:contains("Finalized By")').closest('tr').hide();
    			
       if (mmFieldValue.indexOf(FeedbackMatchingValue) > -1) 
       {
          $('nobr:contains("Finalized Date")').closest('tr').show(); 
          $('nobr:contains("Finalized By")').closest('tr').show();
       } 	
    }
    $(document).ready(function() {
       setTimeout(function() {
          showHideRegionLocation();
       }, 1000);
       $("select[id^='Status'").on('blur', showHideRegionLocation).on('change', showHideRegionLocation);
       });	
    })(window.jQuery);

Adding JavaScript to a form

  1. Open the edit and/or new form of the list.
  2. Set the form in edit mode
  3. Add the Script Editor Web Part to the page
  4. Edit the SNIPPET and add the following code.

    <script src="../../SiteAssets/System/jquery-3.1.1.min.js" type="text/javascript"></script> 
    <script src="../../SiteAssets/System/EditFormHideShow.js" type="text/javascript"></script>
    
  5. Insert the code en Stop editing the form.
  6. Save the custom JavaScript HideColumns and the jQuery script in the correct location.
  7. The JavaScript will now run and hide or shows the field based on the selected value of the field Status.

 

JavaScript / jQuery: Set fields to read only

With SharePoint we use a lot of lists and libraries to store and share information. But not every bit of information needs to be managed/changed by users. Sometimes a workflow or code is responsible for the information. With default SharePoint it is not possible to set field to read only,  but with the help of jQuery and JavaScript we can. We can add JavaScript to the new and or edit form and disable (read only) any field we want. Make sure to disable the quick option, otherwise user will be able to edit the read only field using this feature.

SharePoint 2013/Online: Disable Quick edit

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Quick Edit to No

SharePoint 2010: Disable Datasheet editing

  1. Open the list or library settings
  2. Open the Advanced settings
  3. Set Datasheet to No

Creating the JavaScript

  1. Open your favorite JavaScript Editor
  2. Create a new JavaScript file called HideColumns.js
  3. Add the following base code to the JavaScript file
    // A $( document ).ready() block.
    $( document ).ready(function() {
       
    }
    );
    
  4. Now you need to get the display names of the fields you need to set to read only (disable). Note that you need the correct name of the input, select, text area etc fields. Make sure you do not select the label of the field.
  5. You can use a DOM explorer to find the correct type of fields and the corresponding name. Note that different types are just for different columns
  6. In this example I selected the Multiple Lines of text field
  7. The selected code is
  8. In this code you are able to find the name: Multiple Lines
  9. And the type of field: textarea
  10. Do this for all the fields you need disable
  11. In my example I will disable the following fields
    Name Column Type Input field type
    Multiple Lines Multiple lines of text Textarea
    Title Single line of text Input
    Date Date and time Input
    Choice Choice Select
  12. Depended on the type of field different code is required.
  13. For Input and textarea use
    .attr("disabled", "disabled"); 
    
  14. For select we use
    .prop("disabled", true);
    
  15. The final code will look as follows
    // A $( document ).ready() block.
    $( document ).ready(function() {
        jQuery("input[title='Title']").attr("disabled", "disabled"); 
        jQuery("textarea[title='Multiple Lines']").attr("disabled", "disabled");
        jQuery("input[title='Date']").attr("disabled", "disabled"); 	
        jQuery("select[title='Choice']").prop("disabled", true);
        }
    );
    

Adding JavaScript to a form

  1. Open the edit (or new) form of the list.
  2. Set the edit form in edit mode
  3. Add the Script Editor Web Part to the page
  4. Edit the SNIPPET and add the following code

    <script src="../../SiteAssets/System/jquery-3.1.1.min.js" type="text/javascript"></script> 
    <script src="../../SiteAssets/System/HideColumns.js" type="text/javascript"></script> 
    
  5. Insert the code en Stop editing the form.
  6. Save the custom JavaScript HideColumns and the jQuery script in the correct location
  7. The JavaScript will now run and set the required field on read only when the edit form is opened

Add new page button

SharePoint has multiple ways to add pages. It can be done in the document library (pages) or through the settings drop-down menu. For most users these are not the most practical and easy. An easier and faster way is to simply add a hyperlink or button on a page for user to click on. My favorite method is to add a button on the page in SharePoint style. The hyperlink I am using is exactly the same as the hyperlink in the settings drop-down menu.

ButtonAddPage

Solution with hyperlink only
1. Edit the page where the button needs to be placed.
2. Add a Script Editor web part to the page.
3. Add the following code in the script editor.

 <a onclick="if (LaunchCreateHandler(&#39;PublishingPage&#39;)) { SP.SOD.executeFunc(&#39;sp.ui.dialog.js&#39;, &#39;SP.UI.ModalDialog.showModalDialog&#39;, function() { var dlgOptions = { url:&#39;\u002fsites\u002fknowledge\u002fBestPractice\u002f_layouts\u002f15\u002fCreatePublishingPageDialog.aspx&#39;, autoSize: true, autoSizeStartWidth: 550 }; SP.UI.ModalDialog.showModalDialog(dlgOptions); }); };" href="#">  
      new page  
 </a>  

4. Publish the page.

Solution with button SharePoint style
1. Edit the page where the button needs to be placed.
2. Add a Script Editor web part to the page.
3. Add the following code in the script editor.

 <div class="ms-comm-heroLinkContainer">  
   <a onclick="if (LaunchCreateHandler(&#39;PublishingPage&#39;)) { SP.SOD.executeFunc(&#39;sp.ui.dialog.js&#39;, &#39;SP.UI.ModalDialog.showModalDialog&#39;, function() { var dlgOptions = { url:&#39;\u002fsites\u002fknowledge\u002fBestPractice\u002f_layouts\u002f15\u002fCreatePublishingPageDialog.aspx&#39;, autoSize: true, autoSizeStartWidth: 550 }; SP.UI.ModalDialog.showModalDialog(dlgOptions); }); };" href="#" class="ms-textXLarge ms-heroCommandLink">  
    <span class="ms-list-addnew-imgSpan20">  
      <img class="ms-list-addnew-img20" src="/_layouts/15/images/spcommon.png?rev=23">  
 </span>new page  
 </a>  
 </div>  

4. Publish the page.

Display Template Show Limits Characters

Display templates are used to show the queried results in a attractive and useful layout. With the CQWP we used XSLT to format the data as required, but with display templates we need to use JavaScript. One of my most formatted field is the publishing page content field. In this blog post I will explain how you can limit the number of characters shown. In this post I also explain how to remove the HTML markup.

Solution publishing page content
1. Edit the related Item Template.
2. Add the PublishingPageContent to the ManagedPropertyMapping. For a clean example I removed all mappings besides Title and PublishingPageContent.

<mso:ManagedPropertyMapping msdt:dt="string">'Titel':'Title','PublishingPageContent':'PublishingPageContentOWSHTML'</mso:ManagedPropertyMapping>

3. Create a variable for the PublishingPageContent column.

var PublishingPageContentHTML = $getItemValue(ctx, "PublishingPageContent");

4. The PublishingPageContentHTML will contain the page content but with styling. The following code will remove the styling.

var div = document.createElement("div");
div.innerHTML= PublishingPageContentHTML;
var PublishingPageContentL = div.textContent|| div.innerText|| "";

5. In most situations we also want to show a maximum number of characters followed bu three dots. The following code will limit the amount of characters to 175 followed by the required dots. If the content is less then 175 characters long, no dots will be displayed.

var PublishingPageContent = "";
if (PublishingPageContentL.toString().length > 175) {
	PublishingPageContent = PublishingPageContentL.toString().substring(0,175) + "...";
}
else {
	PublishingPageContent = PublishingPageContentL;
}

6. Us the code below to display the PublishingPageContent.

<div>
   _#= $htmlEncode(PublishingPageContent ) =#_
</div>

 

Result

CSWP Result