Thursday, November 27, 2014

How to set, Person or Group field to Empty or Null in SharePoint using JSOM

There was a requirement for me, where I need to set/update custom "Person or Group" field column to empty using JSOM

Here is the simple way to do that

Create an empty array

var oUser = new Array();

and pass that empty array to column of type "Person or Group"

listItem.set_item('CustomModifiedBy', oUser)

In the above code snippet, 'CustomModifiedBy' is of type "Person or Group"

How to set SharePoint 2013 user defined date time filed to empty using JSOM

This is a very small post, where I need to set, user defined list column of type date time to null

I looked into the internet and I haven't found anything related to this. To set date time field to empty, just set "null" to that column

For ex:

listitem.set_item('UserModifiedBy', null)

In the above code snippet, UserModifiedBy is of type "Date and Time" which is not a required field and allow nulls

Monday, November 24, 2014

Deleting SharePoint Online Site Collection Programatically

Last week, I got a requirement, where I need to delete some 300+ SPO site collections. Its a tedious process to delete SPO SC manually by going to Site Settings page and click on the link "Delete site".

So I thought is there any better way to delete the SPO site collections programmatically. There is no CSOM api, where we can leverage to delete the Site Collections and one of my colleague asked me to try using HTTPWebRequest approach

Here are the high level steps that he suggested me to do:

  1. For one Site Collection, go to site settings page and click on "Delete site" link
  2. Once you are on that page, for the delete button click event, do the fiddler trace and capture the all the actions that fiddler is doing for that operation
  3. Mimic the same using C# code

I followed the same approach that he has suggested and I am able to delete the SPO site collection

Here are the important things that needs to be remembered when doing this operation

  1. First we need to authenticate using SharePoint Online
  2. Get Authenticated cookie to avoid redirects
  3. Set appropriate request headers
  4. Set appropriate POST parameters and url encode the same

Deleting a site collection using Http approach is a three step process:

  1. Authenticate using SPO credentials and get the authenticate cookie for the site collection that needs to be deleted
  2. Need to get post parameters such as form digest, view state, event target, event validation etc
  3. Using the SPO credentials and using the post parameters, created another http web request object that will delete the site collections

Authenticating to SharePoint online

To authenticate to SharePoint online, we need SharePoint client dll's. Refer the following SharePoint client side dlls

  1. Microsoft.SharePoint.Client
  2. Microsoft.SharePoint.Client.Runtime
The below method is used to authenticate the user using SPO credentials



Getting Authentication Cookie

After authentication, we need to get authenticated cookie for the site collection, that needs to be deleted

The below code is used to get authenticated cookie



We need to add the cookie that got generated to the CookieContainer class, which will be added to the HTTPWebRequest class

Setting up the HttpWebRequest instance

The below code will show how to create HttpWebRequest class and how to pass SPO credentials and how to setup the CookieContainer that has been discussed above



The url for deleting the site collection will be: "site collection url"/_layouts/15/deleteweb.aspx.

For ex: https://your tenant/teams/sitecollectionname/_layouts/15/deleteweb.aspx

For the Http Web Request class, we need to set the following properties. This information we got from the fiddler trace

Method = "POST"
ContentType = "application/x-www-form-urlencoded"
UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; BRI/2; InfoPath.3)";

Apart from setting the properties, we also need to set some form parameters, the same form parameters that "Delete" button will set on the "deleteweb.aspx"

These form parameters we can get from the fiddler trace

1. __REQUESTDIGEST
2. __VIEWSTATE
3. __EVENTVALIDATION
4. __VIEWSTATEGENERATOR
5. SideBySideToken

In order to get the above form parameters, first we need to get the html source for the deleteweb.aspx and from that html source, we need to scrap the html source to get the above values.

I have written two functions, first function will return the html source and the second function will parse the html source and will get the desired values as discussed above





The below code will show to use the above two methods and set the post parameters for the http web request class



Setting the post data and pass that post data to the web request class



__EVENTTARGET has been hard coded to "ctl00$PlaceHolderMain$ctl07$RptControls$BtnDelete" which we got from the fiddler trace and this can be used as is until unless Microsoft does not change the button name and position in the deleteweb.aspx

The below part of post data has been hard coded which I copied directly from the fiddler trace. Convert the string post data to byte array and pass that information to the request object




 The final step is to get the HttpWebResponse for the http web request that has been created above




