This was a triumph.
I'm making a note here: HUGE SUCCESS.

Search This Blog

Friday, December 20, 2013

How to redirect all but a few users to a custom page in SharePoint 2013

Imagine that you are working in a production environment, you're close to your deadline on which all users will be granted access to your site. But what if you're not ready yet? What if your supervisor wants you to "deny" all users access to the site by redirecting them to one page, all users except for a select few?

In such a case, you'll need a script that will check the name of the user, see if he/she is allowed full access to the site, and if not redirect the user to a custom page. I used Jane Doe and John Doe as the users that are allowed full access to the site (I advise you to add your own name as well).

The code

We need to make a JavaScript file (I named mine "custom-redirect.js") and we will add the following code to the file:
SP.SOD.executeFunc('sp.runtime.js');
SP.SOD.executeOrDelayUntilScriptLoaded('SP.UserProfiles.js', 
 "~sitecollection/Style Library/Scripts/jquery.SPServices-2013.01.js");

var url = window.location.pathname;
if (url.indexOf('Redirect.aspx') > -1) {
 // Do not run the script if we're already on the page.
}
else {
 function redirectMe() {
  var userListArray = new Array();
  userListArray.push("Jane Doe"); 
  userListArray.push("John Doe"); 

  var user = $().SPServices.SPGetCurrentUser({ 
   webURL: "", 
   fieldName: "Title", 
   fieldNames: {}, 
   debug: false
  });
 
  function include(arr, obj) {
   for (var i = 0; i < arr.length; i++) {
    if (arr[i] == obj) return true;
   }
  }

  if(include(userListArray,user)) {}
  else { 
   window.location = 
    "http://your-site-here.com/Pages/Redirect.aspx";
  }
 }
}

The code will check if we're not on the redirect page already, since there's no need to keep running the script when the user has already been redirected. If we're not, then we'll continue with the function called redirectMe().

We need to make an array that will hold the names of all users that will be granted full access to the site. Push the names of those users to the array.

Then, we use SPServices to check the "Title" (also known as the full name of the user) of the current user. We will need a small function to check if an array contains an object as well. Using that function, we then check if the name of the current user is included in the array. If it is, then we don't need to do anything. If the name of the user is not in the array, then we redirect the user to a different page, in my case a custom redirect page.
And that's all there is to it! Quite simple, now that I look back at it.

You'll need to have the jQuery library for SharePoint Web Services in order to get the current user, you can find it here.
Also make sure you added a reference to your script in your master page, like so:
<!--SPM:<SharePoint:ScriptLink language="javascript" ID="scriptLink9" 
 runat="server" OnDemand="false" Localizable="false" 
 name="~sitecollection/Style Library/Scripts/custom-redirect.js" />-->

You'll also need to add the following line of code directly in your master page:
<script type="text/javascript">
 window.onpaint = redirectMe();
</script>

Make sure your master page and your script are checked in. Now you can freely continue working on your site without anyone seeing that it is not yet finished! Better yet, those who you have granted full access to your site can contribute as well!

If you have any questions, feel free to ask. ;)

How to prevent the page from going to "AllItems.aspx" after deleting a list item or a document in SharePoint 2013

Abouth a month ago on the 19th of November, I noticed something while I was cleaning up my site. I discovered that when I deleted a list item or a document from a list or library, the browser would send me to the "AllItems.aspx" of that list or library.

This was something I didn't really pay attention to at first, but then it came to my mind that end users might find this confusing since they would suddenly end up on a different page whenever they deleted something. Off course I understand that you probably wouldn't find this confusing at all, but imagine that a user with no knowledge of anything related to IT or computers would be in that situation. If such a user would end up on a page that no longer has the trusted design with a title and a paragraph of text, and a list or library that is suddenly showing way more columns than what he/she is used to see, that user would probably end up sending me an e-mail asking me for help because he/she is stuck. Yeah.

To avoid any confusion, no matter how small the problem, I wanted to make sure users would never end up on the "AllItems.aspx" page whenever they deleted something. So, not knowing where to start and not finding any relevant results on Google, I asked the question on Stack Exchange. I had thought that something like this wouldn't be so hard to figure out, but was dissappointed when my first and only "answer" was just a comment saying that I could take pointers. After a few weeks with still no solution, I gave up hope and started a bounty on the question.
Suddenly many more answers appeared, yet none were offering me an example in JavaScript. Most answers required me to use C# and seemed way to complicated for a problem this small, and after a while I thought that maybe my question wasn't clear enough.

Until someone answered with three options, one of which was to use cookies. When I started my search, I discovered that there was a successor to cookies. Named HTML5 Web Storage.

The logic behind the idea

