Friday, April 18, 2008

Rendering list field control manually

Recently I had many customer requesting me to do several development that all required one thing:

Render a field control manually inside my web part.

One development was creating a SharePoint list aggregator. This (upcoming new product on our site soon) web part will get data from several lists and aggregate them into one view.
What we had to support is rendering each item with all of it's fields, even custom field types.

Another development, was to create a web part (also, should be published as a new product on our site soon) that connects to a list, and allows the user to create or edit items in the list - only editing will be done one field at a time using a wizard-like mechanism, where every field you fill will save your changes and will move you to the next field (I called it ItemEditorPlus :) ).

In both cases I needed to load a list item, and display one or more of it's fields using the designated field control - in display mode, or in edit mode, it doesn't matter.

Well, I found this to be a bit tricky to do since after getting the correct field control for the current field type, I found out that each field type acts different when rendering it.

Apart from that, I found 2 methods of doing that. One using a CompositeField control (the easiest way) and the other interrogating the SPField itself.

Using the CompositeField control

This is rather easy, all you need to do is:
1. Get a reference to the SPList and SPListItemyou want to edit
2. Add a CompositeField control to your this.controls collection
3. Set the ListId, ItemId and FieldName properties of the CompositeField control
4. Done!

Here is an example of what should be in your CreateChildControls method:

FieldControlNextField = new CompositeField();
FieldControlNextField.EnableViewState = false;
FieldControlNextField.ListId = list.CurrentList.ID;
FieldControlNextField.FieldName = GetNextFieldName();
FieldControlNextField.ID = "FieldControlNextField";
if (IsEditingMode() )
FieldControlNextField.ControlMode = SPControlMode.Edit;
FieldControlNextField.ItemId = this.CurrentItemID;
FieldControlNextField.ControlMode = SPControlMode.New;

So, that done I was able to render just about any field I testes, including our Rating field type and Tagging field type (which are very composite fields to render, I can assure you).

On the other manual method of rendering a field I will take the time to complete my investigation and publish on a later post. It is possible since I have it working, but it just seems too complicated to do so I think I am missing something...

Well, anyways - This is my first post since I moved to Ontario, Canada... Finally got my fast Internet installed at home - so if any of you emailed me and didn't get a response - I'm getting there!

Happy weekend all,
Shai Petel.