Saturday, October 27, 2007

Creating a new form in a list by copying an existing form (in code)

To copy an existing form in a WSS list, and to add a new content editor web part to that list, use the SPFile class (not the SPForm collection of the list):

//Copy the NewForm.aspx to NewForm_new.aspx
string formPath = "Lists/ClientTest/NewForm.aspx";
string newformPath = formPath.Replace(".aspx", "_new.aspx");
SPFile form = web.GetFile(formPath);
form.CopyTo(newformPath, false);

//Get a reference to the new form, and create a new content editor web part containing onload JavaScript
SPFile copiedForm = web.GetFile(newformPath);
SPLimitedWebPartManager wpManager = copiedForm.GetLimitedWebPartManager(PersonalizationScope.Shared);

//Create the new web part
ContentEditorWebPart wpContent = new ContentEditorWebPart();
XmlDocument xmlContent = new XmlDocument();
XmlElement el = xmlContent.CreateElement("El");
el.InnerText = "";
wpContent.Content = el;
wpManager.AddWebPart(wpContent, "Main", 0);

The JavaScript adds an onload handler to the page, allowing for behaviours to modify the content of the standard list form for example.

3 comments:

Filipe de Campos Cavalcante said...

Hi everyone. I like a lot your blog. Really. I just start to work with sharepoint and seaching for some stuff on the web, i found this blog... lol .. and i already added to my del.icio.us! =D

I have one question. About other subject. If you can answer i'll be happy. How can i get an image gallery by C#? I've tried using SPList, but i got an error...

Tks anyway.

(sorry by my english =D)

Filipe de Campos Cavalcante said...

sorry. My email is: filipe.cavalcante@gmail.com

tks again

whats.to.learn.today said...

Glad you find my scribblings useful!

The SPPictureLibrary class is the one that you need. Have a look at SPPictureLibrary in MSDN for details.