Power Pages 用戶端 API 範例

本文範例展示了如何結合 Power Pages 用戶端 API 來實作表單與清單上的常見情境。 每個範例都是完整的,你可以複製到 JavaScript 網頁檔案或頁面的 自訂 JavaScript 區塊,然後更改表單名稱、欄位名稱和表格名稱以符合你的網站。

所有範例都使用 客戶端 API 初始化中描述的回調模式,確保客戶端 API 在程式碼執行前已準備好。 回呼以 async 宣告,以便使用 await。 當你自己的程式碼沒有使用 await. 時,就省略關鍵字async。

範例 Description
從 Dataverse 記錄設定一個模態查詢值 取得 Dataverse 紀錄並用它來填充模態查詢控制項。
當查閱呈現為下拉式清單時,設定查閱值 依據控制項呈現為下拉式清單還是強制回應查閱,設定查閱值。
讀取並設定多選選擇欄中的數值 閱讀所選選項,並在不移除現有選項的情況下新增選項。
使用伺服器上唯讀或隱藏的控制項 在更改控制行為前,請檢查控制可用性與唯讀狀態。
根據另一欄的值將某欄設為必填 根據另一個控制點的值,套用條件要求和自訂驗證。
顯示或隱藏清單中的欄位 隱藏一個現代清單欄位,並自訂另一欄的標題和提示。
在列表中顯示或隱藏紀錄 隱藏非活躍的列,並視覺上區分目前使用者無法編輯的紀錄。

從 Dataverse 記錄設定一個模態查詢值

此範例是透過 Web API 取得帳號記錄,並用它來填充表單的 模態查詢 。 模態查詢需要一個包含 ID、名稱及相關記錄資料表名稱的物件。

Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    // 1. Retrieve the first account record.
    //    $top=1 returns a single record, and $select limits the payload to the
    //    columns that the lookup control needs.
    const queryOptions = '$select=accountid,name&$top=1';
    const response = await $pages.webAPI.retrieveMultipleRecords('accounts', queryOptions);
    const records = response.value;

    if (!records || records.length === 0) {
        console.warn('No account records were returned from Dataverse.');
        return;
    }

    const firstAccount = records[0];
    console.log(`Retrieved account: ${firstAccount.name}`);

    // 2. Get the form. Use the name or the ID of your basic or multistep form.
    const form = $pages.currentPage.forms.getFormByName('Profile Web Form (Enhanced)');

    if (!form) {
        console.error('The target form was not found on the page.');
        return;
    }

    // 3. Get the lookup control by its logical name.
    const lookupControl = form.getControlByLogicalName('new_managingpartnerid');

    if (!lookupControl) {
        console.error('The lookup control was not found on the form.');
        return;
    }

    // 4. Set the lookup value. A modal lookup expects an object that contains
    //    the id, name, and entityType values.
    lookupControl.setValue({
        id: firstAccount.accountid,
        name: firstAccount.name,
        entityType: 'account'
    });

    console.log('The lookup control is populated.');
});

Tip

當你不知道控制的邏輯名稱時,要找到控制點,可以列舉 form.controls 並使用該 getName 方法,例如 form.controls.find(control => control.getName() === 'Managing Partner')。

當查閱欄位顯示為下拉式清單時,設定查閱值

查詢欄位會依表單配置方式,以模態對話框或下拉清單的形式呈現。 這兩個控制項在方法中接受不同的值 setValue ,所以在設定值前先檢查屬性 isDropdown 。 下拉式查詢期望選擇的 ID,而模態式查詢則期望物件。

重要

下拉式查詢只包含其設定的檢視與篩選器回傳的紀錄。 將值設為下拉選單中可用的紀錄的 ID。 在此範例中,請過濾查詢,使其只返回查詢所提供的紀錄。

Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    const form = $pages.currentPage.forms.getFormByName('Profile Web Form (Enhanced)');
    const lookupControl = form && form.getControlByLogicalName('new_managingpartnerid');

    if (!lookupControl) {
        console.error('The lookup control was not found on the form.');
        return;
    }

    const response = await $pages.webAPI.retrieveMultipleRecords('accounts', '$select=accountid,name&$top=1');
    const records = response.value;

    if (!records || records.length === 0) {
        return;
    }

    const account = records[0];

    if (lookupControl.isDropdown) {
        // A dropdown lookup expects the ID of the option to select.
        lookupControl.setValue(account.accountid);

        // getValue returns an object that contains the id and name of the selected option.
        const selected = lookupControl.getValue();
        console.log(`Selected option: ${selected && selected.name}`);
    } else {
        // A modal lookup expects an object.
        lookupControl.setValue({
            id: account.accountid,
            name: account.name,
            entityType: 'account'
        });
    }
});

讀取並設定多選選擇欄中的數值

多選選擇清單控制會儲存一組數字。 這個例子是在目前的選擇中新增一個選項,但不會移除已經選中的選項。

Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    const form = $pages.currentPage.forms.getFormByName('Profile Web Form (Enhanced)');
    const control = form && form.getControlByLogicalName('new_areasofinterest');

    if (!control || control.getType() !== 'MultiSelectPicklist') {
        return;
    }

    // 1. Read the options that are currently selected.
    const selectedValues = control.getValue() || [];
    console.log(`Selected options: ${selectedValues.join(', ')}`);

    // 2. Add an option only when it isn't selected yet.
    //    setValue throws an error when a value isn't one of the available options.
    const newsletterOption = 740740002;

    if (!selectedValues.includes(newsletterOption)) {
        control.setValue([...selectedValues, newsletterOption]);
    }

    // 3. Clear the selection.
    // control.setValue([]);
});

