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

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Autofill a lookup field based on another lookup field

(0) ShareShare
ReportReport
Posted on by 47

I need to autofill this field when the parent field contains data without click and selecting the field related, theres always only a result related, I already research I know a Javascript code must be load on onChange-field and I have to use a Web API but I dont know how to do that, the code I found doesnt work with me, I dont know what I am doing wrong. I am stuck on this. 

Any help will be appreciate.

I found this code and I adapted but doesn't work.

_____________________

function setExpenseCategorybasedonVendor() {
var lookup1 = Xrm.Page.getAttribute("new_cdigodesocio").getValue()[0].id;
var clientUrl = Xrm.Page.context.getClientUrl();
var query = clientUrl + "/api/data/v8.0/new_membresacliente(" + lookup1.slice(1, -1) + ")?$select=_new_cuenta_value";
makeRequest('GET', query)
.then(function (res) {
var res2 = JSON.parse(res);
var guid = res2._cse_expense_category_value;
var query2 = clientUrl + "/api/data/v8.0/new_membresacliente(" + guid + ")?$select=cse_name";
makeRequest('GET', query2)
.then(function (response) {
var res3 = JSON.parse(response);
var value = new Array();
value[0] = new Object();
value[0].id = guid;
value[0].name = res3.cse_name;
value[0].entityType = "new_membresacliente";
Xrm.Page.getAttribute("new_cuenta").setValue(value);
})
.catch(function (err) {
console.error('there was an error!', err.statusText);
});
})
.catch(function (err) {
console.error(' there was an error!', err.statusText);
});
}

________________________

