Handling RichText Fields while saving the form content back to the SharePoint List Item is a little tricky.
If you try and save the value from this field in the following manner, you won’t see your text in the item.
if (objValue is Microsoft.SharePoint.Publishing.WebControls.RichTextField)
{
Microsoft.SharePoint.Publishing.WebControls.RichTextField richText = (objValue as Microsoft.SharePoint.Publishing.WebControls.RichTextField);
item[richText.Field.Title] = richText.Value;
}
….
item.Update();
Note: objValue is an object in the SPContext.Current.FormContext.FieldControlCollection. This collection contains all the values for all the fields that are rendered.
If you take a look at the Request.Forms collection you will notice a hidden field which has the actual value that you entered in the Rich textbox. This implies that the RichTextField renders a hidden field where it stores the value. If you want your code to be dynamic/efficient, you really don’t want to hard code the hidden fields name to access the value.
Digging a little deeper I found out that the value was not getting assigned to the public variable which is generally used to retrieve the value from the control.
The workaround:
Well, I love OOP, so I tend to find the solution in it.
public class MyRichTextField : RichTextField
{
public MyRichTextField () : base()
{ }
public string TxtValue
{
get
{
this.OnLoad(new EventArgs());
return this.textBox.Text;
}
}
}
I inherit from RichTextField, create a new property called TxtValue. In the accessor, you call the OnLoad function. This is because the OnLoad function assigns the value of the hidden field to the textBox. We use this so that we don’t have to go after the hidden input field. Once you have called the OnLoad, the value becomes available in the textbox.Text property and so now all we have to do is return the Text property from the TextBox control.
To use this workaround, while rendering our form, we have to check if the field is a RichTextField and if so, we have to render it using our class rather than the FormField class.
Now to access the value, we change the code a little.
if (objValue is MyRichTextField)
{
MyRichTextField richText = (objValue as MyRichTextField);
item[richText.Field.Title] = richText.TxtValue;
}
….
item.Update();
Now the form will save the RichText fields also.