Saturday, 22 November 2014

SharePoint 2013/Online: Get current logged in user's groups using javascript

This Post explains how to get current logged in users Groups using javascript. Its a simple ajax call to the sharepoint service. Use the below code

$(document).ready(function () {
     var userid = _spPageContextInfo.userId;
getCurrentUserGroups(userid);
});
function getCurrentUserGroups(UserID) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + UserID + ")/Groups",
        type: "GET",
        headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() },
        dataType: "json",
        async: true,
        success: function (data) {
            /* get all group's title of current user. */
            var results = data.d.results;
            for (var i = 0; i < results.length; i++) {
               alert(results[i].Title);
            }
        }
    });
}

How to hide a ribbon in SharePoint 2010/2013/Online using Jquery

This post explains how to hide a SharePoint Ribbon in SP 2010/2013/ SP Online using jquery.
It is very simple jquery code to hide the ribbon.
For example say suppose you want to hide Add New Item Ribbon in a List called Contacts.
Here is how efficiently we can achieve this.

$(document).ready(function () {
    var currentPage = decodeURIComponent(window.location.href.replace(/\+/g, " "));
    if (currentPage.contains("Lists/Contacts")) {
      window.setTimeout(hideRibbon, 500);
    }
});
function hideRibbon() {
    $('span[id^="Ribbon.ListItem.New.NewListItem"]').hide()
    window.setTimeout(hideRibbon, 200);
}
Above simple jquery code does the trick. As you can see, if the url is lists/contacts, we are calling the method  hideRibbon with a delay. And in the hideRibbon method we are calling the same method again with a delay. which will keep hiding the ribbon.

Happy coding :)

SharePoint: Save string content as a file in Document Library from Client Side with a metadata column.

My previous post Save string content as a file in Document Library from Client Side explains how to add a string content as a file in SharePoint document Library.
This post just extends the previous post. Suppose you have a metadata column in document library which describes some metadata about the file.
For example there is a column called "FileInfo" which will describe some information about the file. So now we need to pass value to this column while adding the file.
Let us see how this can be done.
function AddFileToDocumentLibrary(str) {
    var strm = Base64.encode(str);
    strm = strm.replace(/ /g, '');
    $().SPServices({
        operation: "CopyIntoItems",
        webURL: getCurrentUrl(),
        processData: false,
        async: false,
        SourceUrl: "http://null",
        Stream: strm,
        Fields: "<FieldInformation Type='Text' DisplayName='FileInfo' InternalName='FileInfo'  Value='This File Contains Contact Information' />",
        DestinationUrls: [getCurrentUrl() + "DocumentLibraryName/Contact.txt"],
        completefunc: function (xData, Status) {
             alert("Status=" + Status);
         
        }
    });
}
function getCurrentUrl() {
    var thisSite = $().SPServices.SPGetCurrentSite(); //if this line of code doesn't give you the url, try commenting this line and uncommenting the below line.
    //var thisSite = _spPageContextInfo.siteAbsoluteUrl;
    return thisSite + "/";
}
In the above code as you can see the option Fields allows us to provide values to the columns in the List/Library.
Please don't forget to incluse SPServices js file ans jquery.Base64.min.js (create a js file with this name and copy js code from here how-to-encode-and-decode-strings-with-base64-in-javasript) file.
Happy coding :)

Wednesday, 19 November 2014

SharePoint 2013: setting People Picker Value in NewForm.aspx

SharePoint 2013, people picker supports auto complete. You will not see the address book and the resolve user button any more on the new form.aspx.  If you are looking for a short cut key to resolve the user you can still use Cntrl + K  key combination.

SharePoint 2013 people picker.
In order to provide support for people picker in apps, Microsoft has come up with three new files as given below and is located in the 15 hive.
  1. clientform.js
  2. clientpeoplepicker.js
  3. autofill.js
The above 3 files contains most of the functionality required to be performed by people picker.
Here is the code to fill a people picker in SP2013 with a User.
function SetAndResolvePeoplePicker(fieldName, userAccountName) {
    var controlName = fieldName;
    var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
    var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
    var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
    peoplePickerEditor.val(userAccountName);
    spPeoplePicker.AddUnresolvedUserFromEditor(true);           
     //disable the field

     spPeoplePicker.SetEnabledState(false);

        //hide the delete/remove use image from the people picker

        $('.sp-peoplepicker-delImage').css('display', 'none');

   }
In the above method, the parameters:
fieldName: Name of the people picker column
userAccountName: user name (ex: domain\username).

Hope this Posts helps. Please comment below if you have better solution.

The Ribbon Tab with id: "Ribbon.Read" has not been made available for this page or does not exist. Use Ribbon.MakeTabAvailable()

"The Ribbon Tab with id: "Ribbon.Read" has not been made available for this page or does not exist. Use Ribbon.MakeTabAvailable()"


Have you come acrossthis error on your page?
Then don't worry. its not your fault but a riddle left by MSFT. 
I know that you got this error when playing with wiki pages. Yes, if wiki pages are rendered in IFrame (SPModalDialogue) or wiki page url has IsDlg=1(as part of querystring) this error shows up in sharepoint logs. 
Solution:
You can simply fix this by changing the type of the page from wiki to webpart page. 


Sunday, 9 November 2014

SharePoint Get Current Web URL

How to get SharePoint site current URL ?

We can get SharePoint Current web url in Server-Side as well as in Client side.

Server Side:

 As we all know current web url can be accessed in server side by web object as below.

SPContext.Current.Web.Url

Client Side:

In client side , we can achieve this by using SPServices .

Here is how to achieve this:
Include SPServices js file in your page.
Now you can access the url this way:
var thisWebUrl = $().SPServices.SPGetCurrentSite();
But there is a bug in recent versions of SPServices , where the above method will return only "/".
But in SharePoint 2013, we  can access web url as below as well :
var thisWebUrl = _spPageContextInfo.webAbsoluteUrl; (web url)
var thisSiteUrl = _spPageContextInfo.siteAbsoluteUrl; (site url)
Enjoy coding :)

SharePoint: Save string content as a file in Document Library from Client Side.

This Post explains you how to Save a string content as a file in SharePoint Document Library.
Refer this Post if you want to pass value to a column as well SharePoint: Save string content as a file in Document Library from Client Side with a metadata column
Use the below javascript code: (include SPService reference.)

function AddFileToDocumentLibrary(str) {
    var strm = Base64.encode(str);
    strm = strm.replace(/ /g, '');
    $().SPServices({
        operation: "CopyIntoItems",
        webURL: getCurrentUrl(),
        processData: false,
        async: false,
        SourceUrl: "http://null",
        Stream: strm,
        DestinationUrls: [getCurrentUrl() + "DocumentLibraryName/file.txt"],
        completefunc: function (xData, Status) {
             alert("Status=" + Status);
         
        }
    });
}
function getCurrentUrl() {
    var thisSite = $().SPServices.SPGetCurrentSite(); //if this line of code doesn't give you the url, try commenting this line and uncommenting the below line.
    //var thisSite = _spPageContextInfo.siteAbsoluteUrl;
    return thisSite + "/";
}
Please don't forget to incluse SPServices js file ans jquery.Base64.min.js (create a js file with this name and copy js code from here how-to-encode-and-decode-strings-with-base64-in-javasript) file.

Happy coding :)