First of all, we notice that when you want to delete something (be it a list item or a document, I'll just call it "item" from now on), you first need to click on the edit button for that item before you can choose to delete it. When I edit an item, it opens in a modal dialog. As you may or may not know, the URL of a modal dialog contains "EditForm.aspx".
If I then choose to delete the item, it directs me to the "AllItems.aspx" page. Based on this, we now know that we can write a piece of code that will only run when the user ends up on the "AllItems.aspx" page, having the "EditForm.aspx" page as its referrer.

Next, we just write a piece of code that will take us back to the previous page. But pay attention: technically, the previous page is the modal dialog. We need to go back to the page before we launched the modal dialog, so the page on which you clicked on a list item from a list or a document from a library.

To save the URL of that page somewhere, I used HTML5 Web Storage.
At this point, I just want to share the code with you. After all, there's really not much left to explain.

The actual code

var ref = document.referrer;  // Stores URL of previous page.
var url = window.location.pathname; // Stores URL of current page.

// The following code will run if the user edits a list item or properties of 
// a document.
if (url.indexOf("EditForm.aspx") > -1) {
 sessionStorage.setItem("page", ref);
}

if (url.indexOf("AllItems.aspx") > -1 
    && ref.indexOf("EditForm.aspx") > -1) {
 window.location = sessionStorage.getItem("page");
}

There you have it! It can't be easier, really!
If you follow the code, you'll see that if the URL in your browser window contains "EditForm.aspx", it will store the URL of the "previous" page as a session object. As soon as the URL in your browser window contains "AllItems.aspx" AND if the referrer (aka URL of the previous page) contains "EditForm.aspx", it will set the window location to the URL we stored as a session object earlier. The user won't even see that he/she has been redirected back to that page.

To make things work, you'll need to make sure that you've put a reference to your script in your master page. I had written the code in a new JavaScript file named "no-all-items.js" and added a reference to it in the master page:
<!--SPM:<SharePoint:ScriptLink language="javascript" ID="scriptLink10" 
 runat="server" OnDemand="false" Localizable="false" 
 name="~sitecollection/Style Library/Scripts/no-all-items.js" />-->

And there you have it. Make sure your script is checked in, as well as your master page, and you're ready to go!
Enjoy!

Monday, December 2, 2013

How to hide links in the navigation from users that don't have edit permissions for certain pages in SharePoint 2013

Imagine you have a site that has managed navigation. Most of the pages in the site can be seen by all the users, but there is one page that has unique permissions. This page, for example, is named "Secret headquarters" and should only be visible to the members of the group "Secret service". All other users shouldn't even see the link to that page in the navigation, so basically nobody else but the members of the group should know there is such a page.

So, how do we hide a link to a page with custom permissions? And how exactly can we find out in which groups the user is in, and if the user is a member of the group "Secret service"?
Let me explain that to you.

Preparing a page for unique permissions

First of all, you need to create a group that will hold all the users that will have access to the "secret" page. I named my group "Secret service" and added some users. The group has read and edit permissions.
Then, you will need to create the page (if not already) that will be made hidden to all users except those who are a member of the group "Secret service". When you made the page, do the following:
  1. In your subsite, click on the "Settings" button on the top right corner
  2. Click on "Site content"
  3. Click on the name of the "Pages" library (or the "Subsites" library, depending on where you store your pages)
  4. Find the page you want to make secret, and click on the "..." on the right side of its name
  5. In the small modal dialog, click on "..." again and select "Shared with", then click on "Advanced"
  6. In the ribbon, top left icon, click on "Remove Unique Permissions", click "OK"
  7. Select the remaining groups and then click on "Remove User Permissions", click "OK"
  8. Click on "Grant Permissions", type in the name of the group that will have access to the page (in my case, that will be "Secret service")
  9. Click on "Show options" at the bottom of the dialog and untick "Send an email invitation"
  10. Select "Edit" permissions, press "OK"
  11. repeat steps 8 and 9, now select "Read" permissions, press "OK"
At this point, users who are not a member of the group "Secret service" will still see a link to the page in the navigation, but when they click on it, they will get a "Access denied" message.

Testing the permissions of the page

This will be quick and easy to test if you have a dummy account. If not, then I hope you have a colleague willing to spend 10 minutes of his/her time testing your environment. But let's just continue with the idea of having a dummy account.

First, let's add the dummy to the group and see if the dummy can access the page:
  1. With your administrator account, add the dummy account to the group "Secret service"
  2. Log in with the dummy account, navigate to the page "Secret headquarters"
    • If you can see the page with the dummy, then you did well!
    • If you can't see the page with the dummy, you probably didn't add the dummy user to the group "Secret service".
  3. Still on the dummy account, check if the dummy can see other pages in the same subsite
    • If you can still see all other pages with the dummy, then you did well!
    • If you can't see other pages with the dummy, then you probably set the unique permissions for the whole subsite instead of just the one page

Now we just need to check if the dummy will get an "Access denied" when the dummy tries to access the page without being a member of the group:
  1. With your administrator account, remove the dummy account from the group "Secret service"
  2. Log in with the dummy account, navigate to the page "Secret headquarters"
    • If you can't see the page with the dummy, you did well!
    • If you can see the page with the dummy, then you probably didn't remove the dummy from the group "Secret service".
If you passed these small tests, then we are ready to go to the next step!

Writing the code to hide the page from the navigation

Let's first write down what we want to achieve:
  1. Loop through all links in the navigation on the left side of the subsite
  2. When we encounter a list item in which the href attribute ends with "Secret-headquarters.aspx", we want to check the permissions of that page
  3. If we encounter such an element, we will run a function that will fetch all the groups in which the current user is in
    • If the current user is a member of the group "Secret service", we will take no action and leave the navigation as is.
    • If the current user is not a member of the group "Secret service", then we will select that list item holding the link to "Secret-headquarters.aspx" and set it hidden.
I included some comments, be sure to read those too!
// The following three lines are required, don't forget to find a copy 
//of "jquery.SPServices-2013.01.min.js" and add a reference to it here.
SP.SOD.executeFunc("sp.runtime.js");
SP.SOD.executeFunc("SP.js", "SP.ClientContext");
SP.SOD.executeOrDelayUntilScriptLoaded("SP.UserProfiles.js", 
 "~sitecollection/Style Library/Scripts/jquery.SPServices-2013.01.min.js");

var siteUrl = "";
var element = "";

$(document).ready(function() {
 // We only want to loop through the navigation on the left side of the
 // subsite;
 if($("#NavRootAspMenu") != null) {
  // If present, remove the last list item. This sometimes appears and 
  // causes problems since it doesn't have a href attribute.
  $("ul[id*='RootAspMenu'] li.ms-navedit-editArea:last-child").remove();
 }
});

runMe(); 

function runMe() {
 var $this = $("#NavRootAspMenu");
 if($this != null) {   
  $this.find("li").each(function(i){
   // For each list item that has a "a" element, fetch the "href" 
   // attribute and write it to siteUrl.
   siteUrl = $this.find("a.static")[i].href;
   // When the siteUrl ends with "Secret-headquarters.aspx", save the 
   // current element to "element" and run a function.
   if (siteUrl.indexOf("Secret-headquarters.aspx") > -1) {
    element = $this.find("a.static")[i];
    sharePointReady(siteUrl, element);
   }
  });
 }
}          
      
function sharePointReady(siteUrl, element) {
 // Create an array that will hold a list of all the groups where the 
 // current user is a member of.
 var userGroupArray = new Array();
 var group;
 
 // The line below is handy in case you have multiple pages you want to
 // hide, but need to be accessed by different groups. 
 if(siteUrl.indexOf("Secret-headquarters.aspx") >- 1) { 
  group = "Secret service";
 } 
 
 // Get all groups where the current user is a member of.
 var userGroup = $().SPServices({ 
  operation: "GetGroupCollectionFromUser", 
  userLoginName: $().SPServices.SPGetCurrentUser(), 
  async: false, 
  completefunc: function(xData, Status) {
   $(xData.responseXML).find("Group").each(function() {
    // Push the name of the group to the array.
    userGroupArray.push($(this).attr("Name"));
   });
  }
 });
 
 // This useful little function is to check if an element is contained in
 // your array. 
 function include(arr, obj) {
  for (var i = 0; i < arr.length; i++) {
   if (arr[i] == obj) return true;
  }
 }

 // If the array contains the group "Secret service", then do nothing. 
 if(include(userGroupArray,group)) {
  //console.log("You can edit this!");
 }
 // If the array does not contain the group "Secret service", then hide
 // the element from the current user so that he/she cannot navigate to
 // the page. 
 else {
  //console.log("You can't edit this!");
  element.style.display="none";
 }
}

That's it! We're ready with the script. Now it's time to test it out and see if it works.

Adding a reference to the master page

If we want to apply this code on multiple subsites, then it is best that we add a reference to our script in the master page. I just added the code to an existing script that was already loaded on the master page (I use a HTML master page), but if you want to add it as a separate script, this is how it might look like:
<!--SPM:<SharePoint:ScriptLink language="javascript" ID="scriptLink1" 
runat="server" name="~sitecollection/Style Library/Scripts/scripts.js" 
OnDemand="false" Localizable="false"/>-->

Do note that the ID might be different. You must make sure that you do not already have a scriptlink with the same ID, so change the number of the ID and make it unique.
Check in your master page and your script, and go take a look at the page.
You can re-do the steps mentioned in "Testing the permissions of the page", and this time you will immediately see if the list item for the page "Secret headquarters" is present in the list or not.
It should now be hidden from users who are not a member of the group "Secret service", and it will remain visible to those who are a member of that group.

Enjoy!

If you have any questions, please do not hesitate to ask!
Special thanks go to Ali Sharepoint from Stack Exchange, who helped me with the code.
The code for "JavaScript Array Contains" was found on www.css-tricks.com.

Wednesday, November 27, 2013

UPDATE: How to show calendar events in modal dialogs in SharePoint 2013

I recently just noticed that my code for showing events in a calendar in a modal dialog does not always do its job. It appears that when you change to another month and then try to open an event in that month (or in any other month, since it fails the moment you change the month), the event won't open in a modal dialog! This also seemed to be the case when you changed the year.

Since I didn't just want to run the script whenever a user clicked a certain element (like those for the months and for the year), I came up with a different and rather easy fix.
I decided to just run the code everytime the user clicks anywhere inside the #content div. Don't worry, it won't alter any link inside your navigation, only those that have "DispForm.aspx" at the end.
// When called, this function opens the dialog.
function openDialog(pUrl) { 
var options = {
 width : 600,
 height : 400,
 url : pUrl };
 SP.SOD.execute("sp.ui.dialog.js", "SP.UI.ModalDialog.showModalDialog", 
  options);
}

// When called, this function makes sure each event in the calendar is
// opened in a modal dialog instead of on a new page.
function clickMe() {
 $('a[href*="DispForm.aspx"]').each(function() {
  $(this).attr("onclick", "openDialog('" + $(this).attr("href") + "')");
  $(this).attr("href","javascript:void(0)");
 });
}

window.onload = function () {
 clickMe();
 // A timeout is required for when the page first loads (if you would not
 // use a timeout, then the script won't always load).
 setTimeout(function() { 
  clickMe();
 }, 500);
 
 // When you click anywhere inside #content, it will run the function
 // "clickMe()" twice, once with and once without a timeout. 
 $("#content").click(function() {
  clickMe();
  setTimeout(function() {
   clickMe();
  }, 500);
 });
};

Please do note that it might be possible that your div has a different ID. I modified my HTML master page and I believe I added the div with #Content myself (it just wraps around the #sideNavBox and #contentBox divs), but if you're using the Seattle HTML master page, then you'll need to replace the code for the #content div (which I commented in the code below) with the code for #sideNavBox and #contentBox.
 //$("#content").click(function() {
 // clickMe();
 // setTimeout(function() {
 //  clickMe();
 // }, 500);
 //});

 $("#sideNavBox").click(function() {
  clickMe();
  setTimeout(function() {
   clickMe();
  }, 500);
 });
 $("#contentBox").click(function() {
  clickMe();
  setTimeout(function() {
   clickMe();
  }, 500);
 });

Or you could just modify your HTML master page as well and place a wrapping div around #sideNavBox and #contentBox.

Do make sure that you put a reference to this script on the page with the calendar. I mentioned this in my previous post but I'll say it again in case this is the first time you read about this.
I saved my code in a file named "calendar.js", under a folder named "Scripts" in the "Style library" directory.
Edit the page with the calendar, and at the bottom of a page, add a new script editor web part. Add the following code to that web part:
<script src="/Style%20Library/Scripts/calendar.js" 
type="text/javascript"></script>

Now save the page, make sure it is checked in and published, and try it out. If all went well, you'll now be able to open events in a calendar in a modal dialog! ;)

If you have any questions, do not hesitate to ask.

Tuesday, November 19, 2013

How to show calendar events in modal dialogs in SharePoint 2013

!!! UPDATE !!!
I noticed that my code won't always work, especially when you change to another month in the calendar. So I've rewritten it, you can find the new and correct code in this post. 
_________________________

I have a calendar on a page. When you make a new event in the calendar, you get to make it in a default SharePoint modal dialog (I enabled this in the advanced settings of the calendar). However, when you open an existing event in the calendar, it goes to a new page and shows that event as if I never even enabled modal dialogs.
This is some unwanted behavior, what I really want is that any event in the calendar is shown in a modal dialog, just like when you make or edit an event.

So, I decided to write some code. I added comments to the code to explain to you what it does and what it's for.
// When called, this function opens the dialog.
function openDialog(pUrl) { 
var options = {
 width : 600,
 height : 400,
 url : pUrl };
 
 SP.SOD.execute("sp.ui.dialog.js", "SP.UI.ModalDialog.showModalDialog", 
 options);
}

// When the class "ms-acal-month" is loaded, add an onclick attribute to
// all the links ending with "DispForm.aspx" so that the calendar items 
// will open in a dialog instead of on a new page.
$(".ms-acal-month").ready(function () { 
 setTimeout(function modal() {
  $("a[href*='DispForm.aspx']").each(function() {
   $(this).attr("onclick", "openDialog('" + $(this).attr("href") + "')");
   $(this).attr("href","javascript:void(0)"); 
  });
 }, 500);
});

// This function adds an onclick attribute to the class "ms-cal-nav" (the
// a tag that shows/hides extra items), code is needed when there are 
// more than three calendar items on a day. 
$(".ms-acal-month").ready( function() {
 setTimeout(function() {
  $("a.ms-cal-nav").attr("onclick", "clickMe()");
 }, 500);
});

// This function is called when the onclick attribute has been triggered.
// It needs to add the onclick attribute again, since SP automatically 
// removes this attribute as soon as the function was triggered. 
function clickMe() {
 setTimeout(function() {
  $("a.ms-cal-nav").attr('onclick', "clickMe()");
  $("a[href*='DispForm.aspx']").each(function() {
   $(this).attr("onclick", "openDialog('" + $(this).attr("href") + "')");
   $(this).attr("href","javascript:void(0)");
  });
 }, 500);
}

I saved my code in a file named "calendar.js", under a folder named "Scripts" in the "Style library" directory.
In order for the code to do its work, you'll have to put a reference to it on the page with the calendar. Edit the page with the calendar, and at the bottom of a page, add a new script editor web part. Add the following code to that web part:
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"
type="text/javascript"></script>
<script type="text/javascript" 
src="~sitecollection/Style%20Library/Scripts/calendar.js"></script>

Now save the page, make sure it is checked in and published, and try it out. If all went well, you'll now be able to open events in a calendar in a modal dialog! ;)

If you have any questions or if you are having problems with the code (not working, errors, unwanted behavior,...) feel free to ask!

Friday, October 25, 2013

How to make an accordion menu for a subsite in SharePoint 2013

If you use term driven navigation to manage all the pages on your subsites, and you have a lot of pages for a certain subsite, then your navigation might turn out to be quite long. In situations like this, it might as well come in handy to have an accordion menu that just collapses or expands its contents (terms) upon click. I'm going to use jQuery and JavaScript for this.

Of course, it would also be important that terms having underlaying terms can't act as a link (the link behind them, if any, shouldn't activate and open a new page). Terms that have underlaying terms should expand and show their underlaying terms.

