April 27, 2023

How to trigger Power Automate from SPFx webpart and return result back to SPFx webpart?

Introduction:

In this blog, we will learn how we can trigger Power Automate from SPFx web part, fetch some data or perform any operation and return result back to SPFx web part.

Scenario:

We need to fetch data from API which was not accessible by SharePoint site due to CORS issue. So we created Power Automate which will triggered from SPFx web part, and this flow will fetch the data from API and return the result to SPFx web part.

Implementation:

Follow below steps to trigger Power Automate from SPFx web part and return result back to SPFx web part.

Step 1: First, we need to create Power Automate which will have trigger of When HTTP request is received.

Note: HTTP POST URL will be generated only when you Save the Power Automate.

Step 2: If we want to pass some data from SPFX web part to Power Automate, we need to specify JSON schema in Request Body JSON Schema. 
For example, we can use JSON Schema for Startdate and Enddate as below:
{
    "type": "object",
    "properties": {
        "Startdate": {
            "type": "string"
        },
        "Enddate": {
            "type": "string"
        }
    }
}

Step 3: Now, in Power Automate we need to action for Response at the end of the Power Automate which will return the response to SPFX web part.

Step 4: Now, you can save the flow and copy the HTTP POST URL from first action, which we will use this URL in SPFX web part.

Step 5: In a SPFX web part, first we need to import below namespaces.
import { HttpClient, HttpClientResponse, IHttpClientOptions} from '@microsoft/sp-http';

Step 6: Now, we will create a new method which will be called when we want to trigger Power Automate. So in that method, first we will create a body, which will pass data to Power Automate:

const body: string = JSON.stringify({
      'Startdate': '1-1-2023',
      'Enddate': 12-31-2023
 });

Step 7: Now, we will create header, which will be used when we trigger Power Automate:
const requestHeaders: Headers = new Headers();
requestHeaders.append('Content-type', 'application/json');

Step 8: As we will be using HTTP request, we need to use body and headers in HTTPClient Options:

const httpClientOptions: IHttpClientOptions = {
      body: body,
      headers: requestHeaders
};

Step 9: Now we will trigger the flow using HTTP request as shown in below code:

 return this.props.context.httpClient.post(
      postURL, //This will be the URL which is generated in Power Automate
      HttpClient.configurations.v1,
      httpClientOptions)
      .then((response: HttpClientResponse): Promise<HttpClientResponse> => {
        return response.json();
  });
Note: Before we write above code, we need to create new property for context and we need to assign below value:
context: this.context

Step 10: Here is the full code snippet of the method which will trigger Power Automate:
private getMetricsData(StartDate: string, EndDate: string): Promise<HttpClientResponse> {
    const postURL = ""; // This will be the URL which is generated from Power Automate

    const body: string = JSON.stringify({
      'Startdate': StartDate,
      'Enddate': EndDate
    });

    const requestHeaders: Headers = new Headers();
    requestHeaders.append('Content-type', 'application/json');

    const httpClientOptions: IHttpClientOptions = {
      body: body,
      headers: requestHeaders
    };

    return this.props.context.httpClient.post(
      postURL,
      HttpClient.configurations.v1,
      httpClientOptions)
      .then((response: HttpClientResponse): Promise<HttpClientResponse> => {
        return response.json();
      });
  }

Step 11: Now when we call the method, it will trigger the Power Automate and return the result to SPFX web part. 

Conclusion:

This is how we can trigger Power Automate from SPFX web part and return the result back to SPFX web part. Hope this blog will be helpful for you!

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

March 23, 2023

How to Use Multiple Attachments Controls in Power App List Form

Introduction:

In this blog we will learn how to use multiple attachment controls and how to manage attached files with multiple attachment controls in Power Apps custom list form.

Technical Approach:

We will store files of all attachment controls in collection and then we will store files available in collection in document library using Power Automate.

Pre-requisites:

  1. List should be ready for which you want to create Power Apps form.
  2. Create Document Library with fields shown in below screenshot. Here in this example, Document Library name is Project Documents.

