1

We are having trouble setting the default value of a metadata column in a SharePoint Online environment. Both ways of setting the field default (REST / JSOM) fail for the same reason: new documents added to the library do not set the value of the column.

Field configuration: field config

When document is uploaded: document uploaded without field default value

We have tried to perform the operation both through the REST API and JSOM. The code of the two approaches was:

REST

$.ajax({
    url: "/_api/web/lists/getbytitle('TestLib')/fields/getbytitle('TestMMField')",
    type: "POST",
    data: JSON.stringify({
        "__metadata": {
            type: "SP.Taxonomy.TaxonomyField"
        },
        DefaultValue: "-1;#TestTerm|cb195b78-66e2-4ac8-8982-f835844ba508"
    }),
    headers: {
        Accept: "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
        "IF-MATCH": "*",
        "X-Http-Method": "MERGE"
    },
    success: function(data) {
        alert("Updated!")
    },
    error: function(data) {
        alert(data.statusText);
    }
});

JSOM:

RegisterSod('sp.js', '/_layouts/15/sp.js');
RegisterSod("SP.Taxonomy.js", '/_layouts/15/SP.Taxonomy.js');
RegisterSodDep("SP.Taxonomy.js", "SP.js");

EnsureScriptFunc("SP.Taxonomy.js", "SP.Taxonomy", function() {
    var context = new SP.ClientContext();
    var lcid = _spPageContextInfo.currentLanguage;
    var session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
    var store = session.getDefaultSiteCollectionTermStore();

    var group = store.get_groups().getByName("TestGroup");
    var set = group.get_termSets().getByName("TestSet");
    var term = set.get_terms().getByName("TestTerm");

    var list = context.get_web().get_lists().getByTitle("TestLib");
    var field = list.get_fields().getByInternalNameOrTitle("TestMMField");
    var fieldTax = context.castTo(field, SP.Taxonomy.TaxonomyField);

    context.load(term);
    context.load(fieldTax);

    context.executeQueryAsync(function(a, b, c) {
        fieldTax.set_defaultValue("-1;#" + term.get_name() + "|" + term.get_id().toString());
        fieldTax.update();

        context.executeQueryAsync(function(a, b, c) {
            console.log("updated");
        }, function(a, b, c) {
            console.log("error updating field");
        });
    }, function(a, b, c) {
        console.log("error getting data");
    });
});

After investigating on our own, it seems that the default value cannot be set with the "-1; #", instead it must have the WSSID of the taxonomy term to be assigned. The problem is that we couldn’t found any JSOM / REST APIs that let you find it out. The only way we came up with it (WSSID), was by querying the "TaxonomyHiddenList" element Id asociated with the term Id (Guid). By the way, the TaxonomyHiddenList only has used terms.

function GetTermWSSID(termId, callback) {
    var context = new SP.ClientContext();
    var taxList = context.get_web().get_lists().getByTitle("TaxonomyHiddenList");
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='IdForTerm' /><Value Type='Text'>" + termId + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>");

    var items = taxList.getItems(camlQuery);

    context.load(items);

    context.executeQueryAsync(function() {
        var listItemEnumerator = items.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var item = listItemEnumerator.get_current();
            callback(item.get_id());
            break;
        }
    }, function() {
        alert("No term WSSID");
    });
}

In our case, we can not apply this solution since it is possible that the term has not been used previously in the site collection, so it wouldn't be present in the "TaxonomyHiddenList".

Is there any alternative/workaround? Any help is appreciated.

0

i had a similar issue, how i solved was retriving all the terms of a term group with JSOM, in this case i have to know the TermGroup IDs and then it will return all the terms contained in the TermGroup.

you need to add the refernce of the sp.taxonomy.js script in order to work with this.

Check the javascript taxonomy reference:
https://msdn.microsoft.com/en-us/library/office/jj857114.aspx

Get terms contained in TermGoups.

in this case im getting 4 termGroups terms

    function GetTermsId(termSetGroup1ID, termSetGroup2ID, termSetGroup3ID, termSetGroup4ID) {
        return new Promise(function(resolve, reject) {
            var clientContext = new SP.ClientContext.get_current(),
                taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext),
                termStore = taxSession.getDefaultKeywordsTermStore(),
                terms1 = termStore.getTermSet(termSetGroup1ID),
                terms2 = termStore.getTermSet(termSetGroup2ID),
                terms3 = termStore.getTermSet(termSetGroup3ID),
                terms4 = termStore.getTermSet(termSetGroup4ID),
                termSet1 = terms1.getAllTerms(),
                termSet2 = terms2.getAllTerms(),
                termSet3 = terms3.getAllTerms(),
                termSet4 = terms4.getAllTerms();
            clientContext.load(termSet1);
            clientContext.load(termSet2);
            clientContext.load(termSet3);
            clientContext.load(termSet4);
            clientContext.executeQueryAsync(function() {
                    var termsData = {};
                    termsData = {
                        'termSet1Data': termSet1,
                        'termSet2Data': termSet2,
                        'termSet3Data': termSet3,
                        'termSet4Data': termSet4
                    }
                    resolve(termsData);
                },
                    function (sender, args) {
                        console.log(sender);
                        reject(sender);
                    }
            );
        });
    }

Update taxonomy field value

Check this reference for updating field values on a list:
http://pointofint.blogspot.se/2014/03/how-to-set-any-spfield-value-with-jsom.html

To update taxonomy single value field:

  taxonomySingle.set_label(tag);
  taxonomySingle.set_termGuid(txGUID);
  taxonomySingle.set_wssId(-1);
  taxField.setFieldValueByValue(oListItem, taxonomySingle);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.