locked
How to programmatically add value in metadata column ? RRS feed

  • Question

  • Hello,

    I have one list with metadata column.I need to insert data in list programmatically.

    I have one value lets say "myTermStore" which is in "MyCatagory" term set under "MyGroup" term group in managed metadata service.

    "myTermStore" value i want to add in my custom list.

    I tried following code lines

     SPListItem item = list.Items.Add();
    SPField spfld = item.Fields.TryGetFieldByStaticName("MyColumn");
    TaxonomyField field = (TaxonomyField)spfld;
    TaxonomyFieldValue txFieldValue = new TaxonomyFieldValue(field);
                                   txFieldValue.PopulateFromLabelGuidPair("myTermStore");
    item[field.Id] = txFieldValue;
    item[field.TextField] = "myTermStore";/
    however its not storing "myTermStore" value in "MyColumn" field :(


    Can anyone please let me know how can I achieve this programmatically ?


    Dipti Chhatrapati

    Thursday, June 7, 2012 9:38 AM

Answers

  • Finally my problem solved with following code lines

     TaxonomySession session = new TaxonomySession(site);
                               TermStore mytermstore = session.DefaultKeywordsTermStore;
                               List<Guid> itemsToAdd = new List<Guid>();
    
                               foreach (Group gr in mytermstore.Groups)
                               {
                                   if (gr.Name == "MyGroup")
                                   {
                                       TermSet termset = gr.TermSets["MyTermSet"];
                                       TermCollection terms = termset.Terms;
                                       foreach (Term term in terms)
                                       {
                                           if (term.Name == "MyTerm")
                                           {
                                               itemsToAdd.Add(term.Id);
                                           }
                                       }
                                   }
                               }
    
                               TaxonomyField taxfld = listHousekeepingTasks.Fields["MyField"] as TaxonomyField;
                               Guid[] ids = itemsToAdd.ToArray();
                               TermCollection oTerms = session.GetTerms(ids);
                               taxfld.SetFieldValue(item, oTerms);
                               taxfld.Update();

    Hope this helps to other....


    Dipti Chhatrapati

    Monday, June 11, 2012 8:42 AM

All replies

  • Think you need to add this line at the end:

    item.Update(); 


    Kind Regards Bjoern
    Blog

    Thursday, June 7, 2012 9:44 AM
  • I am sorry Bjoern But that line I have already added in my code only not considered in this post.even thought its not working as expected :-| !!

    and so complete code will be as follow !!

    SPListItem item = list.Items.Add(); SPField spfld = item.Fields.TryGetFieldByStaticName("MyColumn"); TaxonomyField field = (TaxonomyField)spfld; TaxonomyFieldValue txFieldValue = new TaxonomyFieldValue(field);

    txFieldValue.PopulateFromLabelGuidPair("myTermStore"); item[field.Id] = txFieldValue; item[field.TextField] = "myTermStore"; item.Update();



    Dipti Chhatrapati


    Thursday, June 7, 2012 9:47 AM
  • Hello Dipti,

    Try with this code..if it helps.

    TaxonomySession session = new TaxonomySession([Your SPSite]);
    	
    	SPListItem item = [Your SPListItem]
    	TaxonomyField tf = item.Fields[item.Fields.GetFieldByInternalName([Your Taxonomy Column]).Id] as TaxonomyField;
    
    	TermStore termStore = session.TermStores[0]; 
    	Group group = termStore.Groups[0];
    	TermSet termSet = null;
    foreach (TermSet termSet in termsets)
    {
        if (termSet.Name == termSetName)
        {
            termSet = termSet;
            break;
        }
    } TermCollection tc = ts.GetTerms(value, false); if (tc.Count == 0) { Term term = ts.CreateTerm(value, 1033); termStore.CommitAll(); tc = ts.GetTerms(value, false); } Term t = tc[0]; Guid id = t.Id; tf.SetFieldValue(item, t); item.Update();

    -Saumil


    Thursday, June 7, 2012 9:52 AM
  • Hi saumil can you please send me GetTermSet(group.TermSets, taxCol) Method code ?

    as I get following error mentioned in below screen :

    Thanks for helping !!!


    Dipti Chhatrapati


    Thursday, June 7, 2012 10:05 AM
  • got it need to use as "termStore.GetTermSet" then it will not display error message.

    however above  method only takes guid as mentioned in below screen:


    Please let me know how can I get guid of termset programmatically ?

    Thanks for your time.

    Dipti Chhatrapati



    Thursday, June 7, 2012 10:21 AM
  • Hey,

    var termStore = session.DefaultKeywordsTermStore;
                    var group = termStore.Groups.GetByName(termGroup);
                    var termSet = group.TermSets.GetByName(termSetName);
                    TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField;
                    // connect the field to the specified term
                    field.SspId = termSet.TermStore.Id;
                    field.TermSetId = termSet.Id;
                    field.AllowMultipleValues = true;
                    field.TargetTemplate = string.Empty;
                    field.AnchorId = Guid.Empty;
                    field.Update(true);
    Hope this helps :)


    "The Only Way To Get Smarter Is By Playing A Smarter Opponent"

    Thursday, June 7, 2012 10:42 AM
  • Hey,

    var termStore = session.DefaultKeywordsTermStore;
                    var group = termStore.Groups.GetByName(termGroup);
                    var termSet = group.TermSets.GetByName(termSetName);
                    TaxonomyField field = site.RootWeb.Fields[fieldId] as TaxonomyField;
                    // connect the field to the specified term
                    field.SspId = termSet.TermStore.Id;
                    field.TermSetId = termSet.Id;
                    field.AllowMultipleValues = true;
                    field.TargetTemplate = string.Empty;
                    field.AnchorId = Guid.Empty;
                    field.Update(true);
    Let me know if u have any queries :)


    "The Only Way To Get Smarter Is By Playing A Smarter Opponent"

    Thursday, June 7, 2012 10:42 AM
  • I have modified the code please check. [It is not fully tested with application but give you an idea.]

    -Saumil
    Thursday, June 7, 2012 11:06 AM
  • Hello,

    I have tried below code as per the sugession, but again its not adding term value in managed metadata column :(

    SPListItem item = listHousekeepingTasks.Items.Add();
    TaxonomySession taxSession = new TaxonomySession(site);   
    TermStore termStore  = taxSession.TermStores["Managed Metadata Service"];
    Group storeGroup = termStore.Groups["My Term Group"];
    TermSet termSet  = storeGroup.TermSets["My Term Set"];
    Term term  = termSet.Terms["My Term"];
    SPField spfld = item.Fields.TryGetFieldByStaticName(myfield);
    TaxonomyField field = (TaxonomyField)spfld;
    field.SspId = termSet.TermStore.Id;
    field.TermSetId = termSet.Id;
    field.AllowMultipleValues = true;
    field.TargetTemplate = string.Empty;
    field.AnchorId = Guid.Empty;
    field.Update(true);
    item.Update();

    can you please let me know where I am wrong !!!! in above code.

    Thank you very much for your time !!!


    Dipti Chhatrapati


    Friday, June 8, 2012 5:55 AM
  • Hi Dipti,

    Please try the below code and change as per your requirement 

    I got the similar task long back & hope it will help you.

    Let me know if you have any queries.

      SPListItem List = web.Lists["DocLibName"].AddItem();

                                    TaxonomyField tagsField = (TaxonomyField)List.Fields["TaxonomyField"];

                                    TaxonomySession session = new TaxonomySession(siteColl);

                                    TermStore termStore = session.TermStores[tagsField.SspId];

                                    TermSet termSet = termStore.GetTermSet(tagsField.TermSetId);

                                    foreach (Term termItem in termSet.GetAllTerms())
                                    {
                                        if (termItem.Name == lstItem["MetaTag"].ToString())
                                        {

                                            int lcid = CultureInfo.CurrentCulture.LCID;

                                            string termGuid = string.Concat(termItem.GetDefaultLabel(lcid), TaxonomyField.TaxonomyGuidLabelDelimiter, termItem.Id);

                                            TaxonomyFieldValueCollection tagsValues = new TaxonomyFieldValueCollection(tagsField);

                                            tagsValues.PopulateFromLabelGuidPairs(termGuid);

                                            SPFolder myFolder = web.GetFolder("DocLibName");

                                            Hashtable metaDataTable = new Hashtable();

                                            web.AllowUnsafeUpdates = true;


                                            metaDataTable.Add("TaxonomyField", tagsValues.ElementAt(0).ValidatedString);

                                            SPFile myFile = myFolder.Files.Add(fileName, fileStream, metaDataTable, true);
                                            SPListItem lstDocLibItem = myFile.Item;
                                            lstDocLibItem["Title"] = lstItem["Title"];
                                            lstDocLibItem.Update();

                                            myFolder.Update();                                   

                                            Console.WriteLine("File Uploaded: " + fileName);
                                        }
                                    }

    Regards,

    Kumar




    • Edited by Kumar9999 Friday, June 8, 2012 2:06 PM
    Friday, June 8, 2012 2:03 PM
  • hi Kumar ,

    Thanks for the reply.I have also tried your code, howevrer I am getting error on below line of code

    string termGuid = string.Concat(termItem.GetDefaultLabel(lcid), TaxonomyField.TaxonomyGuidLabelDelimiter, termItem.Id);

    Error message is as below:

    "Specified argument was out of the range of valid values.\r\nParameter name: lcid"

    Please let me know what I need to change.It will be great help to me.

    Thanks,


    Dipti Chhatrapati

    Monday, June 11, 2012 7:30 AM
  • Finally my problem solved with following code lines

     TaxonomySession session = new TaxonomySession(site);
                               TermStore mytermstore = session.DefaultKeywordsTermStore;
                               List<Guid> itemsToAdd = new List<Guid>();
    
                               foreach (Group gr in mytermstore.Groups)
                               {
                                   if (gr.Name == "MyGroup")
                                   {
                                       TermSet termset = gr.TermSets["MyTermSet"];
                                       TermCollection terms = termset.Terms;
                                       foreach (Term term in terms)
                                       {
                                           if (term.Name == "MyTerm")
                                           {
                                               itemsToAdd.Add(term.Id);
                                           }
                                       }
                                   }
                               }
    
                               TaxonomyField taxfld = listHousekeepingTasks.Fields["MyField"] as TaxonomyField;
                               Guid[] ids = itemsToAdd.ToArray();
                               TermCollection oTerms = session.GetTerms(ids);
                               taxfld.SetFieldValue(item, oTerms);
                               taxfld.Update();

    Hope this helps to other....


    Dipti Chhatrapati

    Monday, June 11, 2012 8:42 AM
  • item.Update() is necessary in this case !
    Thursday, April 3, 2014 8:25 AM
  • If the destination column is set to accept only single value, it will throw an error, here is the code for this case.

    taxfld.SetFieldValue(item, oTerms[0]);

    Small modification did the trick.

    Sunday, March 29, 2015 8:46 AM