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.');
});

팁

논리적 이름을 모를 때 컨트롤을 찾으려면 form.controls와 같이 form.controls.find(control => control.getName() === 'Managing Partner')을(를) 열거하고 getName 메서드를 사용합니다.

조회가 드롭다운 목록으로 렌더링되는 경우 조회 값 설정

조회 열은 양식이 구성된 방식에 따라 모달 대화 상자 또는 드롭다운 목록으로 렌더링됩니다. 두 컨트롤은 setValue 메서드에서 서로 다른 값을 허용하므로 값을 설정하기 전에 isDropdown 속성을 확인하세요. 드롭다운 조회에는 선택할 옵션의 ID가 예상되며 모달 조회에는 개체가 필요합니다.

Important

드롭다운 조회에는 구성된 뷰와 필터가 반환하는 레코드만 포함됩니다. 드롭다운 목록에서 사용할 수 있는 레코드의 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);
});

메모

서버에 필요한 열은 호출 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' });
                }
            }
        });
    });
});

Important

메서드가 반환하는 getPrivileges 값을 사용하여 데이터 표시 방식을 변경합니다. 보안을 적용하는 데 사용하지 마세요. Power Pages 서버에 테이블 권한을 적용합니다.