使用伺服器上唯讀或隱藏的控制項

Power Pages 會在伺服器套用表單元資料和資料表權限,客戶端 API 無法覆蓋這些設定。 寫防禦性程式碼,檢查控制項是否存在且是否為唯讀,然後再更改它。

以下行為適用:

  • 不在表單上的欄位,或使用者沒有讀取權限的欄位,都不會顯示。 getControlByLogicalName 方法會針對該資料行傳回 undefined,所以在使用前請先檢查結果。
  • 當伺服器上的控制項被鎖定時,例如唯讀表單或欄位上的 多重選取清單,setDisabled(false) 方法不會產生任何效果。
  • 當伺服器需要欄位時,該 setRequired(false) 方法無法將欄位設為可選。
  • 此 setVisible(false) 方法僅在瀏覽器中隱藏控制項。 使用資料表權限和欄位安全來保護資料。 千萬不要依賴隱藏控制來保護資料。
Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    const form = $pages.currentPage.forms.getFormByName('Profile Web Form (Enhanced)');

    if (!form) {
        return;
    }

    const creditLimit = form.getControlByLogicalName('creditlimit');

    // The column isn't on the form, or the user can't read it.
    if (!creditLimit) {
        console.log('The credit limit column is not available to this user.');
        return;
    }

    // A control that's locked on the server stays disabled, even after
    // you call setDisabled(false).
    creditLimit.setDisabled(false);

    if (creditLimit.getDisabled()) {
        console.log('The credit limit column is locked on the server.');
    }

    // Hide the control in the browser. This changes only what people see.
    // Use table permissions and column security to protect the data.
    const internalNotes = form.getControlByLogicalName('new_internalnotes');

    if (internalNotes) {
        internalNotes.setVisible(false);
    }
});

根據另一欄的值將某欄設為必填

此範例僅會在使用者於另一個欄位中選取特定選項時,將某欄設為必填,並新增一個在提交表單時執行的自訂驗證器。 欲了解更多資訊,請參閱 addValidator 方法參數。

Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    const form = $pages.currentPage.forms.getFormByName('Profile Web Form (Enhanced)');

    if (!form) {
        return;
    }

    const contactMethod = form.getControlByLogicalName('preferredcontactmethodcode');
    const mobilePhone = form.getControlByLogicalName('mobilephone');

    if (!contactMethod || !mobilePhone) {
        return;
    }

    const applyRules = () => {
        // Option 3 is Phone in this example.
        const requiresPhone = contactMethod.getValue() === '3';

        // Make the column required and provide a localized message.
        mobilePhone.setRequired(requiresPhone, 'Enter a mobile phone number.');

        if (requiresPhone) {
            // Add a format check that runs when the form is submitted.
            // Reusing the same ID replaces the earlier validator instead of adding another one.
            mobilePhone.addValidator(
                'mobilePhoneFormat',
                (value) => /^(?=.*\d)[0-9\s+()-]{7,20}$/.test((value || '').trim()),
                'Enter a valid mobile phone number.'
            );
        } else {
            mobilePhone.removeValidator('mobilePhoneFormat');
        }
    };

    // Apply the rules when the page loads and whenever a value on the form changes.
    applyRules();
    form.getHtmlElement().addEventListener('change', applyRules);
});

Note

伺服器上必須的欄位仍然存在,即使你呼叫 setRequired(false)。

顯示或隱藏清單中的欄位

此範例隱藏現代清單中的一欄,並重新命名另一欄。 在事件處理程序中讀取清單資料 loaded ,因為每次清單刷新、排序、篩選或分頁資料時,事件會再次發生。 欲了解更多資訊,請參閱 活動列表。

Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    const list = $pages.currentPage.lists.getListById('list_#1');

    if (!list || !list.isModern) {
        return;
    }

    list.on('loaded', () => {
        // Hide a column that people don't need to see.
        const createdOn = list.getColumn('createdon');

        if (createdOn) {
            createdOn.setVisible(false);
        }

        // Rename a column and add a tooltip that screen readers use as the
        // accessible name of the header. Read the configured display name, and
        // then derive the header so that the code produces the same result
        // each time the event occurs.
        const name = list.getColumn('name');

        if (name) {
            name.setHeader(`${name.getDisplayName()} (primary)`);
            name.setTooltip('The primary name of the account.');
        }
    });
});

在列表中顯示或隱藏紀錄

這個範例會隱藏非活躍紀錄,並標示那些無法被編輯的紀錄。 隱藏一列只會改變人們在列表中看到的內容;它不會改變資料或伺服器回傳的記錄數量。

Microsoft.PowerPages.onPagesClientApiReady(async function ($pages) {
    const list = $pages.currentPage.lists.getListById('list_#1');

    if (!list || !list.isModern) {
        return;
    }

    list.on('loaded', () => {
        list.rows.forEach((row) => {
            const state = row.getState();

            // Hide inactive records, where statecode is 1.
            if (state && state.stateCode === 1) {
                row.setVisible(false);
                return;
            }

            // Highlight the records that this user can't edit.
            const privileges = row.getPrivileges();

            if (privileges && !privileges.canWrite) {
                row.addClassName('read-only-row');

                const nameCell = row.getCell('name');

                if (nameCell) {
                    nameCell.setStyle({ fontStyle: 'italic' });
                }
            }
        });
    });
});

重要

利用方法回傳的值 getPrivileges 來改變資料的呈現方式。 不要使用它們來強制實施安全性。 Power Pages 會強制伺服器上的資料表權限。