If the response string contains, "Working on it", then we can assume that site has been deleted
 

Thursday, November 20, 2014

Uploading multiple attachments to the lists using JSOM

In the previous blog post, we have seen how to attach a single file to the list item

In this blog post we will see how we can attach multiple attachments to a list item using JSOM. The following code will work in both SharePoint hosted apps and regular SPO web applications

The following technologies are referred/used in  the blog post

1. jquery.multifile.js
2. jquery
3. SPO client side libraries

Not much information is available in the internet to attach multiple files to the list items.

In your custom form, where you want to attach multiple files, add the following html tags which will facilitate the user to attach multiple files to the list item

As part of this post, we assume that, we have list called "MyList" and in that list we have two list columns called "FirstName" and "LastName"

When we insert data to this list, we also attach multiple list items. The below code snippet will show the simple html that has been created for the user to insert data into the list called "MyList"



As you can see in the above code snippet, I have two html text boxes for FirstName and LastName and a file input control.

To facilitate multi file upload control, I am leveraging "jquery.multifile.js" plugin. If we don't use that plugin, the user will select only one input file for upload

When the user selects multiple files, here is how the UI looks like

 
As you can, with the help of jquery plug in, we can select multiple files. The complete UI will look like this



I also have a submit button and on click of that button, I want to insert a new list item as well as attach as the files that user has selected

On click of btnSubmit, all the files that are selected by the user will be attached to the list item.

Here is the code snippet for the btnSubmit click event. I have written this click event in the jquery document load function



As a first step, loop all the attachments the user as selected and push that information into some javascript array. That javascript array function will just have the file information and not the contents of that file



Create another JSON array, to hold all the values the user has entered such as first name, last name etc. and including the file array that has been created above

data.push({"FirstName": $("#txtFirstName").val().trim(), "LastName": $("#txtLastName").val().trim(), "Files": fileArray});

After this, I have written some function will insert list item also attach the list items also



I am using regular JSOM code for creating the list items. Since attachments has to be inserted  to the newly created item, I need to know the ID to which I need to insert the attachments

So, first I will insert/create the data, get the list id and to that list id, we need to insert attachments


After the getting the list id, I will loop with all the attachments the user has selected. I wont resolve the function, till I insert all the list attachments. If all the attachments are inserted, I will resolve the function

loopFileUpload function need to called recursively till all the list attachments are inserted



As you can see in the above function, loopFileUpload has been called recursively till all the list attachments are inserted

With in the loopFileUpload function, I am calling another function called uploadFile which will associate the list attachment to the id that has been passed to that function



Within the uploadFile function, I am calling another function called, getFileBuffer, will will read the actual contents of the file and pass that information to uploadFile function

We are using REST based approach for inserting the list attachments as REST will allow to upload upto 2 GB of file

Here is the url that needs to be used to access the list item id to which we need to insert the list attachment




Here is the complete source code of the page that I used for this blog post



Here is the snapshot of the list item that got created using this code with multiple attachments
 

Wednesday, September 24, 2014

JSRequest

Today I was exploring JSRequest in sharepoint and I found it very useful for some of the most common things that we will be doing in SharePoint.

Some of the uses of JSRequest are:

1. Reading querystring values from the URL
2. Getting the file name of the page
3. Getting the path name of the file that is getting browsed

Before using the JSRequest properties, you need to call a method called "EnsureSetup" on JSRequest

JSRequest.EnsureSetup();

//Getting a querystring value called searchResults
var searchResults = JSRequest.QueryString["searchResults"]

//Get the current page name. i.e - "default.aspx"
var pageName = JSRequest.FileName;

//Get the current path name. i.e - "/sitecollectionurl/libraryname/default.aspx"
itemId = JSRequest.PathName;



Referred the following url's for the same

http://mahedevelopment.blogspot.com/2013/03/getting-query-string-values-using.html

http://praneethmoka.wordpress.com/2012/01/12/some-useful-javascript-variablesfunctions-in-sharepoint/


Its easy to use and easy to remember

Saturday, September 20, 2014

Usage of JSLink in SharePoint 2013

In this post we will see how to use the JSLink in SharePoint 2013.
 
Till sharepoint 2010, to customize any list views(Lists or Libraries), we are using XSLT to customize the representation of the list view or document library view.
 
