Udostępnij za pośrednictwem


How to set multiple default value(s) for TaxonomyField

Below is the code to set multiple default values for a TaxonomyField.  There was a requirement to create TaxonomyField programmatically and set multiple default values...I looked at some blogs and articles for solution but none of them worked out for me and here is the solution

Later on I realised  that TaxonomyField inherits from SPFieldLookup

public class TaxonomyField : SPFieldLookup (Ref : https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.taxonomyfield.aspx#Y228

Value to be set to field to be formed in below format

For multiple value : id;#name|guid;#id;#name|guid here “id” is nothing but the ID column value in the TaxonomyHiddenList(/Lists/TaxonomyHiddenList)

and  code is

var multipleterms = new List<string>();

for(int i = 0; i < multiplevalues.Count; i++){TermCollection terms = termSet.GetTerms(multiplevalues[i].ToString().Trim(), true);

if (terms.Count >= 1){

int[] ids = TaxonomyField.GetWssIdsOfTerm(listfield.ParentList.ParentWeb.Site, termSet.TermStore.Id, termSet.Id, terms[0].Id, true, 1);

int WssId = -1;

if (ids.Length >= 1)

WssId = ids[0];

multipleterms.Add(WssId + ";#" + terms[0].Labels[0].Value + TaxonomyField.TaxonomyGuidLabelDelimiter + terms[0].Id.ToString());

}

if(multipleterms.Count >= 1){

string allvalues = String.Join(";#", multipleterms.ToArray());

log.WriteErrorTrace("Default(multiple) value: " + allvalues + " for the column: " + listfield.InternalName, "", false);

SPFieldLookup lookup = (SPFieldLookup)listfield;

lookup.DefaultValue = allvalues;

lookup.Update();

}