Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create field in SharePoint programmatically using CSOM (Not with XML)

Is it possible to create fields in SharePoint with CSOM, not using XML?

I've seen many examples using XML, but none with just setting properties for the field programmatically?

fields.Add(new **FieldCreationInformation** {
    InternalName = "Test",
   etc..
});
like image 468
Robin Avatar asked Feb 08 '23 02:02

Robin


1 Answers

That's doable, in the following example is introduced a FieldCreationInformation class:

[XmlRoot("Field")]
public class FieldCreationInformation
{
    [XmlAttribute("ID")]
    public Guid Id { get; set; }

    [XmlAttribute()]
    public string DisplayName { get; set; }

    [XmlAttribute("Name")]
    public string InternalName { get; set; }

    [XmlIgnore()]
    public bool AddToDefaultView { get; set; }


    //public IEnumerable<KeyValuePair<string, string>> AdditionalAttributes { get; set; }

    [XmlAttribute("Type")]
    public FieldType FieldType { get; set; }

    [XmlAttribute()]
    public string Group { get; set; }

    [XmlAttribute()]
    public bool Required { get; set; }


    public string ToXml()
    {
        var serializer = new XmlSerializer(GetType());
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

        using (var stream = new StringWriter())
        using (var writer = XmlWriter.Create(stream, settings))
        {
            serializer.Serialize(writer, this, emptyNamepsaces);
            return stream.ToString();
        }
    }



    public FieldCreationInformation()
    {
        Id = Guid.NewGuid();
    }

}

and then extension method for creating a new field:

public static class FieldCollectionExtensions
{
    public static Field Add(this FieldCollection fields, FieldCreationInformation info)
    {
        var fieldSchema = info.ToXml();
        return fields.AddFieldAsXml(fieldSchema, info.AddToDefaultView, AddFieldOptions.AddFieldToDefaultView);
    }
}

Usage

var fieldInfo = new FieldCreationInformation();
fieldInfo.FieldType = FieldType.Geolocation;
fieldInfo.InternalName = "ContactsLocation";
fieldInfo.DisplayName = "Contacts Location";
ctx.Site.RootWeb.Fields.Add(fieldInfo);
ctx.ExecuteQuery();
like image 168
Vadim Gremyachev Avatar answered Apr 09 '23 20:04

Vadim Gremyachev