Clear | Remove | Delete Managed metadata (Taxanomy) column value in SharePoint List/ library

You may find many references to write into taxonomy columns (aka. managed metadata columns) but the clearing those is pretty much tricky.

Following code sample guide you through how you can clear the taxonomy column value in you custom client side application (JSOM) based on SharePoint.

//USAGE:
//clearWithValue =true => for clear saved taxanomy column values
//clearWithValue =false => wite into taxanomy column 

function saveValuesToManagedMetadataColumns(listName, fieldId, taxanomyLabel, siteUrl, clearWithValue) {

    //You many need seperate function to resolve GUID for the lable.
//Its based on your requirement and for now its hardcoded
    var taxonmyGuid = "9f75f519-51f8-4723-9182-7e8225a54031";
//Loading context and list
    var context = new SP.ClientContext(siteUrl);
    var list = context.get_web().get_lists().getByTitle(listName);
    //Getting item to update
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml("<View>" +
        "<Query>" +
        "<Where><Eq>" +
        "<FieldRef Name=\'ID\'/>" +
        "<Value Type=\'Number\'>" + fieldId + "</Value>" +
        "</Eq></Where>" +
        "</Query>" +
        "</View>");
    var items = list.getItems(camlQuery);
//Load selected items to context
    context.load(items);
    //Loading MMS field
    var field = list.get_fields().getByInternalNameOrTitle("taxanomyColumnName");
    var txField = context.castTo(field, SP.Taxonomy.TaxonomyField);
//Load field to context
    context.load(txField);

    context.executeQueryAsync(function () {
        //getting term set ID
        var functionTermSetId = txField.get_termSetId().toString();
        //Term value build for update..this is not useful is your purpose only for clearing
//But for illustration..got below also to show off
        var termValue = new SP.Taxonomy.TaxonomyFieldValue();
        termValue.set_label(taxanomyLabel);
        termValue.set_termGuid(taxonmyGuid);
        termValue.set_wssId(-1);
//Iterate through collection and update
        var e = items.getEnumerator();
        while (e.moveNext()) {
            var item = e.get_current();

            //Save to taxanomy column
            if (clearWithValue == false)
                txField.setFieldValueByValue(item, termValue);

            //Clering taxanomy column
            if (clearWithValue == true)
                txField.validateSetValue(item, null);

            //Set noraml fields..If you have them too
            item.set_item('Title', metadataCollection.Title);

            item.update();
        }
        context.executeQueryAsync(function (sender, args) {
            console.log('Successfully updated item with ', args, serviceId, false);
        }, function (args) {
            console.log('Error on updating item with taxanomy value', args, serviceId, false);
        });

    }, function (args) {
        console.log('Internal server Error on updating item with taxanomy metadata', args, serviceId, false);
    });

}

References
http://sharepoint.stackexchange.com/questions/47719/how-can-i-set-empty-value-to-taxonomyfield-of-microsoft-sharepoint-client-taxono

Get | Resolve Term ID for Term Value in SharePoint Metadata Service

This may be generic function you can use when you play with managed metadata (taxonomy) columns or with Managed Managed Metadata Service.

Notes:

  • Used JSOM since no impletation in REST API to get done this task in SharePoint to date of post
  • Passing term set ID is must since there may may be many term values equivalent in the term store
  • For the example, I have retrieved the term set ID from the list field which glued with the managed metadata service.

Following code illustrate how to get term ID for term value provided.


// Resolve Term ID for the Term Value 
 function getTermIdForTermValue(siteUri, listName, fieldName, termValue) {
 //Define
 var deferred = $q.defer()
 , termId;
 var clientContext = new SP.ClientContext(siteUrl);
 var list = clientContext.get_web().get_lists().getByTitle(listName);
 //Tx field
 var field = list.get_fields().getByInternalNameOrTitle(fieldName);
 var txField = clientContext.castTo(field, SP.Taxonomy.TaxonomyField);
 //load context
 clientContext.load(field);
 clientContext.load(txField);
 // //excute async of context
 clientContext.executeQueryAsync(
 //Success on Async
 Function.createDelegate(this
 , function () {
 //Getting term set of the field
 var termSetId = txField.get_termSetId().toString();
 var tSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
 var ts = tSession.getDefaultSiteCollectionTermStore();
 var tset = ts.getTermSet(termSetId);
 //Define term label to match
 var lmi = new SP.Taxonomy.LabelMatchInformation(clientContext);
 lmi.set_lcid(1033);
 lmi.set_trimUnavailable(true);
 lmi.set_termLabel(termValue);
 var termMatches = tset.getTerms(lmi);
 //context loading with taxanomy values
 clientContext.load(tSession);
 clientContext.load(ts);
 clientContext.load(tset);
 clientContext.load(termMatches);
 clientContext.executeQueryAsync(
 function () {
 if (termMatches &amp;&amp; termMatches.get_count() &gt; 0) {
 termId = termMatches.get_item(0).get_id().toString();
 console.log("Resolved Term Id for Term " + termValue, termId);
 deferred.resolve(termId);
 }
 else {
 console.log("No IDs to resolved for Term " + termValue);
 deferred.resolve(null);
 }
 }
 , function (sender, args) {
 console.log("Error on resolving term ID", args);
 deferred.reject(null);
 });
 }
 , function (sender, args) {
 console.log(args.get_message() + '\n' + args.get_stackTrace());
 })
 //Failed on Async
 , Function.createDelegate(this, function (err) {
 console.error(err.get_message());
 })
 );
 return deferred.promise;
 }

