0

Inside my CSOM code, I can populate a "People or Group" field using User object, as follow:-

var technician = context.Site.RootWeb.EnsureUser(SQLitem.Technician);
context.ExecuteQuery();
NewUFSlistItem["UserFeedbackEngineer"] = technician;

while if i try to populate a "Managed Metadata" field using Term object, it will fail where the field will not have any value:-

TermSet ts = g.TermSets.GetByName(termsetname);
var customername = ts.Terms.GetByName(SQLitem.Account);
NewUFSlistItem["UserFeedbackCompanyName"] = customername;
context.ExecuteQuery();

so can anyone advice? why my second code sample will not populate the "Managed Metadata" field?

1 Answer 1

1

Managed Metadata field's value is TaxonomyFieldValue object while ts.Terms.GetByName will return Term object, they are not the same so won't work.

Try the code snippet like this, necessary to use SetFieldValueByValue method for setting taxonomy value:

static void Main(string[] args)
        {
            ClientContext ctx = new AuthenticationManager().GetACSAppOnlyContext(siteurl, appid, appsecret);
            ctx.Load(ctx.Web);
            ctx.ExecuteQuery();
            List list = ctx.Web.Lists.GetByTitle("TestList");
            ListItem item = list.GetItemById(1);
            
            ctx.Load(list);
            ctx.Load(item);
            ctx.ExecuteQuery();
            var taxonomySession = TaxonomySession.GetTaxonomySession(ctx);
            var termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            var termGroup = termStore.Groups.GetByName("People");
            termStore.CommitAll();
           
            var termSetCollection = termGroup.TermSets;
            var termSet = termSetCollection.GetByName("Job Title");
            var term = termSet.Terms.GetByName("Job2");
            ctx.Load(termGroup);
            ctx.Load(termSetCollection);
            ctx.Load(termSet);
            ctx.Load(term);
            ctx.ExecuteQuery();


            var clientRuntimeContext = item.Context;

            var field = list.Fields.GetByInternalNameOrTitle("TaxColumn"); //get the TaxonomyField Replace with yours
            var taxKeywordField = clientRuntimeContext.CastTo<TaxonomyField>(field);

            TaxonomyFieldValue termValue = new TaxonomyFieldValue();
           
            termValue.Label = term.Name;
            termValue.TermGuid = term.Id.ToString();
            termValue.WssId = -1;
            taxKeywordField.SetFieldValueByValue(item, termValue);

            taxKeywordField.Update();

            item.Update();
            ctx.Load(item);
            ctx.ExecuteQuery();




        }

How To Update The Taxonomy Field (Single Value Or Multiple Value) Using C# Patterns And Practices In SharePoint Office 365

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.