Here's a screenshot of a term driven navigation with all the terms and underlaying terms visible, no accordion used yet:

What we want is a navigation that looks like this:
 =>
 =>

So basically you have all the categories (the top terms) collapsed. Upon clicking on a term that has underlaying terms, it should expand and show the underlaying terms of that term you just clicked on. And so on.
In the example above, when you open the second category, the underlaying terms expand. In here, there is another term that has underlaying terms, which I named the subcategory. You can once again click on this one and it will expand, showing its respective underlaying terms. If a term no longer has underlaying terms, it cannot expand and it just opens the page.

And now the real work.

You will need to create a JavaScript file (or just add the code in an existing script file if you already use scripts on your site) and make sure to add it to your master page. Mine is named "script.js" and its path is "~sitecollection/Style Library/Scripts/script.js". You will also need jQuery, so make sure you have that as well. My jQuery file its path is "~sitecollection/Style Library/Scripts/jquery-1.10.2.min.js".

To correctly make a reference to your scripts, you must add them to your master page. I'm using a HTML master page. Edit your master page in advanced edit mode and add the reference code after the "ScriptLink" lines. The code below has five ScriptLink references (references to default SharePoint scripts), the code you must add has to be after those scripts.
// The following five lines are already in your master page
<!--SPM:<SharePoint:ScriptLink language="javascript" name="core.js" 
OnDemand="true" runat="server" Localizable="false"/>-->
<!--SPM:<SharePoint:ScriptLink language="javascript" name="menu.js" 
OnDemand="true" runat="server" Localizable="false"/>-->
<!--SPM:<SharePoint:ScriptLink language="javascript" name="callout.js" 
OnDemand="true" runat="server" Localizable="false"/>-->
<!--SPM:<SharePoint:ScriptLink language="javascript" name="sharing.js" 
OnDemand="true" runat="server" Localizable="false"/>-->
<!--SPM:<SharePoint:ScriptLink language="javascript" name="suitelinks.js"
OnDemand="true" runat="server" Localizable="false"/>--> 
     
