Download presentation
Presentation is loading. Please wait.
Published byChristopher Atkins Modified over 7 years ago
1
Rendering SharePoint lists using jQuery DataTables
Kyle Petersen Portland SharePoint Saturday 2016
2
Kyle Petersen kyle@pdxportals.com
Independent SharePoint Consultant PDX Portals Software Development (20+ Years) SharePoint (11 years) 2003 / 2007 / 2010 / 2013 / 2016 Office 365 Microsoft Certified Master SharePoint 2010
3
Agenda Overview Data Tables capabilities
Adding Data Tables to SharePoint Filtering Advanced Scenarios Resources
4
Creating tabular results
Use jsLink and Client Side Rendering Interesting mixture of JavaScript and HTML Data Retrieval is done for you XSLT Web Parts Technically still supported, but complex XSLT required jQuery injection Reformat existing SharePoint Lists Dom is crazy complex
5
So what are DataTables? DataTables is a jQuery Extension
Requires basic HTML and JavaScript Need to be comfortable with JavaScript and jQuery Adds additional functionality to ordinary HTML <table> Sorting Filtering Formatting Pagination Sticky headers to keep column headers visible while scrolling Responsive interface
7
Demo 1 Basic DataTable
8
Think about SharePoint is moving to client side processing
jsLink Add-In model New SharePoint Framework This approach can be implemented in a variety of ways Script Editor web part SharePoint Framework Web Part SharePoint Hosted Add-In (yuck)
9
Approach There are five stages we need to address
1) Create the HTML Template 2) Query SharePoint 3) Parse the data and dynamically build an HTML Table 4) Build the HTML table rows 5) Render the DataTables
10
Requirements Include jQuery in page Include dataTables .js library
Include dataTables .css styles Methods Load from CDN Download files and manually load into SharePoint Site Package as Feature / Add-In and deploy into selected sites
11
Data Tables in SharePoint
Data Tables requires .js and .css files DataTables site has a Download Builder Single Minified Versions (Includes the options you require) Loaded into local site collection site assets library <link rel="stylesheet" href="//<siteUrl>/SiteAssets/datatables.min.css"> <script src=" Or load from CDN Resource Talk about dataTables downloader Combine multiple script and CSS files into a single minified file Explain the CDN url
12
Getting Data Tables on the Page
SharePoint Page Add a Content Editor Web Part Point to external File Data Tables Files HTML + JavaScript Stored in a SharePoint library Version Control Make changes without having to edit page
13
DataTable Essentials Demo 2 Retrieve data from SharePoint List
Render the table Invoke DataTables DataTable Essentials
14
Process
15
Namespace declaration
Code Structure Sample Javascript is written using namespaces to encapsulate code. // define our namespace if (typeof(SPS) == "undefined") { var SPS = Init: function() { try { // // If we are editing the page don't bother doing the query var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value; if (inDesignMode == "1") { // page is in edit mode return; } SPS.Query(); catch (err) { SPS.ReportError(err.message); }, Namespace declaration Declaring Functions Namespaces are really important With everything moving to client side there is a lot more scripting going on. Name spaces ensure there is no collisions Calling Functions Error Handling
16
Template Here is our basic HTML template
Just define the header for now We will inject the table rows when we get the data from sharepoint
17
Step 2 SharePoint Query - Query()
Several Options for retrieving the data SP Services (spservices.codeplex.com) JSOM (JavaScript Object Model) REST (SharePoint Web Services) Example code will just use REST API to Retrieve data There are trade-offs for each method REST is limited to 1000 rows Which probably makes the best performance sense. SP Services has some nice wrappers for dealing with the old SOAP web services
18
Query() Here is what we want to retrieve
Send the query results to SPS.Build() Explain the REST query jQuery helper getJSON When it’s done call SPS.Build if it fails send the erro to SPS.ReportError Note this list has xxx rows so I’m only bringing back 2004 data to keep the number of results small.
19
Step 3 Process Result Use jQuery to parse result
REST: $.each(data.d.results), function() … Iterates over each row of the result Extract values from results Store values into JavaScript variables Try Catch handler to report errors Alerts, logging or analytics
20
Send each record to SPS.Parse()
Process Results Send each record to SPS.Parse() Build gets all the rows of data In demo put an alert() and show the full result We build the HTML table $.each iterates over each row in the results and sends it to Parse When we are done close the body and append it into the table
21
Step 4 Build HTML Table Create the table body element liHTML = ‘<tbody>’ Inject Rows into the body Template liHTML += ‘<tr><td>value</td><td>value</td></tr>’ Close out the body liHTML = ‘</tbody>’ Inject the body into the table $(‘#example’).append(liHTML);
22
Parse Parse gets called once for each row
We pull out the data from the objects And build the table row Architecturally this is not really a great practice to be updating this global object (SPS.body) but this pretty clear to understand
23
Step 5 -Render Now that we have the HTML table we just invoke dataTable dataTable or DataTable both work Here we are just using a couple of the simple parameters
24
Demo 3 So far we have not really done anything that a simple list view could not do. Let’s add some filtering capabilities Filtering
25
Filtering Notes Invoke fnFilter function on dataTable
Filter as a regular expression So we match just “1” and not 1, 11, 12,…
26
Demo 4 The fnFilter is great to filter out data that is already there, but sometimes we want to limit how much data we retrieve Query Filters
27
Query Notes Add filter= parameter to the REST call
With a little code structure change we pass in the Year to the Query
28
Editing Tips and Tricks
Don’t forget about publishing / versioning When the Data Table file is checked out to you, only you will see the changes. You can Check In a minor version so other authors can view changes Only major versions are visible to site visitors SharePoint Designer is the preferred tool for editing content in SharePoint. Office 365 has great new build-in JavaScript editor Files must be named xxx.js instead of xxx.html
29
Debugging Tricks Use Alert() to view variables
Use debugger; to cause Chrome debugger to stop at that point Make small changes and test frequently
30
DataTable Options Destroy – ensures old data is removed when the table is rebuilt Paging – controls the pagination controls Info – row count at the bottom of the page bFilter – Search box to filter results aaSorting – default sort order aoColumns – customize each column (add css classes) fixedHeader: Enables sticky headers* Responsive – enable the responsive features *
31
Demo Styling
32
Formatting Include additional CSS file for /sites/sps-2016/Style Library/css/football.css Inject CSS Classes as part of data table aoColumns:[ {bVisible:false }, {sClass: "week“ }, {sClass: "teamLogo“ }, {sClass: "team“ }, {sClass: "score“ }, {sClass: "teamLogo“ }, {sClass: "team“ }, {sClass: "score“ } ] Alternate syntax (target specific columns by index) aoColumnDefs: [ {bVisible: false, aTargets: [0] }, {sClass: "week", aTargets:[1] }, {sClass: "teamLogo", aTargets:[2,5] }, {sClass: "team", aTargets:[3,6] }, {sClass: "score", aTargets:[4,7] } ] Note CSS selectors have td.week and not just .week . SharePoint CSS has some specific selectors that target TD elements so we have to be more specific (or use !important) to make sure our styles take precedence. aoColumns vs aoColumnDefs
33
Formatting options aaSorting bSearchable bVisible sClass sType
Control default sorting bSearchable Enable / Disable filtering on a column bVisible Show / hide a column sClass Css class sType Data type to use for sorting
34
Smoke and Mirrors ‘Result’ <Div> is initially hidden and is shown when the results are parsed Loading Message displays while query is being processed
35
Demo 6 - Responsive
36
Responsive Add Responsive property to data Tables
Remember, you have to include the Responsive capabilities
37
Demo 7 – Sticky headers
38
Sticky Headers Enable using fixedHeader option
"fixedHeader": {header:true, headerOffset: headerOffsetAmount} Header Offset positions the column header below menu and ribbon bar (if visible) var headerOffsetAmount = $('#portalBar').height() + $('.ms-cui-ribbonTopBars').height();
39
Review Include DataTables (jQuery, js & css) Create the table template
Query the data Parse the results Build the Table Render the DataTable
40
Usage Ideas Retrieve data from other sites or web applications
Combine data from multiple sources Handle really large lists Display non-SharePoint data Create highly stylized tables
41
Resources https://jquery.com/ https://datatables.net/
42
Additional Resources http://stackoverflow.com/search?q=datatable
instant&ion=1&espv=2&ie=UTF- 8#q=dataTables%20example%20site%3Ajsfiddle.net
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.