In SharePoint 2013, a new feature has been added called (Client Side Rendering). In this blog post we will see what is client side rendering and how to use client side rendering and how to debug the same
 
Client Side Rendering is a new feature that got introduced in SharePoint 2013 which will allow the developers to transform the data on the client instead on the server
 
This gives lot of options to the developers to use client side technologies such as HTML, JQuery and any other javascript frameworks.
 
Some of the examples where the Client Side Rendering will be helpful:
 
1. Format the values in the list view web parts
2. Make the columns as read only in the Edit or New list form
 
 
In this blog post we will see how we can use client side rendering to format the values in the XsltListViewWebPart
 
When we talk about, client side rendering, there are two things that we need to consider in SharePoint 2013.
 
  • Display Templates
Display Templates along with Control Templates and Item Templates are used in SharePoint Search and is used to completely transform the search results display
  •  JSLink
JSLink is new property attached to list views, content types, fields and how the JSLink works is, we just need to associate a link to a javascript file to this JSLink property associated to either list views or list forms such as new or edit form
 
See the attached screen shot where the JSLink property will be found for a list view web part



In this blog post we will see how to modify the XSLTListViewWeb Part to add hyperlinks to one of the list column dynamically using the javascript and also, add some graphical image to another column where we want to display the site usage in a graphical representation

We can still achieve the same thing in the old XSLT approach and using XSLT based approach is old way of achieving the same thing

Javascript File

First we will create the javascript file and we will see how to associate this javascript file to the JSLink textbox control to the XSLTListView Webpart

As explained earlier, we will try to add a new value a Permission column. By default there wont be any value in the permission column

But when the list is rendering we will get the value from the "SiteURL" column and we will append site collection permission page of that url and we will render that new value to the "Permission" column

See the below javascript file that I have written to modify the same and we will discuss in detail about this javascript



First we need to write a javascript function which is self invoking and the syntax of that function is


(function(){
})();

So, when the page loads, that function will be called automatically. With in that function, we will write the logic for formatting the list columns inside XSLTListView web part

First we need to declare variables for fields for which we need to override the data

var overrideCtx = {};

The script specifies that we need to override the "Permission" column and we need to specify that value for the Fields override

The syntax for Fields to override was

overrideCtx.Templates.Fields = {FieldName {Scope : Override}}

  • FieldName - This is the internal name of the field you want to override.
  • Scope – This defines when to override the field. The choices are "View","DisplayForm","EditForm", and "NewForm"
  • Override – The actual override. This can be a HTML string with JavaScript embedded, or a function to be executed. In our case we are using a function that needs to be executed

overrideCtx.Templates.Fields = {'Permissions': {'View':changePermissionLink}}

In the above syntax, what we are saying was, replace the "Permissions" field value with that value that is returned from "changePermissionLink"

"changePermissionLink" is a custom javascript function that has been written which will return the value that can be placed inside the permission column

If you want to override value of another field, we can add the same to the Fields object as shown below

Next we need to register our override object with SharePoint using RegisterTemplateOverride method as show below

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);

Now we will see what changes we need to do to "changePermissionLink" to update the new value
 

 

changePermissionLink will take a parameter called ctx, which will give the complete context information of the current item that is being rendered, such as all the list columns information

To get the current field information, we can use either of the below syntax

var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
                           or
var fieldValue = ctx.CurrentItem.Permissions; //Provided if you know the internal name of the field

Then we will get the SiteURL field using the following syntax

var siteUrl = ctx.CurrentItem.SiteURL;

Then we use the following code to format the hyperlink and return that value. As you can see, we are embedding the html anchor in the format

var permissionUrl = $(siteUrl).html()+"/_layouts/15/user.aspx"
var permissionLink = 'Permission'
return permissionLink;


Associating this JS file to JSLink property of XSLTListView web part.
  • Edit the page
  • Edit the web part
  • In the edit web part properties, go to miscellaneous section there you will find a JS Link text box and to that text box value provide the url of the above JS file

When providing the path to the custom js file to the JSLink property, you can use the below syntax
 
~sitecollection/Style Library/LCACollabDB/JS/LCACollabDBRendering.js
 
To add multiple JS files to the JSLink, you can use the pipe symbol. See the below syntax for the same
~sitecollection/Style Library/LCACollabDB/JS/LCACollabDBRendering.js|~sitecollection/Style Library/LCACollabDB/JS/LCACollabDBRendering1.js
 
 

