Showing posts with label Modern SharePoint List. Show all posts
Showing posts with label Modern SharePoint List. Show all posts

August 3, 2023

To create terms dynamically in a TermSet and set them in a Managed Metadata column using Power Automate

Introduction: 

In this blog post, we will learn how to dynamically create Terms in a TermSet of a Termstore and set them in a managed metadata column using Microsoft Power Automate.

Requirement:

To obtain information about Skills and Past Projects from the Office 365 user profile and add it to a SharePoint list, we will enable Out-of-the-Box (OOTB) filtering and sorting operations on these fields.
We can use Single line of text OR Multiline of text site column and store information with delimiters, but limitation was, can’t perform OOTB filtering and sorting operation.

To overcome this issue, we are going to use a Managed Metadata site column to store the terms values dynamically. This approach will allow us to perform Out-of-the-Box (OOTB) filtering and sorting operations on the information, providing a more effective solution compared to using Single line of text or Multiline of text site columns with delimiters.

Approach:

Create “Managed Metadata field” with “Allow multiple values” checkbox enabled and “Customize your term set” option selected as shown in below screenshot.





Below are the steps in Power Automate to dynamically create Terms in a TermSet of a Termstore and then create an item in a SharePoint list with those terms in a Managed Metadata field.

Step 1: Add an action “Initialize Variable”, Name it as “Initialize variable Skills” as shown in below screenshot. This will be used to store JSON for use in SharePoint list Item creation.

 


Step 2: Add “Get user profile (V2)” action with user principal name or Email ID in “User (UPN)” as shown below.

 


Step 3: Append value to “Skills” variable as shown in below screenshot.


 Step 4: Add below set of actions to process each element in “Skills” array (which we retrieved in Step-2).
 



Step 5: Then we need to add an action called “Send an HTTP request to SharePoint” to retrieve terms from TermSet.

Uri - _api/v2.1/termStore/groups/97ac8ae5-1608-4047-8951-585b3a2640c5/sets/e0af947c-6cef-4766-8c79-9c454cc5a323/children.

In Uri, “97ac8ae5-1608-4047-8951-585b3a2640c5” is Termstore ID and “e0af947c-6cef-4766-8c79-9c454cc5a323” is TermSet ID in which we need to store or create terms.

 


Step 6: To compare the current item in the loop with the term name, we need to filter the values retrieved in Step-5 to check if they are "equal to" the term name.

string (item ()? ['labels'][0] ['name']) expression is used in comparison as shown in below screenshot.

 


Step 7: Add the following set of actions to form JSON or create JSON data for the "Skills" variable. The condition, as shown in the below screenshot, checks whether the term is present in the "Skills" TermSet or not, using the expression length(body('Filter_skills_array')). If the term is not present, we are adding a POST call to create a new term and then appending the values to the "Skills" variable. On the other hand, if the term is already present, we simply append the values to the "Skills" variable.


 
Step 8: If the condition is "Yes," indicating that the term is present in the "Skills" TermSet of the Termstore, then we simply append the values to the "Skills" variable.

Note: Value will be appended in JSON format as - 
{
“value”: “Sharepoint|3198df72-311b-4757-9246-052296af2”
}

Where, the expression in below screenshot consists of “{current term name in loop}|body('Filter_skills_array')[0]['id']”

 


Step 9: If the condition is "No," meaning that the term is not present in the "Skills" TermSet of the Termstore, in such a case, we need to create the term using a POST call with the action called "Send an HTTP request to SharePoint," as shown in the below screenshot.

Uri - _api/v2.1/termStore/groups/97ac8ae5-1608-4047-8951-585b3a2640c5/sets/e0af947c-6cef-4766-8c79-9c454cc5a323/children.

In Uri, “97ac8ae5-1608-4047-8951-585b3a2640c5” is Termstore ID and “e0af947c-6cef-4766-8c79-9c454cc5a323” is TermSet ID in which we need to store or create terms.



Step 10: Add “Compose” action to fetch and store term ID from Step-9, as shown below.

 


Step 11: After that, append the JSON value, as shown in the below screenshot, with the term name and ID from the "Step-10" compose action.



