Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Thursday, 5 May 2016

Bind Sharepoint list to Jquery Datatable in SharePoint Hosted App

In this post i am going to describe how you can bind SharePoint list to Jquery datatable (just like grid view) with rich features like Export to excel, Export to PDF etc.


Key Points:

  • Querying people picker and lookup columns using REST API
  • Getting 5000 items in one query
  • Showing first column as hyperlink column to my list item display form.
  • Change column header name dynamically after page load
  • Export to excel, pdf, notepad, csv
  • List view search
  • Paging
  • This grid can be added as app part in sharepoint page as well (Same like list view webpart with rich features)
Thanks to this article. 

Steps:
  1. Create SharePoint hosted app using VS ( i used 2013).
  2. Added below code to default.aspx page.
  3. Add references to your datatable js files
 <link rel="stylesheet" href="../Scripts/css/DashboardStyle.css" />
     <link rel="stylesheet" href="../Scripts/css/dataTables.tableTools.css" />
     <link rel="stylesheet" href="../Scripts/css/jquery.dataTables.css" />
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="../Scripts/EmployeeLists.js"></script>
    <script type="text/javascript" src="../Scripts/jquery.datatables-1.9.4.min.js"></script>    
    <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
   <script type="text/javascript" src="../Scripts/dataTables.tableTools.js"></script>

4. Add HTML in div tag

 <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
         <table id="employeeList" class="table table-striped table-bordered1 table-condensed table-hover table-fullfixed">
            <thead>
                <tr>
                    <th >Title</th>
                    <th>Last Name</th>
                    <th>Email</th>
                    <th id="week1th">Week1Date</th>
                    <th id="week2th">Week2Date</th>
                    
               
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
5. Created one js file and added below code, change column names and list name accordingly.

'use strict';
var hostweburl;
var appweburl;
var _listName;
var employeeListQueryUrl;
var EmployeesList = 'EmployeesList';
// This code runs when the DOM is ready and creates a context object which is   
// needed to use the SharePoint object model  
$(document).ready(function () {
    
   
    //Get the URI decoded URLs.   
    hostweburl =
        decodeURIComponent(
            getQueryStringParameter("SPHostUrl"));
    appweburl =
        decodeURIComponent(
            getQueryStringParameter("SPAppWebUrl"));
    // Resources are in URLs in the form:  
    // web_url/_layouts/15/resource  

    var scriptbase = hostweburl + "/_layouts/15/";

// Using below string i am querying 5000 items and getting values of People picker column, lookup column as well.


    employeeListQueryUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbyTitle('" + EmployeesList + "')/Items?@target='" + hostweburl + "'&$select=Title,LastName,Email,ContactNo,Address,ID,PP/ID,PP/Title,Lookup/ID,Lookup/Title&$expand=PP/ID,PP/TitleLookup/ID,Lookup/Title&$orderby=Created asc&$top=5000";



    // Load the js file and continue to load the page with information about the list top level folders.  
    // SP.RequestExecutor.js to make cross-domain requests  

    // Load the js files and continue to the successHandler  
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});

// Function to prepare and issue the request to get  
//  SharePoint data  
function execCrossDomainRequest() {
    var executor;
    executor = new SP.RequestExecutor(appweburl);

    executor.executeAsync(
        {
            url: employeeListQueryUrl,
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: employeeSuccessHandler,
            error: errorHandler
        }
    );
   
}

function employeeSuccessHandler(data) {
    var jsonObject = JSON.parse(data.body);
    var results = jsonObject.d.results;
    fillData(results, EmployeesList);
    $('#employeeList').dataTable({
        "fnRowCallback": function (nRow, results, iDisplayIndex) {
            $('td:eq(0)', nRow).html('<a target="_blank" href="' + hostweburl + '/Lists/' + EmployeesList + '/Dispform.aspx?ID=' + results[0] + '">' +
            results[0] + '</a>');

            //$('td:eq(0)', nRow).html('<a target="_blank" href="' + hostweburl + '/Lists/' + EmployeesList + '/Dispform.aspx?ID=' + results[0] + '"><img src="../Images/View_icon.png" border="0"/></a>');
        return nRow;
        },

        //"createdRow": function (row, results, index) {
        //    if (results[2].indexOf('Y') == 1) {
        //        $('td', row).eq(2).addClass('highlight');
        //    }
        //},   
       
    });    
    var table = $('#employeeList').dataTable();
    var tableTools = new $.fn.dataTable.TableTools(table, {        

        aaSorting: [[4, 'desc']],
        'aButtons': [
            {
                'sExtends': 'xls',
                'sButtonText': 'Save to Excel',
                'sFileName': 'Data.xls'
            },
            {
                'sExtends': 'print',
                'bShowAll': true,
            },
            {
                'sExtends': 'pdf',
                'bFooter': false
            },
            'copy',
            'csv'
        ],       
      
        'sSwfPath': '//cdn.datatables.net/tabletools/2.2.4/swf/copy_csv_xls_pdf.swf'
    });
    document.getElementById('week1th').innerHTML = "Dynamic Column Name";

}