Monday, August 11, 2014

Adding jQuery reference url to a page if the jquery is not loaded from local project references

In lot of the web applications, adding jquery references is a common practice. There can be scenarios where the jquery that has been referenced in your page might not be loaded due to Connectivity Issue or for some other reason and you don't want the page functionality to break because jquery is not loaded.

The below piece of code will load the jquery from CDN, if the juqery is undefined in your page



The LoadResources function will first check if jquery is defined or not. If not defined, it will try to create a scrip tag and to the script src attribute it will set the jquery CDN url. After setting the src attribute of the script tag to the jquery CDN url, add that script element reference to the head tag

Check jquery sit to get all valid CDN url's

Friday, July 25, 2014

Add a new user to the user field list column in SharePoint 2013 using JSOM

In this small post we will see how we can add user to a user column using JSOM. Assuming that the user entered is a valid user



We have created a new javaScript array variable called oUser

To this array we are pushing user information with the help of javascript function called SP.FieldUserValue.fromUser

To fromUser method, we are passing the valid email and we are setting this oUser object array to the list item
 

Thursday, July 24, 2014

Upload/attach files to SharePoint 2013 list items using REST based approach

In this post we will see how we can add list attachments to the list items in SharePoint 2013 online using Javascript.

Some of the content in this post has been taken from the URL - http://sharepoint.stackexchange.com/questions/60417/cant-upload-a-non-text-file-to-sharepoint-app-via-rest-api and the response has been posted by Fedor Shihantsov

I found lot of articles for uploading documents to the document libraries using REST based API in javascript. But very few articles has been posted for attaching the documents to the list items

SharePoint 2013 supports the following technologies to manipulate SharePoint on the WEB


1. JSOM
2. REST

JSOM is having the size limitation of 1.5MB when uploading documents to SharePoint

Using REST we can upload attachments up 2 GB to SharePoint

In this post we will see, how we can upload the documents to SharePoint list items using REST based approach

Note: This has been tested in IE10+ and Latest google chrome and the browser has to support HTML5 where we will leverage file reader functionality

Lets start exploring for uploading/attaching files to list items

Step 1:

On the SharePoint page, add an input file control and another control of type button to submit the file 



In the above code snippet, I added an input file control and a button to upload a file. 

On click of this button, I wanted to attach the file to a list item id of 1



In the above code snippet, on click of a button, we are checking whether any file has been selected for upload or not

fileName will give the file name the user has uploaded and file variable will contain the actual file content that has been selected for uploaded

We are calling a function called upload and to this function, we are passing the list name, the list id to which we wanted to attach the file



With in upLoadFile, we are calling another javaScript function called uploadFileSP, where the actual code for uploading the file into SharePoint will take place

First we need to get the contents of the file as bytes and the below script will convert the file contents into bytes

To convert the file contents as array, we will be using HTML 5 FileReader object. See the below code for the same. 



getFileBuffer is internally called with in uploadFileSP



Once we get the contents of the file as byte array, need to convert the byte array to binary string

To upload the file, we will be using SP.RequestExecutor and use executeAsync method of SP.RequestExecutor to upload the file

To executeAsync, we need to pass the following information

url: REST based url of list item id, for which we need to attach the list item. 
method: "POST". 
binaryStringRequestBody: true - whether we are sending the contents of the body in binary format
body: The contents of the file 
success: The successcall back function when the file is uploaded successfully
error: The failure call back function if there is any error in uploading the file
state: "update" - We are updating the list item and not insert



The following web sites has been referenced for this post

http://www.shillier.com/archive/2013/03/26/uploading-files-in-sharepoint-2013-using-csom-and-rest.aspx

http://chuvash.eu/2013/02/20/rest-api-add-a-plain-text-file-as-an-attachment-to-a-list-item/

http://sharepoint.stackexchange.com/questions/60417/cant-upload-a-non-text-file-to-sharepoint-app-via-rest-api

Thursday, July 17, 2014

SharePoint 2013 Tips and Tricks - GetUrlKeyValue, SetUrlKeyValue

There are lot of utilities and functions available on the client side SharePoint 2013 API and in this post we will see one of those API called GetUrlKeyValue and SetUrlKeyValue

There are scenarios where we need to get or set the value from or to the querystring of the URL and SharePoint provides an easy way to do this

GetUrlKeyValue:

