سؤال

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.

هل كانت مفيدة؟

المحلول

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى sharepoint.stackexchange
scroll top