Step 12: Add the below action after completing the Condition and loop actions to append the closing of JSON in the "Skills" variable.

 


Step 13: Add the below action to parse the JSON, enabling us to create and store the data in a SharePoint list item.

Schema: {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "Value": {
                "type": "string"
            }
        },
        "required": [
            "Value"
        ]
    }
}

 


Step 14: Use Step-13 parsed JSON in “Create Item” action as shown in below screenshot.

 


Finally, we can see that terms have been added to the "Skills" TermSet using Power Automate flow.
 


Also, terms have been added to the "Skills" Managed Metadata field in the SharePoint list as well.

 


Additionally, we can view the "Skills" managed metadata field from the list settings, where we have dynamically appended terms using Power Automate






If you have any questions you can reach out our SharePoint Consulting team here.

April 21, 2022

How to use Multi-Value Taxonomy Picker Control in the SPFx webpart?

Introduction

Recently we implemented an SPFx web part solution for a Postal and Parcel company based out of Melbourne, Victoria, Australia. We came across a requirement to provide a taxonomy picker control to select the terms for the term set and to store it in the SharePoint list/library. 


There are two ways to store the taxonomy picker's selected value in the SharePoint List/Library based on whether it is a single value or multi-value taxonomy picker. 


We have already shared the details on how to use the single value taxonomy picker control in our previous blog. It can be accessed here.


In this blog, we will learn about multi-value taxonomy picker control and how to use it in the SPFx web part and store its selected term value with other properties/fields in the SharePoint list/library.

Pre-Requisites

  • We need to have a multi-value selectable managed metadata column associated with a term set in the SharePoint list. 
  • We need to have the @pnp/spfx-controls-react package installed in our SPFx web part. We can use the command below to install the package. 
 npm install @pnp/spfx-controls-react --save --save-exact  

  • Create the context and siteUrl props in the SPFx solution. 
  • Create a state of Array type to store the selected taxonomy picker’s value. 

