Create custom NewForm programmatically

19/06/2015 16:58


public static string CreateNewForm(SPList list)
{
 SPFolder rootFolder = list.RootFolder;
 SPWeb web = list.ParentWeb;

 string newFormUrl = string.Format("{0}/{1}/NewFormCustom.aspx", web.ServerRelativeUrl, rootFolder.Url);
 var newForm = web.GetFile(newFormUrl);
 if (newForm != null && newForm.Exists)
  newForm.Delete();   // delete & recreate our new form

 /* create a new NewForm */
 newForm = rootFolder.Files.Add(newFormUrl, SPTemplateFileType.FormPage);
 SPLimitedWebPartManager wpm = newForm.GetLimitedWebPartManager(PersonalizationScope.Shared);
 /* add a listformwebpart instance, configure it for the list */
 ListFormWebPart webpart = new ListFormWebPart
 {
  ListId = list.ID,
  ListName = list.ID.ToString("B").ToUpper(),
  PageType = PAGETYPE.PAGE_NEWFORM,
  Title = list.Title,
  Description = list.Description,
  CatalogIconImageUrl = list.ImageUrl,
  TitleUrl = list.DefaultViewUrl,
  //TemplateName = "SomeCustomRenderingTemplate"
 };
 wpm.AddWebPart(webpart, "Main", 0);

 //Create list items preview - our customization
 XsltListViewWebPart preview = new XsltListViewWebPart();
 preview.Title = "My list items preview";
 preview.ListName = list.ID.ToString("B");
 //preview.ChromeType = PartChromeType.None;

 wpm.AddWebPart(preview, "Main", 9);
 return newFormUrl;
}


Call

 string newFormUrl = CreateNewForm(list);
list.DefaultNewFormUrl = newFormUrl;
list.Update();