This small utility function will try to get the value from the querystring of the url. There is no OOTB function to get the querystring value using javascript and this GetUrlKeyValue will help us in getting the value from the querystring

This function has been declared in in init.js. Ensure that init.js is referenced and loaded before you use this function.

Syntax: The syntax for GetUrlKeyValue is

GetUrlKeyValue(keyName, decodeQueryStringValue, url, caseComparison)

keyName: The querystring name for which we need the value

decodeQueryStringValue: Whether you want to decode the value - default value false

url: The url from which we need to retrieve the keyName value

caseComparison: Case sensitivity for keyName. - default value true

Example:



In the above example, we wanted to retrieve "EditPage" querystring value from the current url - window.location.href

window.location.href can be replaced with your own url

The return value from this method is, string representation of querystring value and in this case it is "EditPage"

If the EditPage key doesn't exists in the url, it will return an empty string

SetUrlKeyValue

This is opposite to GetUrlKeyValue. In GetUrlKeyValue, we will getting the value from the querystring and in SetUrlKeyValue, we will be setting the querystring value

The syntax for SetUrlKeyValue is,

SetUrlKeyValue(keyName, keyValue, bEncode, url)

keyName: The querystring name to which we need to set the value

keyValue: The value that needs to be set to the keyName

bEncode: Whether the value needs to be encoded in the url before setting the value

url: Url to which the value needs to be set

Example




 

Thursday, July 10, 2014

Opening a Page as modal window using JSOM in SharePoint 2013

There are many scenarios where we need to open custom pages or OOTB pages in a pop up. SharePoint provides an API to open the pages in pop up and in this post we will see how we can achieve the same using on the client side using JSOM

We will explore the following methods from the SharePoint 2013 client side library which will help us in opening the page as a dialog.

We will consider the following scenario when opening the page as a dialog:

  • How to open the page in a dialog
  • How to pass data to the dialog page
  • How to return parameters or data back to the calling page from the dialog page
First we will see how to open the page in a dialog window. In order to open the page in a dialog, first we need to set the dialog window properties such as

  • Dialog Window Title
  • URL of the page to be shown in dialog window
  • Width and height
  • Allow dialog to maximize
  • Allow dialog to close
  • Need callback from the dialog window to the parent window
  • Data for the dialog window that needs to be passed from the parent window
So, I have written a function in javascript with those parameters that can be called from the parent window. The below JavaScript code will show that information



We have written a function called openInDialog which can be called from the Parent page and to this method we are passing all the parameters such as title, width, height etc. that discussed above


Then we have created a variable called options which has to be a JSON object that needs to be passed to the SharePoint JavaScript function which we will discuss later



Ensure that you use the same key names in the options variable such as args, showClose, allowMaximize etc

Its always better to pass data in JSON format to the modal window

If we need callback from the dialog window, we need to set a property called dialogReturnValueCallback. To that property, we need to set a custom call back function that will be called when the user closes the dialog window



Here the closeDialogCallBack is a custom callback function that will be called when the user closes the dialog window. We will explore this custom callback function later in this post

To open the page in a dialog, we need to call a sharepoint function called showModalDialog which is defined in the namespace SP.UI.ModalDialog and this name space is present in the JS file sp.ui.dialog.js



To showModalDialog function, we are passing options as a parameter which we have created above

In the dialog window, we can access the data that is passed from the parent window as follows



dialogArgs contains the data that is passed from the parent window
Once the business is completed in the dialog window, the user will press OK or Cancel button in the dialog window.

Before clicking on OK or Cancel button, we need to prepare data that needs to be passed to the parent window. We will see how to prepare the data that needs to be passed to the parent windows



In the above code, we have created a javascript array and to this javascript array we are setting some data and we want to send this data to the parent window and the parent window can take some action based on the data that is sent from the dialog

There are two actions that can be done in the pop up either OK or Cancel. Here are the SharePoint functions for OK and Cancel click events

When the user click on "OK" button, we can call the below SharePoint function
 
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, popData);

When the user click on "Cancel" button, we can call the below SharePoint function

SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, popData);

 As you can see, we are passing popData javascript array to both ok and cancel button.

 commonModalDialogClose sharepoint function internally calls the callback function that we discussed earlier in this post.

In our case we have created a call back function called closeDialogCallBack and this will be called when we close the pop up


 

Friday, July 4, 2014