Implementation

    Below are the steps to implement the Taxonomy Picker Control for the multi-value managed metadata column. 

    Step 1: 

    Import the taxonomy picker and IPickerTerms in the .tsx(file that contains the render method) file of the SPFx web part as shown below. 

     import { TaxonomyPicker, IPickerTerms } from "@pnp/spfx-controls-react/lib/TaxonomyPicker";   
    

    Step 2: 

    Implement the Taxonomy Picker Control in the render method as shown below. 
    <TaxonomyPicker
         allowMultipleSelections={true}
         termsetNameOrID="Job Title"
         panelTitle="Select Job Title"
         label=""
         context={this.props.context}
         onChange={this.onJobtitleTaxPickerChange.bind(this)}
         isTermSetSelectable={false}
         initialValues={this.state.setJobTitletaxonomy}
         />
    


    Below are the attributes used in the Taxonomy Picker Control.

    • allowMultipleSelections: This attribute is used for multi-value selection. Please provide value as "true" in order to work with the multi-value taxonomy picker control.
    • panelTitle: We need to provide the Term Set Picker Panel title.
    • Label: We need to provide the text displayed above the Taxonomy Picker. Context: We need to provide the content of the current web part. For example, this.props.context.
    • TermsetNameOrID: We need to provide the term set's name or its GUID.
    • OnChange: This attribute is used to store the selected term in a state so we can use that state's value while submitting The item to the SharePoint list/library. It's an optional attribute. 
    • InitialValues: This attribute is used to set the taxonomy picker's selected values. It's an optional attribute. 

    Step 3: 

    After creating taxonomy control, we need to define a method to handle its on-change event and store the selected term in a state as shown below. 

      private onJobtitleTaxPickerChange(terms: IPickerTerms) {
        this.setState({
          setJobTitletaxonomy: terms
        });
      } 
    

    Step 4: 

    The managed metadata column has a single line of text hidden column associated with it, it's a hidden field and we will use this field with its internal name for the further process. We can retrieve the internal name of the hidden field of the managed metadata column using the below rest API.  

     http://<sitecollection>/<site>/_api/web/Lists/getbytitle(List Title)/items(itemid)/fieldValuesAsText   

    Here, we have to provide the site address, List title, and item Id of one of the list items. For Example:

     https://binaryrepublik.sharepoint.com/sites/blog/_api/web/Lists/getbytitle('Blog')/items(1)/fieldValuesAsText   
    

    We will get the response from the Rest API as shown below. 


    We will use this column in our program for storing the managed metadata column's value.  

    Step 5: 

    When we use the Rest API to store values to the SharePoint List/Library we need to pass the details in the body of the rest API and to provide the details for managed metadata column we need to use the below format.

        var JobTitle = "";
        this.state.setJobTitletaxonomy.forEach((element, index) => {
          if (index == 0) {
            JobTitle += "-1;#" + element.name + "|" + element.key + ";";
          }
          else {
            JobTitle += "#-1;#" + element.name + "|" + element.key + ";";
          }
        });
        if (this.state.setJobTitletaxonomy.length > 0) {
          bodyArray["fc4c63d6c6ce4056ae9a66b7db5f5564"] = JobTitle;
        }  

    Here, we have used the setJobTitletaxonomy state for the managed metadata column. Now we can use the above body array to the body of the SharePoint rest API call. 

    Step 6: 

    Below is the detailed code for retrieving the values and submitting them to create a new item to the SharePoint List/Library. Submit method of the SPFx form: 

       //getValues() is used to retrieve the request digest value for creating items using the rest API call. 
      public getValues(site): any {
        try {
          var url = site + '/_api/contextinfo';
          return fetch(url, {
            method: "POST",
            headers: { Accept: "application/json;odata=verbose", "Content-Type": 'application/json;odata=verbose', 'Access-Control-Allow-Origin': '*' },
            credentials: "same-origin"
          }).then((response) => {
            return response.json();
          });
        } catch (error) {
          console.log("getValues: " + error);
        }
      }
      //CreteItem() is used to create an item in the SharePoint list.   
      public createItem() {
        let bodyArray = {};
        bodyArray['__metadata'] = {
          "type": "SP.Data.BlogListItem"
        },
        bodyArray['Title'] = "Ajay Varma";
        var JobTitle = "";
        this.state.setJobTitletaxonomy.forEach((element, index) => {
          if (index == 0) {
            JobTitle += "-1;#" + element.name + "|" + element.key + ";";
          }
          else {
            JobTitle += "#-1;#" + element.name + "|" + element.key + ";";
          }
        });
        if (this.state.setJobTitletaxonomy.length > 0) {
          bodyArray["fc4c63d6c6ce4056ae9a66b7db5f5564"] = JobTitle;
        }
        let jsonBodyArray = JSON.stringify(bodyArray);
        var url = this.props.siteUrl + `/_api/web/lists/getbytitle('Blog')/items()`;
        return new Promise<any>((resolve, reject) => {
          try {
            this.getValues(this.props.siteUrl).then((token) => {
              fetch(url,
                {
                  method: "POST",
                  credentials: 'same-origin',
                  headers: {
                    Accept: 'application/json',
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": token.d.GetContextWebInformation.FormDigestValue,
                  },
                  body: jsonBodyArray,
                }).then((r) => {
                  return r.status != 204 ?
                    r.json() : r.status;
                })
                .then((response) => {
                  resolve(response);
                  return response;
                })
                .catch((error) => {
                  reject(error);
                });
            }, (error) => {
              console.log(error);
              reject(error);
            });
          }
          catch (e) {
            console.log(e);
            reject(e);
          }
        });
      }
    

    Results:

    Side Panel for Taxonomy Picker:

    This is the Taxonomy Picker's Panel that retrieves the terms from the term set and displays them as shown below.

    SPFx web part: 

    Once we select and save the term for the Taxonomy Picker it will be added to the Taxonomy Picker field as shown below.

    SharePoint List: 

    The SharePoint List/Library will store the values as shown below.

    Conclusion: 

    This is how we can use the multi-value taxonomy picker. Hope this helps you. 

    If you have any questions you can reach out our SharePoint Consulting team here.