Friday, November 8, 2013

SPFieldMultiLineText.RichText = true does not update

Interesting thing happened to me today, and I guess I’ve seen it happening at least 10 times in the past but I keep forgetting what the solution was every time I see it again.

Say you create a multiple lines of text field in a list (Note field type of class SPFieldMultiLineText).

Now, you want to make sure it supports HTML but you want to do it via code.

The simple thing to do appears to be:

SPFieldMultiLineText myField = …;
myField.RichText = true;
myField.RichTextMode = FullHtml;

Right? Wrong!

Run that code again, you will find that the RichText and RichTextMode properties were not modified.

Even calling list.Update() doesn’t help.

Apparently, the simple solution is to edit and set the myField.SchemaXml property directly, without calling myField.Update() after. Simple, yet annoying.

Here is an example of a working code:

XDocument xSchema = XDocument.Parse(field.SchemaXml);
var xField = xSchema.Root;
bool needUpdate = false;
var xRichText = xField.Attribute("RichText");
if (xRichText == null)
    needUpdate = true;
    xField.SetAttributeValue("RichText", "TRUE");
else if(xRichText.Value != "TRUE")
    needUpdate = true;
var xRichTextMode = xField.Attribute("RichTextMode");
if (xRichTextMode == null)
    needUpdate = true;
    xField.SetAttributeValue("RichTextMode", "FullHtml");
else if (xRichTextMode.Value != "FullHtml")
    needUpdate = true;
if( needUpdate )
    field.SchemaXml = xSchema.ToString();

1 comment:

Badr Mouslik said...

Super ! You´re the best ! you save my day :)