1,804 articles and 14,608 comments as of Saturday, February 19th, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Wednesday, January 14, 2009

Automatically Switching Views When Opening A SharePoint Folder

‘BobW’ from our “Stump The Panel” forums asked, “Is there a way to automatically change from View A to View B when a user opens a SharePoint folder?”

Normally, I’d say “Unfortunately, the answer is No” since folders are part of the list and will always use whatever Views have been setup for the list itself (no separation in “Default” view between folders – they all will use the same), but after reading this question, I decided to take on the problem to see what (if anything) could be done to get around this.

After working on this for a few days (thanks for the help Paul!!), I was finally able to come up with a way to accomplish this through the use of JavaScript and “Content Types”.

The process to create this functionality involves three main steps:

  1. Create “Folder” Content Types for each folder you wish to have a different view associated with.
  2. Create Views for each Content Type in the list.
  3. Add the JavaScript to a CEWP on your default view page.

Step 1: Create the “Content Types”

In your site, go to the “Content Types Gallery” (Site Actions > Site Settings > Site Content Gallery) and click “Create”.

Add a name for the “Content Type”, choose “Folder Content Types” and “Folder” from the dropdowns, leave the rest as is and then click “OK”.

For this, I’ll be using three new “Content Types” named:

  1. “Financials_Folder”
  2. “Personnel_Folder”
  3. “Records_Folder”

Add the Content Types to your list.

In your list, click “Settings -> List Settings”, then “Advanced Settings” and choose “Yes” for “Allow management of content types”.

In the list settings, click “Add from existing site content types” to add in our types.

On the next screen, filter the list by choosing “Custom Content Types” then select each of the three new types and click “Add” to add them to the list.

After clicking “OK”, you should see your types added to the list in the settings page and as options on the “New” link when you create a new item for the list.

Step 2: Create custom Views

Now that you have the “Content Types” added and ready to use, create a matching custom view for each type using the same name (do this for each “Content Type”).

Once completed, you should have views for each “Content Type” (folder):

Create several new folders based on the content types we’ve setup (I’m using simple names for testing purposes to indicate each folder’s CT):

Clicking on each will take you into the folder, but will also continue to use the same “View” we were on before entering the folder (”All Items”).

To get around this, we’ll add our JavaScript to a “Content Editor Webpart” (CEWP) on our “Default View” page.

Step 3:Add JavaScript to CEWP

Add a new CEWP to the page. The page is “AllItems.aspx” in this case, since it’s our default view page. Make sure to “Drag” it below the list webpart.

As with all solutions involving the use of JavaScript in a CEWP, we place the webpart at the bottom of the page in order for it to be able to look through the entire HTML on the page that exists before it to find specific data.

Once you have the CEWP on the page, open its “Tool Pane” then its “Source” option, and add in the following script:

<script type="text/javascript">
var splitStr = document.location.pathname.split("/");
var newStr="";

for(i=0;i<splitStr.length-1;i++)
{
  newStr+=splitStr[i]+"%2f";
}

var tbls = document.getElementsByTagName("table");

for(i=0;i<tbls.length;i++)
{
  if(tbls[i].CType!=null)
  {
    var linkHref = document.getElementById(tbls[i].id).getElementsByTagName("a");
    var linkText = document.getElementById(tbls[i].id).innerText;

    for (j=0;j<linkHref.length;j++)
    {
      linkHref[j].setAttribute("onclick",document.location.pathname.replace("AllItems.aspx","")+tbls[i].CType+".aspx?RootFolder="+newStr+linkText);
      linkHref[j].href = document.location.pathname.replace("AllItems.aspx","")+tbls[i].CType+".aspx?RootFolder="+newStr+linkText;
    }
  }
}
</script>

How the Script works:

The script grabs the current path of the page and splits it into a list (”Array”) of objects based on the forward-slash (”/”) character in the URL.

Example:

Full URL to list: http://www.myportal.com/abc/123/def/lists/MyList/AllItems.aspx

Page path would be: /abc/123/def/lists/MyList/AllItems.aspx

Splitting on the “/” character will create a series of objects as:

Index[0] = abc
Index[1] = 123
Index[2] = def
Index[3] = lists
Index[4] = MyList
Index[5] = AllItems.aspx

Counting these, we have a total of 6 objects starting at the first index position [0].  The Script trims the list by one (the “splitStr.length-1″ part) and then loops through the remaining objects building them back into a complete string, but separates each piece by the HTML-Encoded equivalent of the forward slash (”/” becomes “%2f”) in order to format it properly for the new URL.

Next, the Script looks for and reads all tables (in the page’s HTML) and begins to loop through each one looking for an attribute that indentifies it as having a “Content Type” (the “tbls[i].CType” part).  If it does, this informs us that it’s one of our “Folder” links on the page, so we can begin to process its link properties.

Once we have our tables, or more literally – as we find a table that has a “Content Type”, we create two placeholders for the “a” tag (the actual link object) and its text (the text displayed for our folder).

