Wednesday, 18 March 2009

Manage Internal NavigationNodes in Quick Launch

I build a little tool to move sites within a site collection. Moving sites works fine, but a bit strange that the link to the site is still present on the 'sites' heading on the quick launch bar of the parent site. So I decided to remove the link on the old parent site and create one on the new parent. Quite normal, not?
Well than I run into some troubles with adding links of subsites on the quick launch bar of the parent site.
I want to add the link under the 'sites' heading, so I found some code samples on the internet to do that. To add links to external sites is fine, Just create a new SPNavigationNode like this: with title, url and 'false'

Dim newNode as SPNavigationNode = _
New SPNavigationNode(webTitle, webUrl, False)

But for adding links on this way for subsites (which is actually an internal link) is slightly different. You don't need to add the full url, but that part of the url that's right behind the parent url.
So, if your subsite is http://intranet/project/demo, you need to enter only 'demo' (without the quotes of course).
So remeber, you need to get rid of the parent url part, because SharePoint will add that part just before your entered url. This will raise an error due to an invalid url.
My code will now look like this:

' NewParentWeb is an object of type SPWeb
Dim mySite As SPSite = New SPSite(NewParentWeb.Url)
Dim quickLaunchWeb As SPWeb = mySite.OpenWeb()
Dim quickLaunchNodes As SPNavigationNodeCollection = _
quickLaunchWeb.Navigation.QuickLaunch

' GetSitesNodeIndex is a function that returns the index of the 'sites'
' heading on the quick launch bar.
Dim sitesNodeIndex As Integer = GetSitesNodeIndex(quickLaunchWeb)

Dim navUrl As String = _
WebToMove.Url.Replace(NewParentWeb.Url & "/", "")
Dim newNode As SPNavigationNode = _
New SPNavigationNode(WebToMove.Title, navUrl, False)

quickLaunchNodes(sitesNodeIndex).Children.AddAsLast(newNode)

quickLaunchWeb.Update()

Edit:
Some of you asked for the GetSitesNodeIndex function. So I put it here.

Private Function GetSitesNodeIndex(ByVal web As SPWeb) As Integer

Dim i As Integer = 0
Dim nodes As SPNavigationNodeCollection = web.Navigation.QuickLaunch

For i = 0 To nodes.Count - 1
If nodes(i).Id = 1026 Then
Return i
End If
Next
Return Nothing
End Function

1026 is the node id of the site index. But you can also verify on the title property.

2 comments:

woodyhallen said...

can yo post GetSitesNodeIndex code

Robje said...

Hi woodyhallen,

I edit the post and put the function you requested inside.

Good luck!