Create Power Automate

Step 1: Go to the https://make.powerautomate.com/ and select Instant cloud flow from Create menu of left navigation.


Step 2: Now, type the flow name and select the PowerApps (V2) trigger and click on Create button.

Step 3: Now, expand the Power Apps (V2) trigger and add below input fields:
In above inputs "ItemID", "UploadedByName" and "DocumentType" will be text type field and "File Content" will be file type field.

Step 4: Now, click on New step and new action for Create file in SharePoint as shown in below screenshot:


Step 5: Now, select the Site Address and your document library in Folder Path fields. In the File Name, copy-paste the below expression:
 @{triggerBody()['file']['name']}
And, in File Content field, select File Content which we defined in Power App input as shown in below screenshot:

Step 6: Now, add new step for Update File Properties as shown in below screenshot:


Step 7: Now select the Site Address and Library Name. In Id field, select the ItemId from Create file action as shown in below screenshot:

Step 8: For the Document Type, Uploaded By and Project ID columns, select the Power App inputs as shown in below screenshot:

Step 9: Now, all attachments are uploaded to document library, so we can delete documents form list item attachment. So to delete attachment, add a new step for Get Attachments.

Step 10: Select the Site Address and List name and in Id fields, select the ItemId from Power App input.

Step 11: Now, add a new step for Apply to each.

Step 12: Now in Select an output from previous steps field select the body of Get Attachments action as shown in below screenshot:

Step 13: Now, click on Add an action in Apply to each and select the Delete Attachments action.

Step 14: Now, in Delete Attachments action select the Site Address and List Name. In Id field, select the ItemId from Power App inputs and in File Identifier add the expression as shown in below screenshot:


Step 15: Now our flow is ready, so save the flow.

Use multiple attachment controls:

Follow below steps to use multiple attachment controls in Power App list form:

Step 1: Open your SharePoint list and select Customize form option from integrate menu.

Step 2: Once your Power App form open, one attachment field will already available. Now select attachment data card value and copy it.


Step 3: Now, paste it on the same data card, so Attachments data card will now show 2 file upload controls. You can add label above both of the file upload controls as shown below:



Step 4: Now we will need to add the document library in data source.


Step 5: Now select the first attachment control and add below code in its OnAddFile action.
 ClearCollect(SOWDocs,Self.Attachments);  
Above code will add all current selected files in SOWDocs collection.

Step 6: Now, we will use the same code for second attachment control. But with different collection name.

Step 7: Now, in both attachment controls, write the same code for OnRemoveFile action. So when user add or remove any file in attachment controls, we will have all currently selected files in collection.


Step 8: Now, click on Power Automate from left menu and click on Add flow.

Step 9: Now search for your flow name and click on the flow to add in the Power Apps form.

Step 10: Now, go back to the tree view of form and click on sharepointform1. And in OnSuccess method replace the below code.
 ForAll(  
   SOWDocs As Document,  
   UploadProjectManagementDocuments.Run(  
     SharePointForm1.LastSubmit.ID,  
     User().FullName,  
     "File to Upload",  
     {  
       file: {  
         contentBytes: Document.Value,  
         name: Document.Name  
       }  
     }  
   )  
 );  
 ForAll(  
   ProjectPlanDocs As Document,    
   UploadProjectManagementDocuments.Run(  
     SharePointForm1.LastSubmit.ID,  
     User().FullName,  
     "Additional Attachment",  
     {  
       file: {  
         contentBytes: Document.Value,  
         name: Document.Name  
       }  
     }  
   )  
 );  
 ResetForm(Self); RequestHide();  



Step 11: Now save and publish the power app form and selected document of both attachment controls will be stored in document library when we save the list item from Power App form.




Step 12: To show documents which are already uploaded in document library, you can use gallery control and show documents by filtering using Project ID and Document Type.

Conclusion:

This is how we can use multiple attachment controls in Power App list form. Hope this blog will be helpful for you!

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