Click here to view in gist.

For more details refer following links;

Update SharePoint Metadata (Taxonomy) column with Angular JS

Check following code which updates provided SharePoint list/ library item with Managed metadata column.

First it solves GUID from the Managed Metadata service then push that value and other column values to the SharePoint back end.

Before execute following code you need properly configured “Managed Metadata Service” and list configuration with MMS.

Click here above is not visible.

If this code helped, don’t miss to give feedback and following!

Managed Metadata Column Value Add with Angular | JavaScript & JSOM | CSOM

Following would be high-level program flow;MMS Column Update Program Flow

SP Taxonomy need to be imported.


var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Taxonomy.js");

Create custom list item with metadata column in SharePoint with JSOM and Angular JS.

// Adding item to SharePoint custom list with Managed Metadata column (MMS column) with JSOM
(function () {
    'use strict'; 

    // define controller
    var controllerId = "mmsColumnUploadCtrl"; 

    angular
        .module('app')
        .controller(controllerId, ['$scope', mmsColumnUploadCtrl]); 

    // create controller
    function mmsColumnUploadCtrl($scope) {
        //global var
        var vm = this;

        //add metadata column to sharepoint
        vm.AddMetadataColumn = function () {
            var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/"; 

            // create list item with MMS column
            $.getScript(scriptbase + "SP.Taxonomy.js", createListItemWithMMSColumn); 

        } 

        //Create list item metadata with MMS column
        function createListItemWithMMSColumn() {
            //site URi
            var siteUrl = 'http://<site url>/sites/MMSPOC';
            // List name of updating
            var listName = 'TestList';// List name
            //Term GUID get from Service
            var termId = 'ed414e70-cc02-444b-ba78-8456e6495e45';//term GUID
            //For multi labled column may need to provice term lable also, else no
            //var termLabel = 'ABCTEST';//Term label

            // Client context
            var clientContext = new SP.ClientContext(siteUrl);
            var oList = clientContext.get_web().get_lists().getByTitle(listName);
            var itemCreateInfo = new SP.ListItemCreationInformation();
            var oListItem = oList.addItem(itemCreateInfo);
            // Define item
            oListItem.set_item('Title', 'New Item!'); // non MMS columns
            oListItem.set_item('MMSCol', termId); //MMS column
            // Update item
            oListItem.update(); 

            //client context..Async Req.
            clientContext.load(oListItem);
            clientContext.executeQueryAsync(
                Function.createDelegate(this, onQuerySucceeded),
                Function.createDelegate(this, onQueryFailed)
             );
        } 

        // On query success
        function onQuerySucceeded(oListItem) {
            console.info('Item created!');
        }
        // On query failed
        function onQueryFailed(sender, args) {
            console.error('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        } 

    }; 

})();

Update document library items’ managed metadata column in SharePoint with JSOM and Angular

// Adding item to SharePoint "Document Library" with Managed Metadata column (MMS column) with JSOM
(function () {
    'use strict'; 

    // define controller
    var controllerId = "mmsColumnUploadCtrl"; 

    angular
        .module('app')
        .controller(controllerId, ['$scope', mmsColumnUploadCtrl]); 

    // create controller
    function mmsColumnUploadCtrl($scope) {
        //global var
        var vm = this;

        //add metadata column to sharepoint
        vm.AddMetadataColumn = function () {
            var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/"; 

            // Create document item ith MSS column
            $.getScript(scriptbase + "SP.Taxonomy.js", updateDocumentItemWithMMSColumn); 

        } 

        // Create document metadata of document library item with MMS column
        function updateDocumentItemWithMMSColumn() {
            //site URi
            var siteUrl = 'http://<site>/sites/MMSPOC'; 

            // List name of updating
            var listName = 'MMSPOCDocLib';//document library name

            // GUID of the term
            var termId = 'ed414e70-cc02-444b-ba78-8456e6495e45';//term guid

            //For multi-valued terms following will be needed
            var termLabel = 'ABCTEST';//term label

            //Item Id for update in the document library
            //3 is item ID to be updated
			//You may dynamically change with the requirement
            var itemIdUpdating = 3; 

            // Client context
            var clientContext = new SP.ClientContext(siteUrl);
            var oList = clientContext.get_web().get_lists().getByTitle(listName);
            var itemCreateInfo = new SP.ListItemCreationInformation(); 

            var oListItem = oList.getItemById(itemIdUpdating);
            // Define item
            oListItem.set_item('Title', 'Item updated!');
            oListItem.set_item('MMSCol', termId);
            // Update item
            oListItem.update(); 

            //client context..Async Req.
            clientContext.load(oListItem);
            clientContext.executeQueryAsync(
                Function.createDelegate(this, onQuerySucceeded),
                Function.createDelegate(this, onQueryFailed)
             );
        }
        // On query success
        function onQuerySucceeded(oListItem) {
            console.info('Item created!');
        }
        // On query failed
        function onQueryFailed(sender, args) {
            console.error('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        } 
    };

Await for more interesting coding samples and articles, keep following!!