// Now use these following two lines to reference to your JavaScript
// files, with first referencing to the jQuery script and then your 
// own script.
<!--SPM:<SharePoint:ScriptLink language="javascript" ID="scriptLink1" 
runat="server" OnDemand="false" Localizable="false" 
name="~sitecollection/Style Library/Scripts/jquery-1.10.2.min.js"/>-->
<!--SPM:<SharePoint:ScriptLink language="javascript" ID="scriptLink2" 
runat="server" OnDemand="false" Localizable="false" 
name="~sitecollection/Style Library/Scripts/scripts.js"/>-->

Now that you have correctly made a reference to the jQuery script and your own script, you can save the master page (for now, since we'll add some more later).

Let's start with the script.

This is what the code in my script.js file looks like. I will try to add comments in the code.
function accordionMe(selector, initalOpeningClass) {
   var speedo = 300;
   var $this = selector;
   var accordionStyle = true;

   // First of all, hide all ul's:
   $this.find("li>ul").hide(); 

   // Then for each li you find in that ul,
   $this.find("li").each(function(){ 
      // that isn't empty,
      if ($(this).find("ul").size() != 0) { 
         // find all the ones at the top,
         if ($(this).find("a:first")) { 
            // and make sure it won't do anything on click.
            $(this).find("a:first").click(function(){ return false; });
            // Optional: if you want to style the non-clickable links, 
            // then uncomment the code below. 
            //$(this).find("a:first").addClass("no-click");
         }
      }
   });

   // Open all items.
   $this.find("li."+initalOpeningClass).each(function(){ 
      $(this).parents("ul").slideDown(speedo); 
   });

   // Execute this function on click of li with an a tag.
   $this.find("li a").click(function(){ 
      if ($(this).parent().find("ul").size() != 0) {
         if (accordionStyle) { 
            if(!$(this).parent().find("ul").is(':visible')){
               // Fetch all parents.
               parents = $(this).parent().parents("ul"); 
               // Fetch all visible ul's.
               visible = $this.find("ul:visible"); 
               // Loop through.
               visible.each(function(visibleIndex){ 
                  var close = true;
                  // Check if the parent is closed.
                  parents.each(function(parentIndex){ 
                     if(parents[parentIndex] == visible[visibleIndex]){
                        close = false;
                        return false;
                     }
                  });
                  // If closed, slide the content of the ul up 
                  // (so collapse).
                  if(close){ 
                     if($(this).parent().find("ul") != 
                       visible[visibleIndex]){
                        $(visible[visibleIndex]).slideUp(speedo);
                     }
                  }
               });
            }
         }
         if($(this).parent().find("ul:first").is(":visible")) {
            $(this).parent().find("ul:first").slideUp(speedo);
         }
         else {
            $(this).parent().find("ul:first").slideDown(speedo);
         }
      }
   });
}

There you have it, your code is done! Now all we need to do is make sure it will execute the function as soon as a page is loaded. We need to get back to our master page for this. So open your master page again (in advanced edit mode) and find the following piece of code:
<script type="text/javascript">
//<![CDATA[
 var g_pageLoadAnimationParams = { elementSlideIn : "sideNavBox", 
 elementSlideInPhase2 : "contentBox" };
//]]>
</script>

We will not change that part, but we will have to paste some code underneath it. Here's the code:
<script type="text/javascript">
//<![CDATA[
 var g_pageLoadAnimationParams = { elementSlideIn : "sideNavBox", 
 elementSlideInPhase2 : "contentBox" };

 $(function runOnInitLoad() {
  accordionMe(jQuery("#zz9_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz10_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz11_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz12_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz13_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz14_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz15_RootAspMenu"), "selected");  
  accordionMe(jQuery("#zz16_RootAspMenu"), "selected");  
  runThisCode(); 
  moveScroller();
  setCustomFontName('#fseaFont-1-1-Menu');
 });

 ExecuteOrDelayUntilScriptLoaded(function() { runOnInitLoad(); }, 
 "init.js");
//]]>
</script>

The reason that I use the function on so many different ID's is because these menu ID's get used often, spread across the site. These are just all the ones I needed, so I added them all. Feel free to add/remove some.

After you have saved your master page, checked it in and published it as a major version (and don't forget to check in and publish your scripts as well), we're all done! You now should have a nice accordion menu, sliding up and down as you click on it. :) Enjoy!


PS.: I would like to express my thanks to Mathias Bosman, who seriously helped me with this (basically, he made the whole script work). Thanks Mathias!

How to show more than three levels of sub-menu items in a subsite navigation in SharePoint 2013

In the beginning when I was still learning SharePoint, I had made my first quick launch navigation. The first thing I noticed whas the inability to have more than two or three levels of submenu-items. This was really bothering me since I had to make quite some categories (as I like to call them).
So then I found out I should use a term set navigation. Upon creating a nice navigation with many terms that had underlying terms and so on, I was quite disappointed when I found out it was showing only the first two or three levels. So I started to dig around in the master page, and found out how to fix this.

In the screenshot on the top right of the post, you can see up to six levels can be shown. Each level can be a category to define what kind of pages can be found underneath that category (like terms with underlaying terms, but I just like to refer to them as categories).

To activate this for your SharePoint site, you have to use term driven navigation and edit your master page. I have a HTML based master page, which means that if I make my changes in a HTML master page named "custom.html", it will then automatically convert it to a SharePoint fit master page named "custom.master". You will always need to make your changes in the HTML master page.
Anyway, I'll demonstrate what you need to do. I will use the code of the oslo.html master page.

In SharePoint Designer 2013, open your HTML-based master page in Advanced Editor mode. Search for "V4QuickLaunchMenu". You should find a long piece of code that looks like this:
<!--SPM:<SharePoint:AspMenu 
 id="V4QuickLaunchMenu" 
 runat="server" 
 EnableViewState="false" 
 DataSourceId="QuickLaunchSiteMap" 
 UseSimpleRendering="true" 
 Orientation="Horizontal" 
 StaticDisplayLevels="1" 
 DynamicHorizontalOffset="0" 
 AdjustForShowStartingNode="true" 
 MaximumDynamicDisplayLevels="2" 
 StaticPopoutImageUrl="/_layouts/15/images/menudark.gif?rev=23" 
 StaticPopoutImageTextFormatString="" 
 SkipLinkText="" 
 StaticSubMenuIndent="0"/>-->

Reformat it so that it looks like this:
<!--SPM:<SharePoint:AspMenu 
  id="V4QuickLaunchMenu" 
  runat="server" 
  EnableViewState="false" 
  DataSourceId="QuickLaunchSiteMap" 
  UseSimpleRendering="true"
  Orientation="Horizontal" 
  StaticDisplayLevels="1" 
  DynamicHorizontalOffset="0" 
  AdjustForShowStartingNode="true" 
  MaximumDynamicDisplayLevels="2" 
  StaticPopoutImageUrl="/_layouts/15/images/menudark.gif?rev=23" 
  StaticPopoutImageTextFormatString="" 
  SkipLinkText="" 
  StaticSubMenuIndent="0"/>-->

Now in order to get them to display from top to bottom, you have to change the value of Orientation from Orientation:"Horizontal" to Orientation:"Vertical".
To increase the amount of levels to display, change the value of StaticDisplayLevels from StaticDisplayLevels="1" to StaticDisplayLevels="6" and change the value of MaximumDisplayLevels from MaximumDynamicDisplayLevels="2" to MaximumDisplayLevels="6".
Your code should now look like this:
<!--SPM:<SharePoint:AspMenu 
  id="V4QuickLaunchMenu" 
  runat="server" 
  EnableViewState="false" 
  DataSourceId="QuickLaunchSiteMap" 
  UseSimpleRendering="true"
  Orientation="Vertical" 
  StaticDisplayLevels="6" 
  DynamicHorizontalOffset="0" 
  AdjustForShowStartingNode="true" 
  MaximumDynamicDisplayLevels="6" 
  StaticPopoutImageUrl="/_layouts/15/images/menudark.gif?rev=23" 
  StaticPopoutImageTextFormatString="" 
  SkipLinkText="" 
  StaticSubMenuIndent="0"/>-->

Save the master page. Make sure it is checked in and published as a major version (also, it has to be your defailt master page). Now go check if your term driven navigation is displayed correctly. If it does: hurray! You did it right! If it doesn't, then you might have missed a spot somewhere. ;)

Any questions, let me know.

Wednesday, October 23, 2013

How to make a contact form in SharePoint and submit the messages to a SharePoint list

I had to make a contact page for an intranet SharePoint site, and didn't like the idea of receiving dozens of e-mails every single day. First of all that would really flood my mailbox and I would have to make a folder in my mailbox just for contact messages received by the intranet site, and second of all I just don't like having to read a lot of new e-mails.

So! I decided that I wanted all the messages to be stored in a SharePoint list, and I wrote a script to handle this. The script fetches the subject, message, full name and e-mail address of the user who sends a message through the contact form. Only the subject and the message have to be filled in by the user, the full name and e-mail address are fetched automatically based on the current user. If everything is correct and validates, it saves the data as a new list item. 

Here are some screenshots of what it will look like.

The contact page with the contact form:

The contact form when you try to click send without filling in anything:

The contact form when you filled in the fields and pressed send:

So you see, it has proper validation. If one of the fields or both isn't filled in, it won't get sent as an empty message. If it is filled in properly and the user has pressed send, it will be sent to the Contact list and the input fields and send button will be disabled (to prevent the user from sending the same message again).

If the user has successfully submitted a message, he/she can follow the status of his/her message on another page (or you can put it on the same page, depends on what you like). I've put it on a second page, and this is what it looks like:

Depending on the status of the message, it can be found under either "Sent", "Received" or "Answered". These three tabs are three web parts with different views.

Let's begin. 

First of all, you will need to make a SharePoint list in which you want to store all the messages.
My list is named "Contact".
I created 7 new columns: "Date", "Name", "Email", "Title", "Message", "Status" and "Answer". The "Title" column was a default column that can't be removed, but I'll just use it instead of making a new column for the subject.

Here's an overview of all the columns your list will need:
ColumnTypeUsed for
DateDate and TimeStoring the date and time of the message
NameSingle line of textStoring the name of the user who sent the message
EmailSingle line of textStoring the e-mail address of the user who sent the message
TitleSingle line of textStoring the subject of the message
MessageMultiple lines of textStoring the message
StatusChoiceSetting the status of the message (Sent/Received/Answered)
AnswerMultiple lines of textStoring the answer of the administrator


You will also need to create views for the Contact list. Each view has a filter applied. The first view is filtered to only show items of which the Status column equals the value "Sent", the second view is filtered to only show items of which the Status column equals the value "Received", and the third view is filtered to only show items of which the Status column equals the value "Answered".
What is also very important, is that each view should have 2 filters. The first is to filter the status of the message, the second filter is to make sure only the person who sent the message can see his own message. The items in these views have to satisfy both requirements that have been set in the filters. Other people shouldn't be able to see the messages of others. To do so, set the second filter of all the views to show only items when the column "Made by" equals "[Me]". By doing so, only the person who sent the message will see his message. You as an administrator will off course always be able to see the messages since you can just make another view for yourself and skip the second filter.

When your list is set up, we can begin on preparing the contact page with a contact form. I made a content editor web part and added the following code to it (edit source of the web part first, then add the code):
<table id="ContactTable"> 
   <tbody>
      <tr> 
         <td class="contactLabel">Subject:</td>
         <td colspan="2">
            <input class="contactInput" id="Subject" name="Subject" 
                   type="text" /> 
         </td>
      </tr>
      <tr> 
         <td class="contactLabel">Message:</td>
         <td colspan="2">
            <textarea class="contactInput contactInputMessage" 
                      id="Message" name="Message"> </textarea> 
         </td>
      </tr>
      <tr>
         <td></td> 
         <td>
            <span id="FeedbackField"> </span> 
         </td>
         <td>
            <div id="ClickMeButton">Send​​​​​​​​​​​​​​</div>
         </td>
      </tr>
   </tbody> 
</table>

Put a script editor web part at the bottom of the Contact page and add the following code to it (I stored my script in the MasterPageGallery folder, but wherever you plan on making your script, just make sure that the reference is correct):
<script type="text/javascript" 
src="~sitecollection/_catalogs/masterpage/MasterPageGallery/Contact.js">
</script>

For the Contact overview page, edit the source and add the following code:
<div id="ContactTabs">
   <div id="tabs1">
      <ul>
         <li><a href="#tabs1-1">Sent</a></li>
         <li><a href="#tabs1-2">Received</a></li>
         <li><a href="#tabs1-3">Answered</a></li>
      </ul>
      <div id="tabs1-1">
        <!-- Space reserved for a content editor web part with a view for
             "Sent" -->
      </div>
      <div id="tabs1-2">
        <!-- Space reserved for a content editor web part with a view for
             "Received" -->
      </div>
      <div id="tabs1-3">
        <!-- Space reserved for a content editor web part with a view for
             "Answered" -->
      </div>
   </div>
</div>

Then put a script editor web part at the bottom of your Contact overview page and include the following code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
  $(function() {
    $( "#tabs1" ).tabs();
  });
</script>

This is the CSS for the above contact form and for the contact overview (best to put this in a CSS file and add a link to that file in your master page):
#ContactTable {
 margin-left: auto;
 margin-right: auto;
}

