BitterCoder's Wiki

Edit

Add links

This hack is aimed at adding additional "links" to a custom web part which is generating a custom edit form for a SharePoint list... the idea is that you could say have a set of link(s) above/below your edit form, and when user clicks on the link, it saves the form (or halts the save, if their are validation errors) and then takes some action once the save is complete i.e. redirecting.

In my case I used this to navigate to custom pages for launching certain workflows that were only valid for certain states of the List Item.

Edit

The setup

First off you need to generate the links, which can be done this way - it's assumed you've already stored the SaveButton instance for the form and a HiddenField instance's before generating the links on-click event.

Here is the code:



// need to be setup, before attempting to render the link's attribute.. HiddenField _someField; // were we are recording some additional state SaveButton _saveButton;

string someValue; // the value we want to assign to the hidden field, when this link is clicked.

// assign the on-click handler for a link HtmlAnchor link = new HtmlAnchor(); link.Attributes["onclick"] = _someField.UniqueID + @".value = """ + someValue + "\";" + @"if (!PreSaveItem()) return false;" + @"WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(""" + _saveButton.UniqueID + @"$ctl00$diidIOSaveItem"", """", true, """", """", false, true))";

link.HRef = "#";



Edit

Handling the save

While generating the child controls for your web part, you can attach to the OnSaveHandler... this will be called when the SaveButton is clicked, allowing us to take control of persistence.



if (ControlMode == SPControlMode.Edit) { SPContext.Current.FormContext.OnSaveHandler += delegate { SaveItemAndRedirectSomewhere(); }; }



We use a static method on the SaveButton control to perform the actual save, and then based on the value held in the hidden field we decide if a custom action needs to be taken, or if we just redirect back to the source / default view.



private void SaveItemAndRedirectSomewhere() { SaveButton.SaveItem(SPContext.Current, false, "");

if (!string.IsNullOrEmpty(_someField.Value)) { // redirect somewhere special, based on the _someField's value. } else { // the save button was clicked (rather then one our custom links) SaveButton.SaveItem(SPContext.Current, false, ""); string source = Page.Request["Source"] ?? List.DefaultViewUrl; SPUtility.Redirect(source, SPRedirectFlags.Default, Context); } }

ScrewTurn Wiki version 2.0.2. Some of the icons created by FamFamFam.