1. 程式人生 > 實用技巧 >Client - Side fucntion on Power Portal with Power Apps

Client - Side fucntion on Power Portal with Power Apps

Add advanced client-side functionality

The purpose of this hands-on lab is to demonstrate how to add JavaScript code to a page to render data from Common Data Service as a chart by using another charting library. The data has been retrieved from Common Data Service by using a web template that acts as a REST API endpoint.

The exercises work best when you have sample data to work with. Depending on the environment that you are working with, you might want to install some sample data to assist with the exercises. Power Platform does provide the ability to add sample data as needed. If the environment that you are working in doesn't have sample data installed, follow the steps in the

Add or remove sample datadocumentation to install the sample data into your environment.

Learning objectives

At the end of these exercises, you will be able to:

  • Build a webpage that acts as a REST endpoint that returns data from Common Data Service.
  • Add inline code to a content webpage to retrieve the data by using the endpoint.
  • Use an external JavaScript library to consume the retrieved data.

Estimated time to complete this exercise: 15 to 20 minutes

Prerequisites

For this exercise, make sure that the following parameters are set up in your environment:

  • A Power Apps portal that is provisioned. If you do not have a Power Apps portal available, follow theCreate Portalinstructions to create one.
  • Access to the Power Apps maker portal.

High-level steps

To finish the exercise, complete the following tasks:

  1. Create a web template with Liquid code to retrieve data about accounts in Common Data Service and then return the data in JSON format.
  2. AddPage TemplateandWeb Pagerecords that use the web template that you created.
  3. Open a content page and add JavaScript code that retrieves the data.
  4. Add a charting library to the page and JavaScript code by using the library to build a graph with the retrieved data.

Create a web template

To create a web template, follow these steps:

  1. OpenDynamics 365 Home.

  2. Select the Portals Management app.

  3. SelectWeb Templates.

  4. Select+ New.

  5. Enter the following values:

    • Name- getAccounts
    • Website- Select your current website
    • Source- Enter the following content
    • MIME Type- application/json
    twig
    {% fetchxml accounts %}
    <fetch>
      <entity name="account">
        <attribute name="name" />
        <attribute name="numberofemployees" />
        <attribute name="revenue" />
      </entity>
    </fetch>
    {% endfetchxml %}
    [
    {% for account in accounts.results.entities -%}
      {
        "x": {{ account.numberofemployees }},
        "y": {{ account.revenue }},
        "z": {{ account.revenue | divided_by: account.numberofemployees }},
        "name": "{{ account.name }}"
      }{% unless forloop.last %},{% endunless %}
    {% endfor -%}
    ]
    
  6. PressSave & Close.

This Liquid code retrieves the list of accounts and then generates a data structure in JSON format. The data structure is already prepared for plotting by assigning appropriate labels to data points:

  • name- Company name
  • x- Number of employees
  • y- Company revenue in thousands
  • z- Revenue for each employee (calculated)

Create a page template and a webpage

To create a page template and a webpage, follow these steps:

  1. SelectPage Templates.
  2. Select+ New.
  3. Enter the following values:
    • Name- getAccounts
    • Website- Select your current website
    • Type- SelectWeb Template
    • Web Template- SelectgetAccounts
    • Use Website Header and Footer- Clear the check box
  4. SelectSave & Close.
  5. SelectWeb Pages.
  6. Select+ New.
  7. Enter the following values:
    • Name- getAccounts
    • Website- Select your current website
    • Parent Page- SelectHome
    • Partial URL- getAccounts
    • Page Template- getAccounts
    • Publishing State- Published
  8. SelectSave & Close.

Important

If you have not previously configured entity permissions for the account entity, your API page will return an empty array. Complete the next task to set up the permissions if you have not done so previously.

Add entity permissions

To add entity permissions, follow these steps:

  1. Switch to the Portal Management app.
  2. SelectEntity Permissions.
  3. Select+ New.
  4. Enter the following values:
    • Name- Account Directory
    • Entity Name- Select account entity
    • Website- Select your current website
    • Scope- SelectGlobal
    • Privileges- SelectRead
  5. SelectSave.
  6. Scroll to theWeb Rolessubgrid.
  7. SelectAdd Existing Web Role.
  8. Locate and selectAnonymous usersandAuthenticated users.
  9. SelectAdd.

Test the REST webpage

Go tohttps://yourportal.powerappsportals.com/getAccounts.

Your output should look like the following example:

Add code to retrieve the data

To add code to retrieve the data, follow these steps:

  1. Open Power Apps portals Studio in a new browser tab and then follow these steps:

    1. Go toPower Apps maker portal.
    2. Select the target environment by using the environment selector in the upper-right corner.
    3. From theAppslist, select the application of typePortal.
    4. Select theEditmenu.
  2. Select thePagesicon on the tool belt on the left side.

  3. Select an existing page from the hierarchy, for exampleProduct Blocated under theServicespage.

    Note

    The names and hierarchy of pages on your portal might differ.

  4. Select thePage Copyarea on the page.

  5. SelectComponentson the tool belt.

  6. SelectOne-column section.

  7. SelectAdded sectionand then select thesource code editoricon.

  8. Insert the following code as the content of the innermostdivelement:

    HTML
    <script>
    function makeChart(rData) {
      console.log(rData);
    }
    
    $(document).ready(function() {
      $.get('/getAccounts', makeChart, 'json');
    });
    </script>
    
  9. SelectSave.

  10. SelectBrowse website.

  11. When the page is displayed, press theF12key to display browser developer tools.

  12. Verify that the console output contains the same data as previously retrieved by the REST API page.

Important

If you have not previously configured entity permissions for the account entity, your API call will return an empty array. Make sure that you have completed theAdd entity permissionstask.

Add external library functionality

This exercise uses Highcharts.js library (free for personal or non-profit use) to create a bubble chart based on the data.

  1. Switch to portals Studio.

  2. Locate and open the content page that you previously modified.

  3. Select the section that you previously modified.

  4. Insert the following code either above or below the previous code:

    HTML
      <script src="https://code.highcharts.com/highcharts.js"></script>
      <script src="https://code.highcharts.com/highcharts-more.js"></script>
      <figure>
        <div class="mychart"></div>
      </figure>
    
  5. Modify themakeChartfunction as follows:

    JavaScript
    function makeChart(rData) {
      console.log(rData);
      Highcharts.chart($('.mychart')[0], {
        title: {
          text: "Customers efficiency"
        },
        legend: {
          enabled: false
        },
        xAxis: {
          title: {
            text: "Number of employees"
          }
        },
        yAxis: {
          title: {
            text: "Turnover ($K)"
          }
        },
        tooltip: {
          pointFormat: '<strong>{point.name}</strong><br/>Employed: {point.x}<br>Turnover ($K): ${point.y}',
          headerFormat: ''
        },
        series: [{
          type: 'bubble',
          data: rData
        }]
      });
    }
    
  6. SelectSave.

  7. SelectBrowse website.

  8. The output should now include the bubble chart. Hover over the bubbles to verify the data.