A way to customize forms of a SharePoint list

Ref: http://vtimashkov.wordpress.com/2011/08/11/a-way-to-customize-forms-of-a-sharepoint-list/

Hi, everybody!

There are several approaches to customize NEW/EDIT/VIEW forms of a SharePoint list.

  • Firstly, you could use SharePoint designer and to customize needed form “in-place”. Such approach has obvious disadvantages – it is just not reusable.
  • Second, you could employee Rendering Templates. It is goes alone with SharePoint best practices, but it has many disadvantages too – like impossibility to insert your custom control into the middle of ListFormWebPart.
  • Etc, etc, etc.

I would like to show additional way – flexible enough to be considered when there is a need to customize NEW/EDIT/VIEW form of a list. The final result will look like in my case:

editform_1

As you can see in the form, in standard MultipleLookupField control there is additional server-side button.

As you know, each SharePoint list has several forms which are standard ASP.NET pages. The form to add new list item is “NewForm.aspx” page, the form to edit a list item is “EditForm.aspx” and the form to view a list item is “DispForm.aspx”.

In the terms of SharePoint API, they are SPForm class’s instances.

Each of these forms, has a Web Part Zone with name “Main”; inside this Web Part Zone there is only Web Part – ListFormWebPart. But it is possible to add you own Web Part implementing needed business functionality!

So my steps were:

1. I created a Web Part to be added on EDIT form of certain list. At the moment, the Web Part didn’t do anything useful – just stub code.

2. I added this custom Web Part to the main WebPartZone:

var form = list.Forms[PAGETYPE.PAGE_EDITFORM];
using
(var manager = web.GetLimitedWebPartManager(
       form.ServerRelativeUrl, PersonalizationScope.Shared))
{
    manager.AddWebPart(
new CustomWebPart(), "Main", 0);
}

3. In OnInit() event of the custom WebPart, I created additional button and added it near MultipleLookupField control:

protected override void OnInit(System.EventArgs e)
{
EnsureChildControls();
 var coll = SPContext.Current.FormContext.FieldControlCollection;

    var lookup = coll.Cast()
        .Where(x => x
is
MultipleLookupField)
        .Select(x => (MultipleLookupField)x)
        .FirstOrDefault();

   
if (lookup != null
)
    {
        var button =
new Button { Text = "Update Test Steps!"
};
        lookup.Parent.Controls.Add(button);
        button.Click += OnButtonClicked;
    }

   
base.OnInit(e);
}

4. Code retrieving fields on the form

var coll = SPContext.Current.FormContext.FieldControlCollection;

doesn’t find anything.

You need to call EnsureChildControls(); first before retrieving the fields from form.

5. In Click event of the button, I wrote needed business code modifying next field named “Test Steps” – but it doesn’t matter for the article.

Comments

Popular posts from this blog

Setup SharePoint 2010

Register CSS to SP Master Page