Skip to main content
Community site session details

Community site session details

Session Id :
Service | Customer Service, Contact Center, Fie...
Suggested answer

Set lookup field using Javascript without ID

(0) ShareShare
ReportReport
Posted on by 32

Hi,

Is it possible to set a lookup value based on another field wihtout setting an ID? I have all my order updating using power query, but i need to link each order line to an order using the order number. At the moment, the order number is recorded on the order line, but i need to set the lookup to the order number to link all order lines to an order.

I have attached a screenshot below, basically all i need is for the Unleashed Invoice number (lookup field) to be set to the Name.

I know i can get a lookup using javascript, but at the moment, nothing is set in Unleashed Invoice as i cannot set the lookup field using the Power Query import.

Screen-Shot-2020_2D00_02_2D00_17-at-1.42.43-pm.png

  • Suggested answer
    LeoAlt Profile Picture
    16,331 Moderator on at
    RE: Set lookup field using Javascript without ID

    Hi partner,

    Plug-in is a custom business logic which is developed by C# and can be integrated with D365 and be used to do some custom actions like create/modify/delete/query records automatically when the trigger conditions are met.

    You could refer to the following steps.

    1.Create a plug-in with C#. The code logic is when orders are updated, the plug-in will get the order number of the record and query order lines with the same order number of the order record and then set the order record as a value to lookup filed on order line form. 

    I've wrote a sample code for your reference.

    using System;
    using System.Linq;
    using System.ServiceModel;
    
    // Microsoft Dynamics CRM namespace(s)
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    
    namespace CRMPlugin
    {
        public class Test4s : IPlugin
        {
            /// 
            /// A plug-in that updates lookup field in orderline when updating orders.
            /// 
            /// Register this plug-in on the Update message, order entity,
            /// and asynchronous mode.
            /// 
            public void Execute(IServiceProvider serviceProvider)
            {
                //Extract the tracing service for use in debugging sandboxed plug-ins.
                ITracingService tracingService =
                    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    
                // Obtain the execution context from the service provider.
                IPluginExecutionContext context = (IPluginExecutionContext)
                    serviceProvider.GetService(typeof(IPluginExecutionContext));
                // Obtain the organization service reference.
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
    
                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];
    
                    // Verify that the target entity represents an order.
                    // If not, this plug-in was not registered correctly.
                    if (entity.LogicalName != "order")
                        return;
    
                    try
                    {
                        //get the order number of order record,you should replace the field name with your correct field name in your order entity
                        string orderNumber = entity.Attributes["new_orderNumber"].ToString();
                        //get the order ID
                        string orderId = entity.Id.ToString();
    
                        //query order lines whose order number is the same as the order
                        var query = new QueryExpression("orderline")
                        {
                            ColumnSet = new ColumnSet("orderlineid"),
                            Criteria = new FilterExpression(LogicalOperator.And),
                            TopCount = 50
                        };
                        //add query condition if orderNumber(orderline) equals orderNumber(order)
                        query.Criteria.AddCondition("ordernume", ConditionOperator.Equal, orderNumber);
                        EntityCollection results = service.RetrieveMultiple(query);
    
                        results.Entities.ToList().ForEach(x =>
                        {
                            string orderlineId = x.Attributes["orderlineid"].ToString();
                            //update the orderline lookup field
                            var retrieveOrderLine = new Entity("orderline", new Guid(orderlineId));
                            var orderLine = new Entity("orderline");
                            orderLine.Id = retrieveOrderLine.Id;
                            //set the lookup value
                            orderLine["lookupfield"] = new EntityReference("orderline",new Guid(orderId));
                            service.Update(orderLine);
                        });
    
    
    
                        // Create the contact in Microsoft Dynamics CRM.
                        tracingService.Trace("TestPlug: Updating the OrderLine.");
                    }
                    catch (FaultException ex)
                    {
                        throw new InvalidPluginExecutionException("An error occurred", ex);
                    }
    
                    catch (Exception ex)
                    {
                        tracingService.Trace("TestPlug: {0}", ex.ToString());
                        throw;
                    }
                }
            }
        }
    }

    2.And you need to register this plug-in with pluginregisterationtool.

    For more steps, please refer to the following blogs.

    https://carldesouza.com/deploying-plugin-across-different-dynamics-365-environments/

    https://docs.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/register-deploy-plugins

    https://crmbook.powerobjects.com/extending-crm/plug-in-development-and-workflow-extensions/plug-ins/registering-and-deploying-plug-ins/

    Hope it helps.

    Best Regasrds,

    Leo

  • lachie1992 Profile Picture
    32 on at
    RE: Set lookup field using Javascript without ID

    Hey Leo!

    Thanks for your reply, ive been playing around with the web api today with not a whole lot of luck.

    Your understanding is 100% correct, i would love to be able to set the lookup field automatically when updating with power query but i didnt think that was possible? I am not given any lookup fields when using power query. What plug in is it??

    Thanks!

    Lach

  • LeoAlt Profile Picture
    16,331 Moderator on at
    RE: Set lookup field using Javascript without ID

    Hi partner,

    Unfortunately, we could not set lookup value without record ID, it is no allowed in D365 :-(

    If you want to get the order id on the order line form according order number, you could use web api to do this.

    function getValueFromLookUp(executionContext){
        var formContext=executionContext.getFormContext();
        //get order number
        var Number=formContext.getAttribute("Name");
        if(Number!=null){
            //use record id to retrieve order id
            Xrm.WebApi.retrievemultipleRecord("order","?$select=orderid&$filter=name eq " Number).then(
                function success(result){
                    //get the orderid value and set it to cat_food field
                    var orderid=result.orderid;
                    //set the lookup value with orderid and order name
                    ....
                },
                function (error){
                    console.log(error.message);
                }
            )
    
        }
        
    }

    If you want D365 to set the lookup field automatically when updating orders by power query, you could use plug-in to do this.

    And if my understanding is not correct, please feel free to let me know and providing more details.

    Best Regards,

    Leo

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

News and Announcements

Now Available: 2025 Release Wave 2

Quick Links

Ramesh Kumar – Community Spotlight

We are honored to recognize Ramesh Kumar as our July 2025 Community…

Congratulations to the June Top 10 Community Leaders!

These are the community rock stars!

Announcing the Engage with the Community forum!

This forum is your space to connect, share, and grow!

Leaderboard > Service | Customer Service, Contact Center, Field Service, Guides

#1
Muhammad Shahzad Shafique Profile Picture

Muhammad Shahzad Sh... 51 Most Valuable Professional

#2
Ramesh Kumar Profile Picture

Ramesh Kumar 42

#3
David Shaw_UK Profile Picture

David Shaw_UK 27

Featured topics

Product updates

Dynamics 365 release plans