The Script closes out with a simple loop through each link where it overrides the built-in (SharePoint) JavaScript action for the link’s “onclick” method and actual “HREF” property, by updating its target URL (where it will take you after clicking the link) to point to a dynamically built address consisting of a new “View” page that matches up with the “Content Type”, our modified page path (from the beginning of the Script), and the appropriate link text (this makes sure we not only go to the correct “View” page, but also that we arrive in the correct folder as well).

Conclusion

The Script itself is pretty simple in its design (many thanks again to Paul Grenier in his suggestion of the use of “Content Types” with this to simplify things), but what it does is so much more.

Till next time…

- Dessie

 

Please Join the Discussion

17 Responses to “Automatically Switching Views When Opening A SharePoint Folder”
  1. larry says:

    Very impressive. Will this only work with the folder content types?

  2. Christophe says:

    For the record, the JavaScript in a CEWP does not always need to be at the bottom of the page (for example if you use _spBodyOnLoadFunctionNames).

  3. larry,
    Although this script is designed to use specifically with the Content Types created in the examples, I’m sure it could be modified to work with any Content Type.

    - Dessie

  4. Christophe,
    You are correct…thanks for pointing out my error.

    - Dessie

  5. Ward says:

    This can also be done without using JavaScript.
    When you create a view, there is an option ‘Folders’ where you can select wether to show this view in the top-level folder or to show this view in a folder content type.

    So why make it so difficult when it can be done with an out of the box functionality?

    See also : http://officesharepointpro.com/TabId/149/NodeId/1923/Implementing-Folder-Content-Types.aspx

    Ward

  6. Kaiser says:

    This is really a useful approach. Is it also possible to use this for a document library?

  7. Lindon says:

    Response to Ward’s comment.

    The reason for doing this with Java is that the OOB function will not change the default view when navigating into folders. Sure the settings you describe enable you to make certain views only visible in certain folders, but no combination of settings (that I can find) allow you to change the default view dependent on the folder content type.

    This code, along with carefully considered content types and views, allows you to much more fully craft functionally varied list items into one list.

    I’d be happy to give a more complete example if required, and happier to find a way OOB to change the default view in a folder.

    Dessie, until version next (which always solves every issue we have with current version, thank you for your post… excellent!

  8. Jay says:

    Nice tip, thanks! Works well with one exception:

    I have 5 folder content types and have implemented the content types, views and folders per the instructions.

    Navigating into the folders within my document library works well and the view switches as it should. However when I click the breadcrumb trail to return to the root of the library the view does not switch back to the “All Documents” view.

    Is there a “/clear” type of function that could be added to the script to force this, or perhaps another alternative?

    Thanks again!

  9. Jay says:

    Ok, there is a no code way to accomplish this task.

    Zubair Alexander posted how to do this on his blog at http://blog.techgalaxy.net/archives/1109

    I have tested this and it does work.

  10. dave says:

    page not found errors when I copy and paste the code above into the source editor of the CEWP. trying to do this in a document library, adding only 1 content type called “Recorded Calls” with a matching view. Could be I have spaces in the URL to the document library?

  11. larry says:

    Is the JavaScript still available?

  12. Larry – Try it again. Should be visible now. — Mark

  13. larry says:

    Thanx Mark. You guys are the greatest. I can’t even image the effort to convert all you had before to what you have now. Thank you for all your hard work. If I can ever help or support you please let me know.
    Larry

  14. Thanks Mark!!

    - Dessie

  15. Ashfaq says:

    nice article.
    i hav multiple folders in a sharepoint list.when i go to any folder in the list, i need to dynamically populate a field with the name of the current folder.so anyone can tell me how to get the current list folder name through the javascript..?

  16. larry says:

    @Ashfaq ,
    here is a script, props to Alexander at sharepointjavascript.wordpress.com. this script sets the value of a field by using the FieldInternalName to find the field. Place it on NewForm after the form at the bottom.
    I am sure with some tweeking your value can be based on the folder selected. You also have the option of using query string values and grabing you val from the string and setting the field. th

    [script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js">[/script>
    [script type="text/javascript">
    fields = init_fields();
    // Find the Title-field and insert text
    $(fields['Title']).find('input').val("Insert this text in the Title-field");
    
    function init_fields(){
    var res = {};
    $("td.ms-formbody").each(function(){
    if($(this).html().indexOf('FieldInternalName="')<0) return;
    var start = $(this).html().indexOf('FieldInternalName="')+19;
    var stopp = $(this).html().indexOf('FieldType="')-7;
    var nm = $(this).html().substring(start,stopp);
    res[nm] = this.parentNode;
    });
    return res;
    }
    [/script>
    
  17. Joe Dragon says:

    Sharepoint provides this functionality OOTB, as shown here http://www.mikhaildikov.com/2008/05/sharepoint-folders-need-more-love.html

    Folders really do need more love!!!


Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!