Wednesday, May 25, 2011

Creating multi level discussion groups programmatically

Recently, I was required to create a multiple level discussion groups.

As we know, Sharepoint 2010 offers only one level of Discussion group (at least as far as I know) i.e., First level is Discussion Group and the inner level is Discussion Threads (individual posts).


What did I do, I create the discussion group programmatically and move the created group under an existing discussion group. This way, I was able to achieve multiple levels of discussion groups.

 var web = SPContext.Current.Web;    
 var discussionList = web.Lists[DISCUSSION_LIST_NAME];
 var discussionContentType = 
web.AvailableContentTypes[DISCUSSION_CONTENT_TYPE_NAME];
 
web.AllowUnsafeUpdates = true;
  
 var newDiscussionItem = SPUtility.CreateNewDiscussion(discussionList, title);
 newDiscussionItem["Title"] = title;
 newDiscussionItem["ContentTypeId"] = discussionContentType.Id;
 newDiscussionItem["ContentType"] = discussionContentType.Name;
newDiscussionItem.Update();
 
 //if the discussion group is a child discussion (Thread) 
 //then move the discussion group 
 //to a sub level (under its parent discussion group)
 if (parentDiscussionID != -1)
 {
    var parentDiscussionGroup = discussionList.GetItemById(parentDiscussionID);
    var destinationUrl = parentDiscussionGroup.Url + "/" 
+ newDiscussionItem.Folder.Name;
    newDiscussionItem.Folder.MoveTo(destinationUrl);
 }
 web.AllowUnsafeUpdates = false;
 
 
Using the above method of .Folder.MoveTo() any SPListItem can be moved to any destination. Hope this would help someone else.

4 comments:

  1. I would love to use this technique on our new SharePoint server however I'm not sure how to add/use the code. Any help would be appreciated.

    ReplyDelete
  2. Hi James,

    I am just using the OOTB Dicussion Board and creating multi-level (group within another group). SP provides only one level i.e., you cannot create a discussion group within an existing group by default. I create the group using SPUtility.CreateNewDiscussion() and then I move it as a child to an existing group using newDiscussionItem.Folder.MoveTo() statement.

    If you can provide me with more details, I might be able to help you more.

    Senthil

    ReplyDelete
  3. Thanks for the reply Senthil,

    I should have been more specific. How do you run the code? I am relatively new to programming in SharePont. Does it need to be added to a Masterpage or executed on the server? Many thanks!

    ReplyDelete
  4. I have this code in a button click event handler for creating new discussion groups.

    ReplyDelete