Declaring SharePoint Client Side Taxonomy Picker Control and Reading the Selected Values and Create Item in List

In this post, We will learn how to declare the SharePoint Client Side Taxonomy Picker control and reading the values from it.

Step 1: References required to load the Taxonomy Picker Control Correctly.

CSS Reference: Try to download it (Refer if  already have in your sites)
<!-- CSS Files -->
            <link href = "/taxonomypickercontrol.css" rel = "stylesheet" / >
<!-- Javacript Files -->


JS References Files:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type = "text/javascript" src = "../_layouts/15/SP.Taxonomy.js"></script>
<script type = "text/javascript" src = "/taxonomypickercontrol.js"> </script>
<script type = "text/javascript" src = "/taxonomypickercontrol_resources.en.js"></script>

If images are not loaded correctly please downlaod it and upload


HTML Code:

<table>
                <tr>
                    <td>
                        Asset Function
                    </td>
                    <td>
                        <input type="hidden" id="taxPickerAssetFunction" />
                    </td>
                </tr>
                <tr class="dislplayNone">
                    <td>
                        Business Segment
                    </td>
                    <td>
                        <input type="hidden" id="taxPickerBusinessSegment" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="button" id="btnCreateItem" onclick="createListItem();" value="Create Item"/>
                    </td>
                </tr>
            </table>


Please find the full code in the below.:

<html>
    <head>
        <!-- CSS Files -->
            <link href = "/taxonomypickercontrol.css" rel = "stylesheet"/>
<!-- Javacript Files -->
    
    <style>
        .dislplayNone
        {
            display:none;
        }
    </style>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type = "text/javascript" src = "../_layouts/15/SP.Taxonomy.js"></script>
<script type = "text/javascript" src = "taxonomypickercontrol.js"> </script>
<script type = "text/javascript" src = "taxonomypickercontrol_resources.en.js"></script>
    <script>
        var clientContext;
        var taxPickerIndex = {};
        
        var taxPicekrAssetFunctionTermID= "";
        var taxPickerBusinessSegmentTermID = "";
        $(document).ready(function() {
            var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
            $.getScript(scriptbase + "SP.Runtime.js", function () {
                    $.getScript(scriptbase + "SP.js", function(){
                        $.getScript(scriptbase + "SP.Taxonomy.js", bindTaxPickerAssetFunction);                    });
                });
        });
        
        function createListItem()
        {
            var today = new Date();
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl +"/_api/web/lists/getbytitle('SPFcReact')/items",
                type: "POST",
                data: JSON.stringify({
                    "__metadata": { "type": "SP.Data.SPFcReactListItem" }, // <-- entity type name
"Title": "Title_" + today,
//On Item Creation to pass the Taxonomy Picker value
                    "AssetFunctionTS": {
                        "__metadata": {
                            "type": "SP.Taxonomy.TaxonomyFieldValue"
                        },
                        "TermGuid": taxPicekrAssetFunctionTermID, // <-- Term Id
                        "WssId": "-1" // <-- always "-1"
                    },
                    "BusinessSegmentTS": {
                        "__metadata": {
                            "type": "SP.Taxonomy.TaxonomyFieldValue"
                        },
                        "TermGuid": taxPickerBusinessSegmentTermID, // <-- Term Id
                        "WssId": "-1" // <-- always "-1"
                    }
                }),
                headers: {
                     "Accept": "application/json; odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                },
                success: function(data)
                {
                    alert("Success");
                },
                 error: function(data)
                {
                    console.log(data.responseText);
                    alert(data.responseText);
                }
            });
        }
        
      function bindTaxPickerAssetFunction()
        {   
            clientContext = new SP.ClientContext.get_current();
$('#taxPickerAssetFunction').taxpicker({ isMulti: true, allowFillIn: false,
useKeywords: false, termSetId: "749438f8-c292-46c9-820f-81eb680a32ea",
levelToShowTerms: 1,maxSuggestions: 5 }, clientContext,initializeBusinessSegmentTaxPicker);
$('#taxPickerBusinessSegment').taxpicker({ isMulti: false, allowFillIn: false,
useKeywords: false, termSetId: "67acc2d8-56ff-4f14-b423-15a0c3ef36af",
levelToShowTerms: 1, useTermSetasRootNode: false }, clientContext,getBusinessSetmentTerm);
                taxPickerIndex["#taxPickerBusinessSegment"] = 0;
        }
        
        
        //On Change showing the Other Taxonomy Picker and reade the Taxonomy Picker Value.
        function initializeBusinessSegmentTaxPicker() {
            if (this._selectedTerms.length <= 1) {
                $("tr").removeClass("dislplayNone");
                taxPicekrAssetFunctionTermID = this._selectedTerms[0].Id;
                console.log(taxPicekrAssetFunctionTermID);              
            }
            else if(this._selectedTerms.length > 1)
            {
                //Multiple items format : -1;#|TERMGUID1;#-1;#|TERMGUID2
                taxPicekrAssetFunctionTermID= "";
                $("tr").removeClass("dislplayNone");
                for(i=0; i < this._selectedTerms.length;i++)
                {
                    taxPicekrAssetFunctionTermID = "-1;#|" + this._selectedTerms[i].Id + ";#" + taxPicekrAssetFunctionTermID;
                    console.log(taxPicekrAssetFunctionTermID);  
                }
                taxPicekrAssetFunctionTermID = taxPicekrAssetFunctionTermID.slice(0, -2);
            }
        }
//On Change to reade the Taxonomy Picker Value.
        function getBusinessSetmentTerm()
        {
            if (this._selectedTerms.length > 0) {
            taxPickerBusinessSegmentTermID = this._selectedTerms[0].Id;
            console.log(taxPickerBusinessSegmentTermID);
            }
        }
</script>
</head>
    <body>
        <div>
            <table>
                <tr>
                    <td>
                        Asset Function
                    </td>
                    <td>
                        <input type="hidden" id="taxPickerAssetFunction" />
                    </td>
                </tr>
                <tr class="dislplayNone">
                    <td>
                        Business Segment
                    </td>
                    <td>
                        <input type="hidden" id="taxPickerBusinessSegment" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="button" id="btnCreateItem" onclick="createListItem();" value="Create Item"/>
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>


Happy Coding.... :)










Comments

Popular posts from this blog

SharePoint 2013 Keyword Query (KQL) Content Class Property Restrictions

Filtering the Sharepoint List Taxonomy Column using Rest API

SharePoint CSOM to Create Folders and Sub Folders based on Excel Data