function errorHandler(data, errorCode, errorMessage) {
    alert(data + ' >> ' + errorCode + ' >> ' + errorMessage);
}


function fillData(results, _ListName) {
    var $appContent = $('#employeeList tbody');

    for (var i = 0; i < results.length; i++) {

        var $tr = $('<tr/>');

        $('<td/>').text(results[i].ID).appendTo($tr);
        $('<td/>').text(results[i].Title).appendTo($tr);
        $('<td/>').text(results[i].Email + "Y").appendTo($tr);
        $('<td/>').text(results[i].Lookup['Title']).appendTo($tr); // Set lookup text
        $('<td/>').text(results[i].PP['Title']).appendTo($tr); // Set people picker value
        $tr.appendTo($appContent);
    }


}

// This function prepares, loads, and then executes a SharePoint query to get   
// the current users information  

//Utilities   

// Retrieve a query string value.   
// For production purposes you may want to use   
// a library to handle the query string.   
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    }
}

Final Output:



Wednesday, 9 March 2016

Hide ribbon on item selection in sharepoint 2010 list view using jquery

<script src="/SiteAssets/jquery-1.8.3.min.js"></script>
 <script language="javascript">


 $(".s4-wpcell").removeAttr('onkeyup').removeAttr('onmouseup');

 </script>

Friday, 19 February 2016

Get SharePoint list column value using javascript

Below is the function to easily get sharepoint list column value using internal name, its better to get value then using column id.

function getField(fieldType,fieldTitle) {
    var docTags = document.getElementsByTagName(fieldType);
    for (var i=0; i < docTags.length; i++) {
        if (docTags[i].title == fieldTitle) {
            return docTags[i]
        }
    }
}

to get single line text use :

getField('input' , 'Title');

Choice Colum:

 getField('select' , 'col name');

Hide SharePoint list form fields using jQuery/Javascript


Just add jQuery reference and use below lines

Single line/Multi Line

$("input[title$='Col Name']").closest('tr').hide();

Dropdown

$("select[title$='Col Name']").closest('tr').hide();

to show field use below line

$("select[title$='Col Name']").closest('tr').show();

People Picker or any other field

$("nobr:contains('Col Name')").closest('tr').hide();

Readonly text colum:

$("input[title='Col Name']").attr("readonly",true);

Wednesday, 28 November 2012

Check the user in a particular group and check it with the current logged in user to hide/disable controls

Below is the script to check the user in a particular group and check it with the current logged in user using JavaScript and Jquery.

If current user is present in desired group than you can implement any of the logic.
I have implemented disabling controls and hiding tables.

