βOn a recent project, I am using a custom web part to create and modify items in a list. I wanted to highlight the required fields, to let the user know what fields had to be completed before submitting. The standard SharePoint EditForm and NewForm display a red asterisk (*), but I wanted something less subtle.
What I found was, highlighting HtmlSelect controls and FormField controls that use TextBoxes are fairly straightforward, but the FormField PeopleEditor was more problematic.
To highlight a HtmlSelect control:
- Define a module-level constant to define the background color (I used a subdued red):
private const string REQUIRED_FIELD = "#FF9D9D";
- Create a function to determine if the current field is required (FieldName is the field the control manages):
private bool IsRequired(string FieldName)
{
return mobjItem.Fields.GetFieldByInternalName(FieldName).Required;
}
Note: I use GetFieldByInternalName in case the title of a field is different from the Internal Name. See Internal Name for further details.
- At the point where you add the HtmlSelect control, change the style:
if (IsRequired(string FieldName))
MyControl.Style.Add("background-color", REQUIRED_FIELD);
To highlight a FormField control, you have to isolate the TextBox control. There are two support methods for this purpose:
- First, determine if the FormField given is a TextField control:
private bool IsTextField(Control MyControl)
{
if (MyControl.GetType().Name != "FormField")
return false;
return (MyControl.Controls[0].GetType().Name == "TextField");
}
β
- Next, locate the TextBox control within the FormField. This function is recursive, to navigate through every control collection until a TextBox is found:
protected bool GetTextBox(Control MyControl, out TextBox MyTextBox)
{
if (MyControl.GetType().Name == "TextBox")
{
MyTextBox = (TextBox)MyControl;
return true;
}
try
{
foreach (Control objChild in MyControl.Controls)
if (GetTextBox(objChild, out MyTextBox))
return true;
}
catch
{ }
MyTextBox = null;
return false;
}
- Now the complete function that assigns the field to the FormField, so you can see where the style is changed:
protected void AddControl(FormField MyControl, string FieldName)
{
try
{
TextBox MyTextBox;
PeopleEditor MyEditor;
MyControl.FieldName = FieldName;
MyControl.ListId = mobjItem.ParentList.ID;
MyControl.ItemId = mobjItem.ID;
// Check for null values in Display mode.
if (MyControl.ItemFieldValue != null &&
MyControl.ItemFieldValue.ToString().Contains(" field value."))
return;
if (IsTextField(MyControl))
{
if (GetTextBox(MyControl, out MyTextBox))
{
MyTextBox.Width = 200;
if (IsRequired(FieldName))
MyTextBox.Style.Add("background-color", REQUIRED_FIELD);
}
}
else if (IsUserField(MyControl))
{
if (GetPeopleEditor(MyControl, out MyEditor))
{
MyEditor.Width = 280;
if (IsRequired(FieldName))
MyEditor.Attributes.Add("required", "true");
}
}
}
catch
{ }
AddLabelAndControl(MyControl, FieldName);
}