We have a requirement like whenever our one custom site is get created, on welcome page one of our custom web part should be added by default. Since our custom site is based on OOB team site template, welcome page of the site is wiki page.
So here I will discuss steps to add our custom web part on wiki page.
Here problem with Wiki page is we do not have web part zone so that we can’t directly add into given zone. Here on wiki page we have content field available and we need to put some mark up as the value of this field.
So written one web level feature and in feature activated added code
Steps:
- Getting the web instance.
- SPWeb web = properties.Feature.Parent as SPWeb;
- Get the welcome page.
- string welcomePageUrl = web.RootFolder.WelcomePage;
- SPFile welcomePage = web.GetFile(welcomePageUrl);
- Check out the welcome page.
- Get the webpart manager as.
- SPLimitedWebPartManager wpmgr = welcomePage.GetLimitedWebPartManager(PersonalizationScope.Shared)
- Create the instance of our custom webpart and add using webpartmanager.
-
-
-
- Guid storageKey = Guid.NewGuid();
- string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));
-
-
- MyCustomWp myCustomWP = new MyCustomWp();
- myCustomWP.ID = wpId;
- myCustomWP.ChromeType = PartChromeType.None;
- myCustomWP.Title = “My Custom WP”;
-
- wpmgr.AddWebPart(MyWorkspacesWP, "wpz", 0);
- Set the MarkUp required to Content field for the wiki page.
- string markup = string.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", new object[] { storageKey.ToString("D") });
-
-
- SPListItem item = welcomePage.Item;
-
-
- item[SPBuiltInFieldId.WikiField] = markup;
- item.Update();
- welcomePage.Update();
- Finally check in the page.
- welcomePage.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
Thanks!
Enjoy SharePoint
Your comments/suggestions/feedback is most welcome!