ExecuteOrDelayUntilScriptLoaded(disableControls, “sp.js”);
function disableControls()
{
clientContext = new SP.ClientContext();
groupCollection = clientContext.get_web().get_siteGroups();
group = groupCollection.getById(21); //The ID of the SharePoint user group(can be checked in group URL)
users = group.get_users();
clientContext.load(group);
clientContext.load(users);
currentUser = clientContext.get_web().get_currentUser();
clientContext.load(currentUser);
clientContext.executeQueryAsync(Function.createDelegate(this,
this.onQuerySucceeded), Function.createDelegate(this,
this.onQueryFailed));
RefreshCommandUI();
}
function onQuerySucceeded()
{
if(users.get_count() >0)
{
UserExistInGroup = false;
for(var i=0; i < users.get_count(); i++)
{
if(users.itemAt(i).get_loginName() == this.currentUser.get_loginName())
{
UserExistInGroup = true;
break;
}
}
}
if (UserExistInGroup)
{
var p=$(‘input[title=col1'); //Name of the columns that needs to be disabled
var i=$('input[title=col2]‘); //Name of the columns that needs to be disabled
$($(p)[0]).attr(‘disabled’,false);
$($(i)[0]).attr(‘disabled’,false);
document.getElementById("Table1").style.display = 'none';
}
else
{
var p=$(‘input[title=col1');
var i=$('input[title=col2');
$($(p)[0]).attr(‘disabled’,true);
$($(i)[0]).attr(‘disabled’,true);
document.getElementById("Table1").style.display = 'inline';
}
}
function onQueryFailed(sender, args)
{
var p=$(‘input[title=col1');
var i=$('input[title=col2]‘);
$($(p)[0]).attr(‘disabled’,true);
$($(i)[0]).attr(‘disabled’,true);
document.getElementById("Table1").style.display = 'inline';
}

Friday, 2 November 2012

Hide Controls for particular sharepoint group using Jquery

This blog is to hide sharepoint contols, buttons, tables etc. for sharepoint group on page load.


Using CEWP we can achieve this simply refering some Jquery files and add CEWP in your page or list form and give your control id you want to hide and you can hide easily on Page Load.


Steps:

Download Jquery files:
1. jquery.min.js
2. jquery-1.4.2.min.js
3. jquery.SPServices-0.5.4.min.js
4. jquery.SPServices-0.6.2.js

Add the script in your page either using CEWP or directly and refer above mentioned files as below:

<script src="site url/SiteAssets/jquery.min.js" type="text/javascript"></script><script src="/site url/SiteAssets/jquery-1.4.2.min.js" type="text/javascript"></script><script language="javascript" src="/site url/SiteAssets/jquery.SPServices-0.5.4.min.js" type="text/javascript"></script><script language="javascript" src="/site url/SiteAssets/jquery.SPServices-0.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$().SPServices({
      operation: "GetGroupCollectionFromUser",
      userLoginName: $().SPServices.SPGetCurrentUser(),
      async: false,
      completefunc: function(xData, Status) {
       //alert(xData.responseXML.xml);
        if($(xData.responseXML).find("Group[Name='Group Name']").length == 1)
        {
         //alert('User in a group');
         document.getElementById("Ur control or button id").style.visibility="visible";
      document.getElementById("Ur control or button id").style.display="inline";
        }
        else
        {
         //alert('User not in a group');
         document.getElementById("Ur control or button id").style.visibility="hidden";
         document.getElementById("Ur control or button id").style.display="none";
 
        }
      }
   });
}); </script>



Done!

Thursday, 25 October 2012

Jquery for Tabbed Navigation in Sharepoint Custom List forms

Jquery Tabs for sharepoint custom list form:

This post is to divide custom list form in to jquery tabs.

Using this tab navigation we can also reduce veritcal scrol and also achieve our business functionality.

It is a OOB approach without Infopath and object model

Below are the steps:

1.       Download Jquery from Jquery.com

















2.       Add this to Sharepoint All files Folder or Site Assets.
3.       Create you list
4.       Open this list in sharepoint Designer and Create new Custom Form (Newform.aspx)

5.       Add the Following Tab code in your Custom form

<div id="tabs">
    <ul>
        <li><a href="#tabs-1">Personal</a></li>
        <li><a href="#tabs-2">Contact</a></li>
        <li><a href="#tabs-3">Office</a></li>
        <li><a href="#tabs-4">New Hire</a></li>
       
              </ul>
    <div id="tabs-1">
                   <table border="0" cellspacing="0" width="100%">

                   </table>
              </div>
    <div id="tabs-2">
                   <table border="0" cellspacing="0" width="100%">

                   </table>
              </div>
    <div id="tabs-3">
                   <table border="0" cellspacing="0" width="100%">

                   </table>
              </div>
</div>

6.       Cut the Column <Tr> from you list and paste under tabs table.

7.       Save this form and preview in browser
8.       Edit this page after clicking page tab
9.       And add two HTML form web parts on that page
10.       Edit first html web part properties and click source editor button, it will open a window copy and paste the jquery and CSS reference in this window.

In my case I have added this jquery folder to Site Assets.

<link type="text/css" href="SiteUrl/SiteAssets/jquery-ui-1.8.18.custom/css/redmond/jquery-ui-1.8.18.custom.css" rel="stylesheet" />    
<script type="text/javascript" src=" SiteUrl /SiteAssets/jquery-ui-1.8.18.custom/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src=" SiteUrl /SiteAssets/jquery-ui-1.8.18.custom/js/jquery-ui-1.8.18.custom.min.js"></script>
<script type="text/javascript">
            $(function(){
                // Tabs
                $('#tabs').tabs();   
            });
</script>
Note- You can also add this script below your Head tad in Master page if you can access Master page
11.       Save the page and Stop editing your Tabs are ready nowJ
12. Final view would be like this:

Columns are divided in to Jquey tabs you can also change the look and feel of list form

The above approach is full OOB and Client side no server hit on clicking tabs(As in case of infopath on every clik there is a post bak occurs )


Thanks!