i had create a list programmatically on Feature_activated. Now i want to add a new Field to my list with an XML File on UpgradeActions from the Feature. I know the solution for add a Field with C#.
regards
gidion
i had create a list programmatically on Feature_activated. Now i want to add a new Field to my list with an XML File on UpgradeActions from the Feature. I know the solution for add a Field with C#.
regards
gidion
I implemented similar behavior some time ago, I used xml file with following structure:
<?xml version="1.0" encoding="utf-8" ?>
<Fields ListUrl="Lists/Test">
<Add>
<Field ID="{1174073D-CD08-4A8A-A70E-5199200E04AC}"
Name="TestField"
Required="TRUE"
Indexed="TRUE"
MaxLength="255"
Type="Text"
DisplayName="TestField" />
</Add>
</Fields>
To deserialize xml file I used following class:
[Serializable]
[XmlRoot("Fields")]
public class FieldsConfiguration
{
[XmlAttribute]
public string ListUrl { get; set; }
[XmlArrayItem(typeof(Field))]
public List<Field> Add { get; set; }
}
public class Field
{
[XmlAttribute]
public string ID { get; set; }
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Type { get; set; }
[XmlAttribute]
public string List { get; set; }
}
I added xml file to feature definition. To get xml file name in my feature receiver I used code:
string fileName = Path.Combine(properties.Definition.RootDirectory, "FileName.xml");
Method that applies changes to list:
/// <summary>
/// Method adds fields to list from xml file.
/// </summary>
/// <param name="config">Deserialized xml file</param>
/// <param name="doc">XmlDocument of xml file</param>
/// <param name="web">Current web</param>
/// <param name="list">Current list</param>
protected void AddFieldsFromFile(FieldsConfiguration config, XmlDocument doc, SPWeb web, SPList list)
{
foreach (var field in config.Add)
{
//check if field is already exist
if (list.Fields.ContainsField(field.Name))
continue;
//get field schema from xml
var fieldSchema = doc.SelectSingleNode(string.Format("/Fields/Add/Field[@Name='{0}']", field.Name));
if (fieldSchema == null || fieldSchema.Attributes == null)
continue;
//hack for Lookup fields
if(!string.IsNullOrEmpty(field.List))
{
var lookupList = web.GetListNoThrow(field.List);
if (lookupList == null)
continue;
fieldSchema.Attributes["List"].Value = lookupList.ID.ToString();
}
list.Fields.AddFieldAsXml(fieldSchema.OuterXml, false, SPAddFieldOptions.AddFieldInternalNameHint);
list.Update();
}
}
Provided code supports all field types except Taxonomy fields.