New Custom Styles and new bulleted styles to SharePoint 2013 Rich Text Editor

By default SharePoint 2013 RTE provides two bulleted styles such as bullets and numbers as shown below


We can add new styles to support new bulleted styles and for this we need to extend the styles that comes with SharePoint 2013.

In one of my previous post, I have explained how to add new table styles. Here is the URL for the same.

In this pose we will see how we can extend styles and elements of SharePoint 2013 styles so that we can add our own styles

There are two sections in Styles in RTE for SharePoint 2013 called
  1. Page Elements
  2. Text Styles
First we will see the difference between Page Elements and Text Styles

Page Elements:

Page elements: Page elements are HTML elements such as Span, H1 to H6 etc. This will apply styles to particular html elements.

To add new page element styles we need to use the below syntax

elementName.ms-rteElement-yourName

Here elementName is any html element as explained above. For elements, we need to extend ms-rteElement

Text Styles:

This will allow to change styles for the text portion. For ex: I have a text called: "SharePoint 2013 has great features when compared to SharePoint 2010". I wanted to highlight both SharePoint 2013 and SharePoint 2010 to different styles and in this scenario we will be using text styles where we can apply different styles to the text

ms-rteStyle-yourName

For styles we need to extend ms-rteStyle.

The below steps we will see how we can create new styles and elements. For the elements we will see how we can add new bulleted styles and for styles we will see how we can add new text styles


Steps:

1. Create a new CSS file called RteStyles.css and in that css we will create one CSS styles for text style and another CSS style for elements where we will add new bulleted style for exclamation (!) and section (§) as shown below


We also  build another style for text, where we will highlight the text red in color and we will make the text bold as shown below



RTE Element Styles



In the above RTE element styles, we are trying to add styles to html element h6. We have given the value to -ms-name as "LSW Glyphs Exclamation". A element style will appear in the element section of the RTE Styles as shown  below

We also need to specify -ms-element to true otherwise the new element style will not appear





As you can see, a new styles as been added for exclamation. If you select that styles, a new exclamation will be added at the start of the text. For getting the exclamation we added a glyph style called "\0021".

See the below url for some of the glyphs styles:

http://css-tricks.com/snippets/html/glyphs/

For getting new bulleted styles, we shouldn't use any of the existing html elements. So I have used new elements such as h7, h8 etc. If we use existing html elements such as h1 to h7 or Para tag or Span tag, we wont get bulleted functionality
 
So, to get bulleted functionality, I have used new  elements such as h7 and h8 for exclamation and section bulleted lists. See the below styles for the same



As you can see above, we have added two element styles for h7 and h8 to get new bulleted styles for exclamation and section. See the below image for the same

 
 
 
As you can see in the above figure, two new RTE element styles for h7 and h8 tags as been added


The newly created styles should be added to the master page



Now where ever rich custom editors has been used such as "Publishing Html Fields" or "Content Editor Web parts", the new RTE styles will be seen

For Text styles, we need to follow the same procedure as we followed for elements. Instead of rteElement, we need to specify rteStyles.

Since rteStyles will act on the text portion, no need to specify any html tags before rteStyles.

The signature to extend rteStyles are show below



As you can see in the above, we created rteStyle with styleName and this name can be replaced with your own style name

Also, I have given -ms-name as "New Style" and this name will appear in the RTE styles as shown below 





As seen above, a new text style with the name "New Style" will appear in the Text Styles window

Select some text in the RTE editor and you select the above mentioned styles, then the selected text will have that styles(Text will appear as bold and red color will be applied)
 

Thursday, June 26, 2014

Adding custom RTE Table Styles to SharePoint 2013

Out of the box SharePoint RTE provides 12 table styles and there are scenarios where we need to add new table styles.


As seen above, there are 12 table styles and to this we will add two more table styles

SharePoint provides extensibility framework to add custom table styles and in this post we will examine how to add custom table styles to the RTE. We can add as many table styles as we want but we need to follow some naming conventions so that RTE knows to add those custom table styles

In order to add new table styles, we need to extend "ms-rteTable" class and we need to prefix our own name to "ms-rteTable".

If we don't use "ms-rteTable" then new table styles wont appear in the table drop down.

