Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

we are to create several web parts after a site is provisioned with WSP. I can either create wp from scratch on feature action. Or save a set of WP in gallery and create an instance out of that when needed. The wsp for site template also creates list and libraries where these wp will go. Hope I am making sense. What are my best options to create WP when site is provisions. I will have to add some code to create WP at the end of provisioning site so I am certain all the lists have been created. Please suggest.

share|improve this question
    
What does your web part need to do, and do you need it provisioned on a page when a site is created? –  James Love Apr 29 '11 at 17:22
    
I think they are just regular web part with normal view. –  Roxanne Apr 29 '11 at 21:39

1 Answer 1

up vote 5 down vote accepted

Ok, consider we have this environment:

  1. We have farm-level WSP file (this also could be sandboxed in this situation, but for clarity, let's consider it is a farm one).
  2. This WSP contains some lists and libraries definitions/instances, and also some visual webparts.
  3. Also, WSP file contains at least one feature in it.
  4. This WSP is added into your farm, deployed to specified site collection and feature is activated there. So, lists and libraries are created and webparts are added into the gallery.
  5. After all this done, we want to instantiate a webpart 'Webpart1' at 'default.aspx' site page.

From this point, we can add some code to the feature receiver (into FeatureActivated), to accomplish our goal. This code will look smth like this:

// prepare the webpart
var webPart = new WebPart1();
// ...here you can initialize some webpart properties, if needed

// fetch SPFile object for default.aspx page
SPFile page = web.RootFolder.Files["default.aspx"];
if (page.Exists)
{
   // ...here you probably need to check out the page if it is a publishing site

   // get LimitedWebPartManager object for the page
   var webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
   // add our webpart into the 'Main' webpart zone, using zone index = 1
   webPartManager.AddWebPart(webpart, "Main", 1);

   // ...do not forget to commit your changes here if you are using publishing site

   // save our changes
   page.Update();
}

MSDN references:

  1. SPLimitedWebPartManager
  2. SPLimitedWebPartManager.AddWebPart
  3. How to: Work with Web Parts on a Page
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.