#ClickMeButton {
 padding: 5px;
 background-color: #d7d6d8;
 border: 1px solid gray;
 width: 78px !important;
 margin-top: 10px;
 font-family: 'Francois One', sans-serif;
 text-transform: uppercase;
 letter-spacing: 0.1em;
 text-align: center;
 float: right;
}

.contactLabel {
 width: 100px;
 display: table-cell;
 vertical-align: top;
 padding-top: 4px;
 text-align: right;
 padding-right: 10px;
}

.contactInput { width: 400px; }

.contactInputMessage {
 max-width: 650px !important;
 min-width: 650px !important;
 min-height: 100px;
 max-height: 200px;
}

#ContactTabs .ms-webpartzone-cell { margin-top: 10px; }

#ContactTabs {
 margin-left: auto;
 margin-right: auto;
 width: 700px;
}

All right! We have now set up the Contact page and the Contact overview page and styled them. Don't forget to add the content editor web parts to the Contact overview page.

Now all we need is functionality!

Create a JavaScript file, I created mine in SharePoint Designer 2013 and it is located in _catalogs/masterpage/MasterPageGallery/Contact.js. You can put it somewhere else if you want to, but this is just where I put it.

Here's the code of my Contact.js file, I added comments to explain to you what everything does. Please keep in mind that I might not have put comments everywhere, but I do my best!
// Load the scripts, make sure you have a script for jQuery as well.
SP.SOD.executeOrDelayUntilScriptLoaded(sharePointReady, 
"SP.UserProfiles.js", 
"~sitecollection/Style Library/Scripts/jquery.SPServices-2013.01.min.js"
);
SP.SOD.executeFunc("SP.js", "SP.ClientContext", sharePointReady);

