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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

Retrieve field value from lookup with Javascript

(0) ShareShare
ReportReport
Posted on by 800

Hi, I created below Javascript. The goal of this Javascript is to get a boolean value through the contact lookup and set a boolean on the quick create form:

// GET Lookup
function retrieveContact(executionContext) {

    // Access the field on the form
    var field = executionContext.getFormContext().getAttribute("msevtmgt_contactid");

    // Verify it does exist on the form
    if (field != null) {

        // Get its field value; Returns the Lookup object
        var value = field.getValue();

        // To get the Id, Name and Entity Name (account/contact)
        var record_id = field.getValue()[0].id;
        var record_name = field.getValue()[0].name;
        var record_entityName = field.getValue()[0].entityType;

    }

    function GetRelatedData(executionContext) {
        var formContext = executionContext.getFormContext();

        //
        Xrm.WebApi.retrieveRecord("contact"record_id"?$select=rbc_participant").then(
            function success(result) {
                if (result.rbc_participant == true)
                    formContext.getAttribute(rbc_participantcontact).setValue(true);


            }
            function error(error) {
                Xrm.Navigation.openAlertDialog({
                    text: error.message
                });
            }
        );
    }

}
I can't seem to get it to work. I do not get an error, it does nothing. Does anybody has an idea?
Below a screenshot regarding the form. So when Contact Person contains data and on that record the Participant value == Yes, then the Participant contact? field should set to Yes. This should happen onchange of the Contact Person. So I can't use a workflow.
Participant-Event.png
I have the same question (0)
  • Suggested answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hi,

    You need to call GetRelatedData function from retrieveContact function

    Use below updated code and check.

    // GET Lookup
    function retrieveContact(executionContext) {
    
        // Access the field on the form
        var field = executionContext.getFormContext().getAttribute("msevtmgt_contactid");
    
        // Verify it does exist on the form
        if (field != null) {
    
            // Get its field value; Returns the Lookup object
            var value = field.getValue();
    
            // To get the Id, Name and Entity Name (account/contact)
            var record_id = field.getValue()[0].id;
            var record_name = field.getValue()[0].name;
            var record_entityName = field.getValue()[0].entityType;
            record_id=record_id.replace('{','').replace('}','');
            GetRelatedData(executionContext,record_id);
    
        }
    
        function GetRelatedData(executionContext,record_id) {
            var formContext = executionContext.getFormContext();
    
            //
            Xrm.WebApi.retrieveRecord("contact", record_id, "?$select=rbc_participant").then(
                function success(result) {
                    if (result.rbc_participant == true)
                        formContext.getAttribute(rbc_participantcontact).setValue(true);
    
    
                }
                function error(error) {
                    Xrm.Navigation.openAlertDialog({
                        text: error.message
                    });
                }
            );
        }
    
    }

    If found helpful, Please mark my answer verified.

  • JacquesNL Profile Picture
    800 on at

    Thnx for the quick reply. I am getting these errors when I test both functions:

    ReferenceError: Web resource method does not exist: retrieveContact

    ReferenceError: Web resource method does not exist: GetRelatedData

  • Suggested answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hi,

    Try below code. There was some syntax error in your JS I fixed.

    // GET Lookup
    function retrieveContact(executionContext) {
    
        // Access the field on the form
        var field = executionContext.getFormContext().getAttribute("msevtmgt_contactid");
    
        // Verify it does exist on the form
        if (field != null) {
    
            // Get its field value; Returns the Lookup object
            var value = field.getValue();
    
            // To get the Id, Name and Entity Name (account/contact)
            var record_id = field.getValue()[0].id;
            var record_name = field.getValue()[0].name;
            var record_entityName = field.getValue()[0].entityType;
            record_id=record_id.replace('{','').replace('}','');
            GetRelatedData(executionContext,record_id);
    
        }
    }
    
        function GetRelatedData(executionContext,record_id) {
            var formContext = executionContext.getFormContext();
    
            //
            Xrm.WebApi.retrieveRecord("contact", record_id, "?$select=rbc_participant").then(
                function success(result) {
                    if (result.rbc_participant == true)
                        formContext.getAttribute(rbc_participantcontact).setValue(true);
    
    
                },
                function error(error) {
                    Xrm.Navigation.openAlertDialog({
                        text: error.message
                    });
                }
            );
        }

    Whenever you get this type of error always check syntax of your web resource code online javascript validator tool such as below tool.

    https://esprima.org/demo/validate.html

    If found helpful, Please mark my answer verified.

  • JacquesNL Profile Picture
    800 on at

    Tnx again for the quick reply, still I get an error: UciError: Required parameter is null of undefined: id

    Do I have to declare this var in another way? --> var record_id = field.getValue()[0].id; ?
  • Verified answer
    Guido Preite Profile Picture
    54,086 Moderator on at

    you don't actually need two functions (and although is technically possible I would avoid putting a function nested inside another).

    This code should work, I also put the required lines and fixing some errors (like the quotation marks missing on the boolean field you wanted to set) EDIT: a comma was missing inside the code, I fixed it. EDIT2: I changed another part where you get the initial contactid value

    // GET Lookup
    function retrieveContact(executionContext) {
    	var formContext = executionContext.getFormContext();
        // Access the field on the form
        var fieldValue = formContext.getAttribute("msevtmgt_contactid").getValue();
        // Verify it does exist on the form
        if (fieldValue != null) {
            // To get the Id, Name and Entity Name (account/contact)
            var record_id = fieldValue[0].id;
    		
    		Xrm.WebApi.retrieveRecord("contact", record_id, "?$select=rbc_participant").then(
                function success(result) {
                    if (result.rbc_participant == true) {
                        formContext.getAttribute("rbc_participantcontact").setValue(true);
    				}
                },
                function error(error) {
                    Xrm.Navigation.openAlertDialog({ text: error.message });
                }
            );
        }
    }

  • Verified answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hi,

    I have just verified in my trial instance by changing the lookup field schema to primarycontactid and it seems to be working fine for me.

    below Code working on my trial instance.

    // GET Lookup
    function retrieveContact(executionContext) {
    debugger;
        // Access the field on the form
        var field = executionContext.getFormContext().getAttribute("primarycontactid");
    
        // Verify it does exist on the form
        if (field != null) {
    
            // Get its field value; Returns the Lookup object
            var value = field.getValue();
    
            // To get the Id, Name and Entity Name (account/contact)
            var record_id = field.getValue()[0].id;
            var record_name = field.getValue()[0].name;
            var record_entityName = field.getValue()[0].entityType;
            record_id=record_id.replace('{','').replace('}','');
            GetRelatedData(executionContext,record_id);
    
        }
    }
    
        function GetRelatedData(executionContext,record_id) {
            var formContext = executionContext.getFormContext();
    
            //
            Xrm.WebApi.retrieveRecord("contact", record_id, "?$select=donotphone").then(
        function success(result) {
            var donotphone = result["donotphone"];
            var donotphone_formatted = result["donotphone@OData.Community.Display.V1.FormattedValue"];
        },
        function(error) {
            Xrm.Utility.alertDialog(error.message);
        }
    );
        }

    I would recommend you to debug your javascript. Add debugger same way i added in my javascript. Hit F12 on your browser to open Developer tool then change lookup field value then it should hit your code then check your code line by line to see where it is failing.

    Also try in different browser to check if it is browser issue. Also add check condition after var value = field.getValue(); to check if it contains data. Also keep alert like below .

    alert("check lookup");

    var record_id = field.getValue()[0.id;

    alert(record_id);

    If found helpful, Please mark my answer verified.

  • JacquesNL Profile Picture
    800 on at

    @Bipin and @Guido, thnx a lot for your help! It is working now. Again, thnx for the quick and detailed reply's!

    Br,

    Jacques

  • JacquesNL Profile Picture
    800 on at

    Hi again, the javascript is working great, however, I need to expand the javascript.

    Based on the retrieved values: result.rbc_participant I need to filter a lookup using fetchxml. To be specific, how do I implement this javascript in the existing one:

    function preFilterLookup(executionContext) {
    
        var formContext = executionContext.getFormContext();
        var ParticipantContact = executionContext.getFormContext().getAttribute("rbc_participantcontact").getValue();
        formContext.getControl("msevtmgt_eventid").addPreSearch(function () {
    
            if (ParticipantContact == true) {
                addDefaultLookupFilter(executionContext);
            } else if (ParticipantContact != true) {
    			addLookupFilter(executionContext);
    		}
    
        });
    
    }
    
    function addDefaultLookupFilter(executionContext) {
        var formContext = executionContext.getFormContext();
    
        fetchXmlDefault = ""  
            ""  
            ""  
            ""  
            "";
    
        formContext.getControl("msevtmgt_eventid").addCustomFilter(fetchXmlDefault);
    
    }
    
    function addLookupFilter(executionContext) {
        var formContext = executionContext.getFormContext();
    
        fetchXml = ""  
            ""  
            ""  
            ""  
            ""  
            "";
    
        formContext.getControl("msevtmgt_eventid").addCustomFilter(fetchXml);
    
    }

    Where var ParticipantContact should refer to result.rbc_participant.

    I do not have an error message yet, because I do not know how to merge these two together.

    Br,

    Jacques

  • Suggested answer
    Bipin D365 Profile Picture
    28,983 Moderator on at

    Hi,

    You can modify preFilterLookup method to add one more parameter which is result.rbc_participant and call this function from previous javascript code.

    See below updated code

    function preFilterLookup(executionContext, participant) {
    
        var formContext = executionContext.getFormContext();
        //var ParticipantContact = executionContext.getFormContext().getAttribute("rbc_participantcontact").getValue();
        formContext.getControl("msevtmgt_eventid").addPreSearch(function () {
    
            if (participant == true) {
                addDefaultLookupFilter(executionContext);
            } else if (participant != true) {
    			addLookupFilter(executionContext);
    		}
    
        });
    
    }
    
    function addDefaultLookupFilter(executionContext) {
        var formContext = executionContext.getFormContext();
    
        fetchXmlDefault = ""  
            ""  
            ""  
            ""  
            "";
    
        formContext.getControl("msevtmgt_eventid").addCustomFilter(fetchXmlDefault);
    
    }
    
    function addLookupFilter(executionContext) {
        var formContext = executionContext.getFormContext();
    
        fetchXml = ""  
            ""  
            ""  
            ""  
            ""  
            "";
    
        formContext.getControl("msevtmgt_eventid").addCustomFilter(fetchXml);
    
    }

    Now add below line of code in your prvious javascript inside if condition where you are getting the result.

    preFilterLookup(executionContext, result.rbc_participant);

    If found helpful, Please mark my answer verified.

  • JacquesNL Profile Picture
    800 on at

    Would my code look like this then?

    // GET Lookup
    function retrieveContact(executionContext) {
        var formContext = executionContext.getFormContext();
        // Access the field on the form
        var contactValue = formContext.getAttribute("msevtmgt_contactid").getValue();
        // Verify it does exist on the form
        if (contactValue != null) {
            // To get the Id, Name and Entity Name (account/contact)
            var record_id = contactValue[0].id.replace("{", "").replace("}", "");
    
            if (typeof ($) === 'undefined') {
                $ = parent.$;
                jQuery = parent.jQuery;
            }
    
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: Xrm.Page.context.getClientUrl()   "/api/data/v9.1/contacts("   record_id   ")?$select=rbc_participant",
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                    XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    XMLHttpRequest.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
                },
    
                async: false,
                success: function (data, textStatus, xhr) {
                    var result = data;
                    var rbc_participant = result["rbc_participant"];
                    if (rbc_participant == true) {
                        formContext.getAttribute("rbc_participantcontact").setValue(true);
                        preFilterLookup(executionContext, result.rbc_participant);
    
                    } else if (rbc_participant != true) {
                        formContext.getAttribute("rbc_participantcontact").setValue(false);
                        preFilterLookup(executionContext, result.rbc_participant);
                    }
                },
    
                error: function (xhr, textStatus, errorThrown) {
                    Xrm.Utility.alertDialog(textStatus   " "   errorThrown);
    
                }
    
            });
        }
    }
    
    function preFilterLookup(executionContext, rbc_participant) {
    
        var formContext = executionContext.getFormContext();
        //var ParticipantContact = executionContext.getFormContext().getAttribute("rbc_participantcontact").getValue();
        formContext.getControl("msevtmgt_eventid").addPreSearch(function () {
    
            if (rbc_participant == true) {
                addDefaultLookupFilter(executionContext);
            } else if (rbc_participant != true) {
    			addLookupFilter(executionContext);
    		}
    
        });
    
    }
    
    function addDefaultLookupFilter(executionContext) {
        var formContext = executionContext.getFormContext();
    
        fetchXmlDefault = ""  
            ""  
            ""  
            ""  
            "";
    
        formContext.getControl("msevtmgt_eventid").addCustomFilter(fetchXmlDefault);
    
    }
    
    function addLookupFilter(executionContext) {
        var formContext = executionContext.getFormContext();
    
        fetchXml = ""  
            ""  
            ""  
            ""  
            ""  
            "";
    
        formContext.getControl("msevtmgt_eventid").addCustomFilter(fetchXml);
    
    }

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Pallavi Phade Profile Picture

Pallavi Phade 96

#2
Tom_Gioielli Profile Picture

Tom_Gioielli 69 Super User 2025 Season 2

#3
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 43 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans