Search code examples
c#powershellsharepointsharepoint-2010sharepoint-list

Configure per-location view settings programmatically


I have a feature on my SharePoint site that adds views to a list when the feature is activated.

On SharePoint's list settings menu, we have a link that says "display settings by location" (or "Per-location view settings" in English installations). When I activate my feature, all of my views are in the right column of "views available at this location". But for some views I want them to be in the left column, "views hidden at this location".

I tried setting the parameter "Hidden" to true for my concerned views but this caused my views to disappear from the per-location view settings page altogether.

Is it possible to manage which views are displayed / hidden at specific locations in C# or in Powershell?


Solution

  • A location in this instance refers to a folder within your list (or the root folder if no other folders exist).

    To access which views are displayed or hidden within a particular folder, access the client_MOSS_MetadataNavigationSettings property of that folder.

    That property will be a string of XML containing a <ViewSettings> element, inside of which you'll see <View> elements for any views that have been configured with special per-location settings. The Index attribute of a <View> node will be a string representation of a negative number if the view is set to be hidden from that location.

    A brand new view will show up on all folders by default, but will not have an entry in the <ViewSettings> collection; if you want to hide it, you'll need to create a new XML element and insert it into the property.

    Here's an example in Powershell of hiding a view from the root folder:

    $viewName = "Secret View"
    $web = get-spweb http://example-site
    $list = $web.Lists["Example List"]
    $viewToHide = $list.Views | where-object { $_.Title -like $viewName }
    $folder = $list.RootFolder
    $settings = [xml]$folder.GetProperty("client_MOSS_MetadataNavigationSettings")
    $view = $settings.MetadataNavigationSettings.ViewSettings.View | where-object { $_.ViewId -like $viewToHide.Id }
    if($view -ne $null){
        $view.Index = "-1"
    }else{
        $view = $settings.CreateElement("View")
        $settings.MetadataNavigationSettings.ViewSettings.AppendChild($view)
        $view.setAttribute("ViewId",$viewToHide.Id)
        $view.setAttribute("CachedName",$viewToHide.Title)
        $view.setAttribute("Index","-1")
        $view.setAttribute("CachedUrl",$viewToHide.Url)
    }
    $folder.SetProperty("client_MOSS_MetadataNavigationSettings",$settings.OuterXml)
    $folder.Update()