// run the following function.
sharePointReady();

function sharePointReady() {
  // Initialize a new instance of the ClientContext object.
   var clientContext = new  SP.ClientContext.get_current();   
   this.website = clientContext.get_web();
   this.currentUser = website.get_currentUser();
  
   clientContext.load(currentUser);
   clientContext.load(website);

   // Execute the query, add functions to launch when it succeeds/fails.
   clientContext.executeQueryAsync(
      Function.createDelegate(this, this.onRequestSucceeded), 
      Function.createDelegate(this, this.onRequestFailed)
   );
}

function onRequestSucceeded() {   
   // Fetch the full name of the user that is sending the message.
   var fullUserName = $().SPServices.SPGetCurrentUser({
      fieldName: "Title",
      debug: false
   });

   // Fetch the e-mail address of the user that is sending the message.
   var emailAddress = $().SPServices.SPGetCurrentUser({
      fieldName: "Email",
      debug: false
   });
  
   // Execute the following function.
   SendEnquiry();
 
   function SendEnquiry() {
      document.getElementById('ClickMeButton').onclick = function(){   
         var NameField = fullUserName;
         var emailField = emailAddress;
         var subjectField = document.getElementById("Subject").value;
         var messageField = document.getElementById("Message").value;

         // If one of the input fields or both input fields are empty,
         // then give feedback.
         if( (subjectField == "" && messageField == "")
          || (subjectField == "") || (messageField == "") ){
            document.getElementById("FeedbackField").innerHTML =
               "Please fill in all the fields. ";
            document.getElementById('FeedbackField').style.color = "red";
         } 
         // If both fields are filled in, start the function to save
         // the values as a new list item in the Contact list.
         else {   
           SaveInContact(NameField,emailField,subjectField,messageField);
         }
      };
   }

   function SaveInContact(Name,Email,Subject,Message) {
      // Initialize a new instance of the ClientContext object for the 
      // specified SharePoint site.
      var context = new SP.ClientContext.get_current(); 
      var web = context.get_web();
      // Get the list in which you want to store the values, we use the 
      // Contact list.
      var list = web.get_lists().getByTitle("Contact");  
      var listItemCreationInfo = new SP.ListItemCreationInformation();   
      var newItem = list.addItem(listItemCreationInfo);
      // This below is to set which column will get which value, the 
      // first part is the name of the column and the second part is 
      // the value it will get.
      newItem.set_item("Title", Subject);
      newItem.set_item("Name",Name);
      newItem.set_item("Email",Email);
      newItem.set_item("Message",Message);
      newItem.set_item("Status",'Sent');
      newItem.update();

      context.executeQueryAsync(
         Function.createDelegate(this, this.onAddSucceeded), 
         Function.createDelegate(this, this.onAddFailed)
      );
  
      document.getElementById("FeedbackField").innerHTML = 
         "Thank you! Your message has been sent. ";   
      document.getElementById('FeedbackField').style.color = "green";
      // Disable the input fields and the button to prevent the user 
      // from submitting the same message again.
      document.getElementById("Subject").disabled = true;
      document.getElementById("Message").disabled = true;
      document.getElementById("ClickMeButton").disabled = true;
      document.getElementById("ClickMeButton").style.backgroundColor = 
         "#ECEBEC";
   }
}

