web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Power Pages
Suggested Answer

Power page forms

(1) ShareShare
ReportReport
Posted on by 6

Hi there,

We’ve built a Power Pages form to allow users to submit extension requests for our department. (Please find a screenshot of the form attached.)The intention is that when a user selects their Contact from the lookup field, the rest of their details (e.g., email, phone, etc.) should auto-populate from their existing record in our CRM. However, we haven't had any success getting this to work so far. Is there a recommended way to achieve this? Ideally, if a contact already exists in the system and the user selects them from the Customer lookup, the form should automatically fill in their associated details, allowing them to simply review and submit.

Any guidance or suggestions would be greatly appreciated.


Kind regards,

 

Categories:
I have the same question (0)
  • Suggested answer
    Jon Unzueta Profile Picture
    1,827 Super User 2025 Season 2 on at
     

    To auto-populate fields on a Power Pages form based on a selected Contact from a lookup field, you can achieve this using JavaScript and Web API calls within Power Pages. Here's a step-by-step guide to help you implement this:


    Goal:

    When a user selects a Contact from a lookup field, the form should automatically populate fields like email, phone, etc., from the selected Contact's record in Dataverse.


    Steps to Implement:

    1. Enable JavaScript on the Form

    In Power Pages:

    • Go to your form in the Design Studio.
    • Under Advanced, enable Custom JavaScript.

    2. Add JavaScript to Fetch Contact Details

    Here’s a sample script you can use:

     

    // Replace 'contactid' with your actual lookup field name

    // Replace 'email', 'telephone1', etc., with your actual field names on the form

    function onContactChange(executionContext) {

        var formContext = executionContext.getFormContext();

        var contactLookup = formContext.getAttribute("contactid").getValue();

        if (contactLookup && contactLookup.length > 0) {

            var contactId = contactLookup[0].id.replace("{", "").replace("}", "");

            Xrm.WebApi.retrieveRecord("contact", contactId, "?$select=emailaddress1,telephone1,firstname,lastname").then(

                function success(result) {

                    formContext.getAttribute("email").setValue(result.emailaddress1);

                    formContext.getAttribute("phone").setValue(result.telephone1);

                    formContext.getAttribute("firstname").setValue(result.firstname);

                    formContext.getAttribute("lastname").setValue(result.lastname);

                },

                function (error) {

                    console.log("Error retrieving contact: " + error.message);

                }

            );

        }

    }

    🏷️ Tag me if you have any further questions or if the issue persists.
    ✅ Click "Accept as Solution" if my post helped resolve your issue—it helps others facing similar problems.
    ❤️ Give it a Like if you found the approach useful in any way.

     

  • MV-09050036-0 Profile Picture
    6 on at
    Hi Jon,
     
    Thank you for the reply. Unfortunately, that didn't work. 
     
    current form in portal

    what we are trying to do is when the contact field is changed - the js looks up the contact & retreives the email & wsu id, & then populates the fields with them. Currently the wsu id is populated on form load & doesn't change. The code above is supposed to clear the fields when the contact is de-selected. At the moment the console log lines are not displaying in the browser dev tools console so hard to troubleshoot.

    contact table email logical name

     

    contact table wsuid logical name

    case table form displaying in portal - contact field event on change

     

     

     

    web resource settings

    console.log("Custom JS loaded");

    // Replace 'contactid' with your actual lookup field name

    // Replace 'email', 'telephone1', etc., with your actual field names on the form

    function onContactChange(executionContext) {

        var formContext = executionContext.getFormContext();

        console.log('Contact change triggered');

     

        var contactLookup = formContext.getAttribute("primarycontactid").getValue();

     

        if (contactLookup && contactLookup.length > 0) {

            // Contact selected

            var contactId = contactLookup[0].id.replace("{", "").replace("}", "");

     

            Xrm.WebApi.retrieveRecord("contact", contactId, "?$select=emailaddress1,mobilephone,new_wsuidn").then(

                function success(result) {

                    console.log("Retrieved contact:", result);

     

                    if (formContext.getAttribute("emailaddress")) {

                        formContext.getAttribute("emailaddress").setValue(result.emailaddress1);

                    }

     

                    // Only set WSUID if it's currently empty

                    var wsuidAttr = formContext.getAttribute("crdff_wsuid");

                    if (wsuidAttr && !wsuidAttr.getValue()) {

                        wsuidAttr.setValue(result.new_wsuidn);

                    }

     

                },

                function (error) {

                    console.error("Error retrieving contact: " + error.message);

                }

            );

        else {

           console.log("No contact selected. Clearing fields.");

     

           const wsuidAttr = formContext.getAttribute("crdff_wsuid");

           if (wsuidAttr) {

               console.log("Before clear:", wsuidAttr.getValue());

               wsuidAttr.setValue(null);

               console.log("After clear:", wsuidAttr.getValue());

           }

       }

    }

     

     

     

  • Suggested answer
    Ajlan Profile Picture
    235 on at
    Hi,
    To achieve this, you’ll need to use the Power Pages Web API and jQuery to get the Contact details when the Customer field changes. Make sure you add below two site settings
     
    Name: Webapi/contacts/enabled 
    Value: true
     
    Name: Webapi/contacts/fields
    Value: (Over here add logical name of fields which you are using) (For example: fullname,emailaddress1,mobilephone)
     
     
    $(document).ready(function () {
        (function (webapi, $) {
            function safeAjax(ajaxOptions) {
                var deferredAjax = $.Deferred();
                shell.getTokenDeferred().done(function (token) {
                    ajaxOptions.headers = ajaxOptions.headers || {};
                    ajaxOptions.headers["__RequestVerificationToken"] = token;
                    $.ajax(ajaxOptions)
                        .done(deferredAjax.resolve)
                        .fail(deferredAjax.reject);
                }).fail(function () {
                    deferredAjax.rejectWith(this, arguments);
                });
                return deferredAjax.promise();
            }
     
            window.webapi = window.webapi || {};
            window.webapi.safeAjax = safeAjax;
        })(window.webapi = window.webapi || {}, jQuery);
     
        // Create an async handler for the change event
        $('#customerField').on('change', async function () {
            const contactId = $(this).val();
            if (!contactId) return;
     
            const url = `/_api/contacts(${contactId})?$select=fullname,emailaddress1,mobilephone`;
     
            try {
                const data = await webapi.safeAjax({
                    type: "GET",
                    url: url,
                    contentType: "application/json"
                });
     
                // Populate your form fields
                $('#contactNameField').val(data.fullname || '');
                $('#contactEmailField').val(data.emailaddress1 || '');
                $('#contactPhoneField').val(data.mobilephone || '');
            } catch (error) {
                console.error("Error retrieving contact:", error);
            }
        });
    });
     
    Cheers! 🎉
  • Suggested answer
    Fubar Profile Picture
    8,354 Super User 2025 Season 2 on at
    First question I have is is this a public website or is the user logged in?
     
    If public, please be aware of privacy as you are exposing a list of Contacts to the world (and also, if then using the Portals Web API ensure the exposed fields are limited and appropriate permissions are in place as a hacker will be able to query your contacts table using the permissions and exposed fields).
     
    If the user is logged in then you do not need the dropdown as you have access in Liquid to the 'user' object (which is the Contact record, and so can use liquid to get the values you need and javascript/JQuery to populate the fields), similarly you can use form/step Metadata on the form to populate fields where the data is on the currently logged in user record (configure metadata on the form/step definition via the Power Pages Management App ).
     
    If you do use a Lookup, as you want to edit you would either need to go to another form to do the edit or use the Portals Web API  (which previous poster has responded), if you just need to display the values (readonly) you can configure a Quick View form in Dataverse.
     
     
     
  • Suggested answer
    CU19050439-0 Profile Picture
    2 on at
    Hi there, I hope you have already found the result to this. If not, please refer to my article on LinkedIn: https://www.linkedin.com/posts/soumya-das-_powerplatform-powerpages-lowcode-activity-7338452148344541184-wn9u?utm_source=share&utm_medium=member_desktop&rcm=ACoAADkdOwIBlvPvmZZNHk7Gr_s4Jfwi7VEbhHs


    It has 3 approaches to solve this problem:
    ✅ No-code method
    ✅ Server-side with Liquid
    ✅ JavaScript (my go-to)
     

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Forum hierarchy changes are complete!

In our never-ending quest to improve we are simplifying the forum hierarchy…

Ajay Kumar Gannamaneni – Community Spotlight

We are honored to recognize Ajay Kumar Gannamaneni as our Community Spotlight for December…

Leaderboard > Power Pages

#1
Fubar Profile Picture

Fubar 74 Super User 2025 Season 2

#2
Jerry-IN Profile Picture

Jerry-IN 55

#3
sannavajjala87 Profile Picture

sannavajjala87 31

Last 30 days Overall leaderboard