Wednesday, March 28, 2012

Custom Form for SharePoint List - FieldRenderingControl

I was working on a feature to enable bulk edit of list items..For this purpose, I wanted to develop a custom page in which all the list fields/columns should be rendered for the user to submit his data..

I thought I might have to build the form rendering logic myself..i.e, render a text box for text fields, drop down for choice fields etc..

But to my pleasant surprise, I chanced upon the "FieldRenderingControl" property of SPField, and it turned out that the complete rendering logic could be achieved with just few lines of code, as shown below:

SPList list = web.Lists[new Guid(listID)];
foreach (SPField field in list.Fields)
{
     BaseFieldControl 
renderingControl = field.FieldRenderingControl;
     
renderingControl .ID = field.Id.ToString().Replace("-", "_");
     
renderingControl .ControlMode = SPControlMode.New;
     
renderingControl .ListId = list.ID;
     
renderingControl .FieldName = field.InternalName;
     
renderingControl .RenderContext = SPContext.GetContext(HttpContext.Current, list.DefaultView.ID, list.ID,   web);

      myPanel.Controls.Add(renderingControl); //Add the control dynamically to a panel on page
}

This is it.. The above code will render all the fields in the list with the appropriate edit controls..

Note: You can use the following condition, within the above loop to hide read-only and non-editable fields:

if (field.ShowInNewForm.GetValueOrDefault(true) 
                                && field.Hidden == false 
                                && field.ReadOnlyField == false
                                && field.FieldRenderingControl != null
                                && (field.ShowInEditForm ?? false || field.CanBeDisplayedInEditForm))
{
      // Render the fields
}

No comments:

Post a Comment