function onRequestFailed(sender, args) {   
 console.log("Error: " + args.get_message());
 alert("Request failed: " + args.get_message() + '\n' 
   + args.get_stackTrace());
}

function onAddSucceeded() {
 document.getElementById("ClickMeButton").style.color = "green";
}

function onAddFailed(sender, args) {
 alert("Error: " + args.get_message() + "\n"+ args.get_stackTrace());
}

(function () { 
 document.getElementById("ClickMeButton").onclick = SendEnquiry();
})(); 


That's it! With this code, you should now have a functional contact form. :)

Got questions? Need extra information? Are you stuck at some part? Then do not hesitate to comment, I'll do my best to help you as soon as I can. Also, adding console logs everywhere in the code might help. That way you can see what get executed and what doesn't.


Regards,

Magali

Tuesday, October 22, 2013

Trying to take over the world... One post at a time.

My boyfriend told me I should have a blog. To post about all the little things I do that make me happy. Creative things, crafts. I'm also just going to put some handy SharePoint posts here, since I often have the feeling that some of the things I code might actually come in handy for other people. So yeah. :)

Perhaps a small introduction is in place!

My name is Magali. Yes, I am female.
I'm a junior analyst programmer and I work at the college university of Ghent, where I also graduated as bachelor in Applied Computer Science in 2012.
My job is to make a new kind of intranet site in SharePoint 2013. At first I didn't even know how to work with SharePoint since I only had a few workshops during my education, but I was given the opportunity to learn more about SharePoint and to study it in order to properly do my job. And here I am now, actually enjoying SharePoint. I still like to code in JavaScript though, so I often use JavaScript to make things work.

Other than that, I also have a wide arrange of hobbies. 

I'm often told that I have too many, but I enjoy them all. Variation, yay! Here's what I like to do:
  • play the piano
  • watch series and movies
  • go to the movies
  • play video games (both on computer and consoles)
  • make things with perler beads in 8-bit style
  • sew hand-made felt plushies
  • craft things out of cardboard (mostly miniature furniture)
  • collecting Pokémon games
  • going for a swim
  • dozens of other things 

Also, I'm geeky

Indeed I am! A geeky girl. To me, being geeky means that I'm passionate about something. Not only about computer business and gaming, but also about hobbies like crafting. I do tend to sometimes mix the two (like making 8-bit Space Invaders, you just wait until that project is finished and you will be amazed!).

Anyway, please do enjoy my blog. Expect lots of coding, crafting, geeky creativity and cat pictures!


- Magali


PS: The cake IS a lie. No, seriously, did you see that recipe?