Creating a Publishing Field Declaratively and Programmatically in SharePoint

I recently came across a task in SharePoint that nearly drove me insane. I was creating a publishing…

I recently came across a task in SharePoint that nearly drove me insane. I was creating a publishing layout template and I needed to add some “Publishing HTML” fields so the user would have full editing control inside that editable field. Doing this declaratively using a SharePoint feature in Visual Studio is simple enough – some example code is below:

<?xml version="1.0" encoding="utf-8"?>
  <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Field ID="{your-guid-here}" Type="HTML" RichText="TRUE" RichTextMode="FullHTML" Name="YourInternalName" DisplayName="Your Display Name" Group="YourGroupName"></Field>
  </Elements>

Be sure to use the type “HTML”. This type is not included on many of the lists that describe all of the types in SharePoint, because a lot of those only cover SharePoint foundation and this is part of the Publishing Infrastructure of SharePoint Server. Remember, you can generate your own guids inside of Visual Studio under “Tools”. Also, remember to not include spaces in your internal name for cleanliness (spaces get converted to %20 behind the scenes).

The harder part is how to create this programmmatically. I haven’t tried this in SharePoint 2013, but 2010 seems to have a bug that does not let you instantiate the HTMLField class correctly, which limits your ability to use the straight server object model. Every time I attempted this I received the dreaded “column failed to install correctly error. Avoid this.

Instead, try creating the column programmatically using the AddFieldAsXML method of the SPFieldsCollection class, and then passing in the declarative XML that we know works. Make sure to escape your quotes, as seen below.

Creating a SharePoint Publishing HTML column programmatically

using (SPWeb web = yourSiteCollection.RootWeb)
{
    web.Fields.AddFieldAsXml("<Field ID=\"{your-guid-here}\" Type=\"HTML\" RichText=\"TRUE\" RichTextMode=\"FullHTML\" Name=\"YourInternalName\" DisplayName=\"Your Display Name\" Group=\"Your Group Name\"></Field>");
}

This is a bit of a work around but it does work, and it’s not a hack as it’s using built in functionality. If anyone knows why using the straight object model always seems to fail, please leave a comment. Until then, these are both great ways to add the powerful Publishing HTML columns to your site.

0 Shares:
You May Also Like