How to create a new site based on a custom site template

Here is a method to create a sub site based on a custom site template.  You need to pass in your new site name and the name of the site template.  It will check the available site templates for the one you specified (so you must deploy the site template first).  If it’s not there an error gets displayed.  I put a label on my web part to display the error _lblErrMsg.  You will need that control (or you can remove it and handle errors whatever way you want.

private bool CreateSubSite(string newSiteName, string ProjectsiteTemplateName)
      {
          try
          {
              SPWeb webSite = SPContext.Current.Web;

              webSite.AllowUnsafeUpdates = true;

              //Get all the site templates
              SPWebTemplateCollection Templates = webSite.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));

              //Get the specific project template
              SPWebTemplate siteTemplate = null;

              //Verify the custom site template exists
              if (templateExists(Templates, ProjectsiteTemplateName))
              {
                  siteTemplate = Templates[ProjectsiteTemplateName];
              }
              else
              {
                  _lblErrMsg.Text = "Could not find the custom site template.";
              }

              if (siteTemplate != null)
              {

                  SPWeb newWeb; 
                  newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(
                      newSiteName.Trim(),
                      newSiteName,
                              "Project Site",
                              LOCALE_ID_ENGLISH, siteTemplate,
                              true, false);

                  //Inherit navigation from parent site
                  newWeb.Navigation.UseShared = true;

                  newWeb.Update();

                  siteCreated = true;

                  webSite.AllowUnsafeUpdates = false;

              }

              webSite.Close();

          }
          catch (Exception ex)
          {
              this._lblErrMsg.Text = ex.Message.ToString();
          }

          return siteCreated;
      }
[tweetmeme only_single=”false”]
Advertisements

Got something to add?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s