Are you looking to access primary entity and related entity data in single query using OData then this post is for you.
If we need to access related entity data, we can use expend open in our odata query, we need to specify relationship name, in below example I am fetching data from account and more address entity and relationship name for this is “Account_CustomerAddress”. Here is the code to get entity information:
function GetRelated() {
var context = Xrm.Page.context;
var EntityID = Xrm.Page.data.entity.getId();
var serverUrl = context.getServerUrl();//for CRM 2013 and later use getClientUrl()
var ODataPath = serverUrl + “/XRMServices/2011/OrganizationData.svc”;
var retrieveResult = new XMLHttpRequest();
retrieveResult.open(“GET”, ODataPath + “/AccountSet?$filter=AccountId eq (guid'” + EntityID + “‘)&$expand=Account_CustomerAddress”, false);
retrieveResult.setRequestHeader(“Accept”, “application/json”);
retrieveResult.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
retrieveResult.send();
if (retrieveResult.readyState == 4 /* complete */) {
if (retrieveResult.status == 200) {
var retrieved= this.parent.JSON.parse(retrieveResult.responseText).d;
var Result = retrieved.results[0];
//Field From Account
alert(Result.Name);
//fields from more address
alert(Result.Account_CustomerAddress.results[0].Line1);
}
}
}
Hope it will help.
Enjoy!!!
Note: if you will copy this code please make sure to change quotes.
Hello Mahneder Pal,
I am using your code .. Kept eye on your Note.(Change quote)
All working fine..
My primary entity is Order and related entity is Product (1 Order : N Product).
I have used below url..
var url = ODataPath + “/OrderSet?$filter=salesorderid eq (guid’” + EntityID + “‘)&$expand=order_details”;
But i am getting 404: Not Found.
Is anything wrong in url ?
Did you try to browse this url, you should get list of records while you will browse this url.
thank u so much sir
Very good post. This helped med a lot, I really didn’t want to do a fetchxml-query with js.
How to get the id of a primary entity in related entity. For eg how to get order ID in order Product ID.
I hope you are asking to get it in Client side, you you can simply write below script in your order product form
var ID = Xrm.Page.getAttribute(“orderid”).getValue();
But make sure you have updated rollup installed because initially there was issue (which is fixed), where you will get this order id only when order product is created
Thanks a lot. It helped me with my problem.