5305.PNG
Error.
3733.png
1185.png

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi,

    The error message is saying "makeRequest" method is not defined. Do you have this method in your java script library.

    It is possible that when you copied the code you haven't copied the complete script.

    For Web API, I would suggest you to download Rest Builder tool and generate your request. This will be the easer then changing some existing code.

    Refer this carldesouza.com/.../

    You can download the tool here- github.com/.../releases

    By the way, what is the field y=name on your parent entity which you want to copy? new_cuenta is the name of the field where you want to copy, what is the name on the parent entity for this field?

    Hope this helps.

  • neryhumberto Profile Picture
    47 on at

    I really dont have any idea how to use it, I'm new on JS, what I have to put on "Id To Retrieve"?

    New_cuenta is the name of the field where I want to paste the account id related from new_cdigodesocio.

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    So new_cuenta is the name of the field on your parent entity which you want to copy and also the name of the field on your child entity where you want to copy?

  • neryhumberto Profile Picture
    47 on at

    Hi Ravi, how are you?

    So "new_membresacliente" is the schema name of the main entity wich contains a lookup field to "parentaccountid" that is a normal account.

    I am working on another entity in a form wich contains "new_cdigodesocio" that is a lookup field that is related with the name of record on "new_membresacliente" entity, also this form contains a lookup field called "new_cuenta" to account entity wich is releated with the record selected in "new_cdigodesocio" on the same form. I just want to get the name of the account related from "new_cdigodesoscio" to "new_cuenta" automatically.

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi,

    ""new_membresacliente" is the schema name of the main entity wich contains a lookup field to "parentaccountid" " - This cannot be true because if your entity schema name staryts with new_ (or any other prefix) then the field name should also start with some prefix like new_account etc.

    Can you please check again what is the schema name of the account field on your parent entity "new_membresacliente"

  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    You can refer this blog which has the exact code you are looking for. You need to replace the schema name as per your entity.

    community.dynamics.com/.../get-lookup-value-from-other-entity-and-set-it-on-the-form-using-web-api-in-microsoft-dynamics-crm

    If you still face issue, I would suggest to build the query in rest Builder as it will automatically use the correct field name. In the tool, select Endpoint: Web API;

    Action: Retrieve Single;

    Primary Entity: Select parent entity from where you want to copy the field;

    Id to Retrieve: Put anything e.g. 123 [We need to pass this id from code

    Field to select: select the field you want to copy

    Once done, click 'Create Request', this will generate the web api code for you to retrieve your parent entity record with the id you have passed. You replace this code in the above blog. You can share it here as well if you want further help.

    Hope this helps.

  • neryhumberto Profile Picture
    47 on at

    Hi Ravi, thanks for you response.

    "So new_cuenta is the name of the field on your parent entity which you want to copy and also the name of the field on your child entity where you want to copy?"

     - You were right "new_cuenta" is the name of the lookup field to Account in both forms.

    I tried the code of the another thread, but unfortunaly doesn't work. I bet I am missing something.

    ______________________________________________

    function yourFunctionName() {

    var lookup= Xrm.Page.getAttribute(“new_cdigodesocio”).getValue();
    var newid = lookup[0].id.slice(1, -1);

    var req = new XMLHttpRequest();

    req.open(“GET”, Xrm.Page.context.getClientUrl() + “/api/data/v8.1/ new_membresaclientes(” + newid + “)?$select=_prefix_ new_cuenta_value”, true);
    req.setRequestHeader(“OData-MaxVersion”, “4.0”);
    req.setRequestHeader(“OData-Version”, “4.0”);
    req.setRequestHeader(“Accept”, “application/json”);
    req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
    req.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);
    req.onreadystatechange = function () {
    if (this.readyState === 4) {
    req.onreadystatechange = null;
    if (this.status === 200) {
    var result = JSON.parse(this.response); 

    var retrivedvalue= result._prefix_new_cuenta_value;
    var retrivedformatedvalue= result[“_prefix_new_cuenta_value@OData.Community.Display.V1.FormattedValue”];
    if (retrivedvalue!= null) {

    var value = new Array();
    value[0] = new Object();
    value[0].id = retrivedvalue;
    value[0].name = retrivedformatedvalue;
    value[0].entityType = “new_membresaclientes”;

    Xrm.Page.getAttribute(“new_cuenta”).setValue(value);
    }
    else
    alert(“some textt!!!!!!”)
    } else {
    Xrm.Utility.alertDialog(this.statusText);
    }
    }
    };
    req.send();

    }

    2337.PNG

    ______________________________________________


    I also followed your steps and I generated the code with the tool, that is this code above:

    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/new_membresaclientes(123)?$select=_new_cuenta_value", true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function() {
    if (this.readyState === 4) {
    req.onreadystatechange = null;
    if (this.status === 200) {
    var result = JSON.parse(this.response);
    var _new_cuenta_value = result["_new_cuenta_value"];
    var _new_cuenta_value_formatted = result["_new_cuenta_value@OData.Community.Display.V1.FormattedValue"];
    var _new_cuenta_value_lookuplogicalname = result["_new_cuenta_value@Microsoft.Dynamics.CRM.lookuplogicalname"];
    } else {
    Xrm.Utility.alertDialog(this.statusText);
    }
    }
    };
    req.send();

    
    

    Settings:

    1v1.png

  • Suggested answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi,

    The error you are getting is "<yourfunctionname> not defined at eval". This error is mostly to be occurred because of the below 2 reason-

    1) You have made changes to your JavaScript library like added a function and have register it on form load, onchange etc but due to caching your browser is loading the old version which did not have this function before.

    2) You have some syntax error in your JavaScript file due to which browser failed to load that JavaScript file

    Now in both the above scenario, CRM is expecting to call your function but it couldn't find that function hence it is throwing the error saying <function name> not found.

    To validate & fix the first scenario, do publish all customization, close your browser session and try agin in a new browser session. Alternatively you can clear browser cache (Google on how to clear browser cache if you are not already aware) or open your CRM in Incognito/ In private session and check again.

    After performing the above, the issue will be fixed most liekly but if you are still getting the same error i.e. "<function name> not defined at eval", you are most likely hitting a second scenario where there is a syntax error in your JavaScript library. Do not that after the first scenario, you may get some other error which requires different fix, this one is for the exact same error message.

    Now to fix the second scenario, you can use need to review your code and find ou the systax error. Most common problem are missing quotes, commas etc. This can be easily validated by opening your code either in visual studio or any other code editor tool. You can also use Online JavaScript Syntax validator - esprima.org/.../validate.html

    Coming back to your code, I verified your code in my visual studio and there were some syntax error. I have updated the code. Could you please try this again and check. Do remember to publish customization and try it in  a new browser session just to rule out any caching issues.

    ========================

    function yourFunctionName() {  

       var lookup = Xrm.Page.getAttribute("new_cdigodesocio").getValue();

       var newid = lookup[0].id.slice(1, -1);

       var req = new XMLHttpRequest();

       req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/new_membresaclientes(" + newid + ")?$select=_new_cuenta_value", true);

       req.setRequestHeader("OData-MaxVersion", "4.0");

       req.setRequestHeader("OData-Version", "4.0");

       req.setRequestHeader("Accept", "application/json");

       req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

       req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

       req.onreadystatechange = function () {

           if (this.readyState === 4) {

               req.onreadystatechange = null;

               if (this.status === 200) {

                   var result = JSON.parse(this.response);

                   var _new_cuenta_value = result["_new_cuenta_value"];

                   var _new_cuenta_value_formatted = result["_new_cuenta_value@OData.Community.Display.V1.FormattedValue"];

                   var _new_cuenta_value_lookuplogicalname = result["_new_cuenta_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

                   if (_new_cuenta_value != null) {

                       var value = new Array();

                       value[0] = new Object();

                       value[0].id = _new_cuenta_value;

                       value[0].name = _new_cuenta_value_formatted;

                       value[0].entityType = _new_cuenta_value_lookuplogicalname;

                   }

                   else {

                       alert("Error: No account found to copy!");

                   }

               } else {

                   Xrm.Utility.alertDialog(this.statusText);

               }

           }

       };

       req.send();

    }

    ========================

    Hope this helps.

  • neryhumberto Profile Picture
    47 on at

    Hi Ravi, how are you? I did all the recomendations, publish all customizations, clear cache, use incognito mode. I added the new code, doesn't show any error but doesn't work either. If I select a record then I delete it shows this error. Should I use xrm.webapi on rest tool?

    1185.1v1.PNG

    I really appreciate the time you already took on this, so grateful.

  • Verified answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Can you please try this? Made some change to avoid the erro you get on clearing and also added the statment to populate the field value after retrieving (forget that last time).

    ==========================

    function yourFunctionName() {  

       var lookup = Xrm.Page.getAttribute("new_cdigodesocio").getValue();

       var newid = lookup[0].id.slice(1, -1);

       var req = new XMLHttpRequest();

       req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/new_membresaclientes(" + newid + ")?$select=_new_cuenta_value", true);

       req.setRequestHeader("OData-MaxVersion", "4.0");

       req.setRequestHeader("OData-Version", "4.0");

       req.setRequestHeader("Accept", "application/json");

       req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

       req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");

       req.onreadystatechange = function () {

           if (this.readyState === 4) {

               req.onreadystatechange = null;

               if (this.status === 200) {

                   var result = JSON.parse(this.response);

                   var _new_cuenta_value = result["_new_cuenta_value"];

                   var _new_cuenta_value_formatted = result["_new_cuenta_value@OData.Community.Display.V1.FormattedValue"];

                   var _new_cuenta_value_lookuplogicalname = result["_new_cuenta_value@Microsoft.Dynamics.CRM.lookuplogicalname"];

                   if (_new_cuenta_value != null && _new_cuenta_value[0] != null) {

                       var value = new Array();

                       value[0] = new Object();

                       value[0].id = _new_cuenta_value;

                       value[0].name = _new_cuenta_value_formatted;

                       value[0].entityType = _new_cuenta_value_lookuplogicalname;

                       Xrm.Page.getAttribute("new_cuenta").setValue(value);

                   }

                   else {

                       alert("Error: No account found to copy!");

                   }

               } else {

                   Xrm.Utility.alertDialog(this.statusText);

               }

           }

       };

       req.send();

    }

    ==========================

    Do remember to clear cache..

    Hope this helps

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

Introducing the 2026 Season 1 community Super Users

Congratulations to our 2026 Super Stars!

Meet the Microsoft Dynamics 365 Contact Center Champions

We are thrilled to have these Champions in our Community!

Congratulations to the March Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
AS-17030037-0 Profile Picture

AS-17030037-0 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans