Tuesday, December 24, 2013

Finding SharePoint page is in edit mode using javascript

Recently in my project I got a requirement where I have to switch views of web parts based on the page mode (browsing mode and edit mode). When user is in edit mode I have to show some styles which will give option to user to add the data easily, but when user save the changes and publish the page, the styles will go away and they see normal page. So, I have to identify whether the page is in Edit mode or Browse mode in javascript.

I have a set of styles already written and based on the page mode I need to add those styles to some divisions on html. To find the edit mode of the page using javascript we have to use below logic:
var IsPageInEditMode = 
document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value; 
if (IsPageInEditMode == "1") { 
    alert("web part page is in edit mode."); 
} 
else { 
    alert("web part page is in browse mode."); 
}
But, this is not it all. To make it a common solution we must do more. :) The above logic works only for the Publishing pages. Which means if you have team pages (/sitepages/) or wiki pages then the above solution fails to return the correct value. For this, we should use below logic.
var IsPageInEditMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value; 
if (IsPageInEditMode == "Edit") { 
   alert("wiki page is in edit mode"); 
} 
else { 
   alert("wiki page is not in edit mode"); 
}
These SharePoint hidden variables are handy most of the times. Let's take a closer look at how we did it.
SharePoint uses the form variable for all its operations. This is a global variable added by SharePoint Framework to javascript. See the below image:

If you see the above image, there are many variables available for you in javascript. The first one is what we have used to get the form name. And the same way, we have many hidden variables available in javascript. These all can be visible by doing "View Source" on your browser. :)


From one of my friend, I got to know that in SharePoint 2010, 2013 we have a method available to get the Page State.
var IsPageInEditMode = SP.Ribbon.PageState.Handlers.isInEditMode();
That's all for now. Enjoy the new findings. I know it's old finding but learning is always fun!

Importing Excel Data to SharePoint

Recently for my company I have implemented a nice tool for importing data to SharePoint. The initial implementation started with Importing Excel Data to SharePoint List. Few years back me and my colleague implemented the same solution for 32 and 64 bit SharPoint 2007 servers. But, this new tool is targeted for SharePoint 2010, SharePoint 2013 and SharePoint Online. For more details visit the company blog. And also take a look at the codeplex project.

Its officially moved to my company utilities page. Please get it here.