Steps:

 
 
  1. Create a new CSS class and I created a class name called customRTETableStyles.css
  2. To this css class, I have created the below styles
  3. In the above CSS class, I have created my own table style by extending ms-rteTable and I have given the same as "ms-rteTable-myCustomTable"
  4. -ms-name: Give some name to property that you wanted to see in the table style drop down.
  5. In this case I have given the name as "My Custom Table" and this name will appear at the bottom of all the table styles
  6. Save the above CSS file into any sharepoint document library and preferably "Style Library"
  7. Refer that css file in your master page
  8. Edit any Rich HTML Field or Content Editor Web Part
  9. Insert Table and highlight the table and go to Design tab in the ribbon
  10. Under table styles, you should see our new table style as shown below
If you select the above table style, the table inside the Rich HTML Field and Content Editor Web Part will have that table style and in this case it is having the following features

1. Table header will be having blue back ground
2. Table border will be having gray color
3. Padding is 10px


In order to add new RTE table style, copy the above code and replace "myCustomTable" with new name and new RTE table style will appear





 

Wednesday, June 18, 2014

Using jquery templates to display sharepoint list data on the client side using JSOM

The following post will provide a scenario where you want to format sharepoint list data data using jquery template and everything on the client side using JSOM

As every body might aware that SharePoint online wont allow server side coding and everything needs to be written on the client side only

In the SharePoint online world, the developer should be using JSOM to retrieve the sharepoint data. Once the data is retrieved, the data should be presented to the user in a presentable way and in this post we will see how you can use jQuery, jQuery Templates to display SharePoint list data.

For this post, I will consider a SharePoint list called Customers and I have the following list columns inside that Customers list

1. First Name
2. Last Name
4. Email

When displaying the data, I wanted to combine First Name and Last Name and I want the email to be an hyperlink for the First Name and Last Name and I want to display the data as an unordered list. The final output will look something like this

This post will explain how we can do the same in SharePoint online using JSOM, JQuery and JQuery Templates

The first step in getting the data from the sharepoint list is to get reference to SharePoint and to get a reference to SharePoint context we need to load required Sharepoint JS file and the JS that needs to be loaded is SP.js. The following code snipped will show that information


In the above function we have created a small function called GetSharePointListData and to that function we are passing the list name and the CAML query that needs to be executed on the list, there is also an anonymous function called OnGetSuccess and we will discuss more on this later in this post
We have created another function called getData and in this function we will fire a request to SharePoint and fetch the data.



The following code will show the information on how to get context to SharePoint



Once you get a context to SharePoint, the next step will be, try to get context to the current web and the list from which you want to retrieve the list items and display the results




Once we set all the context, fire an async request to SharePoint and the following code will show that information



In order to display the data in the format that we require, we need to store the data on the client side that is retrieved from the SharePoint.

To store the data on the client side, we will use JSON and in the above code snippet, we are using dataset[] variable for that purpose.

For each and every item that we are getting from the sharepoint, we are storing that information in JSON array and we are using the following code snippet to store the data into JSON array



 Once we get all the data, we return the data from the function using the anonymous function that we are passing as a parameter to _getData function

onGetSuccess(that.DataSet);

that.DataSet contains all the sharepoint list data in json format. The following code will show how the list data looks like in JOSN format



If there is any error that SharePoint returns, we are capturing that information in another anonymous function and in that function we are calling another function called _onFail and in that function you can capture sharepoint error and update the UI accordingly.

Once we have the JSON data, we can make use of JQuery and JQueryTemplate plugins to display the data accordingly. We can make use of other plugins such as UnderScore or some other plugins for displaying the data. In this post we are using jQueryTemplates for displaying the data

The following code will show, how we can call the function GetSharePointListData and pass the required parameters. The following code snippet will show that information

GetSharePointListData(spListName, camlQuery, function (data) {
    $("#customerTemplate").tmpl(data).appendTo("#ulCustomer");
});


 In the above code snippet, #customerTemplate is the jquery template where we have written how the data should be displayed and formatted and more on this later in this post

To that template we are passing the data (JSON data) and we are appending the completed HTML to ul tag with the name "ulCustomer"

The following code snippet will show customerTemplate html template with the place holders for the data that is coming from JSON data



I am displaying the data in un-ordered list format, where FirstName and LastName becoming an hyperlink and on clicking of the hyperlink, default email client will open

The final output of the data will look like this
References

jQuery Template: http://plugins.jquery.com/loadTemplate/1.4.4/

Let me know your comments on this post