1

How can I create site column with "Image with formatting and constraints for publishing" content type programmatically in FeatureActivated method?

I need to add this site column to the List

1 Answer 1

1

First you need to add a Site Column, following function will help:

public void CreateSiteColumn(SPWeb site, string columnXml, Guid columnGuid)
{
    if (site.AvailableFields.Contains(columnGuid) == false)
    {
            site.Fields.AddFieldAsXml(columnXml);
            site.Update();
    }
}

Than add the column to content type:

public void AddColumnToContentType(SPWeb site, string contentTypeName, Guid columnGuid, string columnTitle, bool isRequired)
{
    var contentType = site.ContentTypes[contentTypeName];
    if (contentType != null)
    {
        var isFieldAdded = contentType.FieldLinks.Cast<SPFieldLink>().Any(fieldRef => fieldRef.Id == columnGuid);

        if (!isFieldAdded)
        {
             var field = site.Fields[columnGuid];
             var fieldLink = new SPFieldLink(field);
             fieldLink.Required = isRequired;
             fieldLink.DisplayName = columnTitle;
             contentType.FieldLinks.Add(fieldLink);
             contentType.Update(true);
        }
    }
}

Than adding content type to the List

SPList list = site.Lists.TryGetList("List Title");
SPContentType contentType = site.ContentTypes["Content Type Title"];
list.ContentTypes.Add(contentType);

Using the above to add Image column

var fieldGuid = new Guid("guid-here");
var fieldXml = string.Format("<Field ID=\"{0}\" Type=\"Image\" Name=\"FieldName\" Description=\"\" DisplayName=\"Field Display Name\" StaticName=\"FieldName\" Group=\"Site Column Group\" Hidden=\"FALSE\" Required=\"FALSE\" RichText=\"TRUE\" RichTextMode=\"ThemeHtml\"></Field>", fieldGuid.ToString("B"));

fieldsManager.CreateSiteColumn(site, fieldXml, fieldGuid);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.