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 :
Microsoft Dynamics CRM (Archived)

JavaScript: Object reference not set to an instance of an object

(0) ShareShare
ReportReport
Posted on by

The script  was created using Rawish Kumars example.  It fails with the general error "Internal Server Error."  From debugger mode, "req:XMLHttpRequest: response" indicates the error is "Object reference not set to an instance of an object".


**** Begin of script

function VPNApplicable_Opt() {
debugger;
    
    var fieldValueToCopy  = Xrm.Page.getAttribute("new_2vpnapplicable").getValue();
    var lookupObj = Xrm.Page.getAttribute("objectid").getValue();
    var newid = lookupObj[0].id.slice(1, -1); // you will get perfect id like "EDCJDKDJDKJDJDKJDJKD" here.

    var req = new XMLHttpRequest();
    /*
    var primaryProjectId;
    EntityReference  primaryProjectId = new EntityReference ("msdyn_projects", newid);
    console.log(primaryProjectId);
    
    queueitem["primaryProjectId"] = primaryProjectId;    
    */
    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/msdyn_projects(" + newid + ")?$select=new_2vpnapplicable$expand=msdyn_project_QueueItems($select=objectid)", true);
    /*
    var url = Xrm.Page.context.getClientUrl() + "/api/data/v9.0/msdyn_projects(" + newid + ")?$select=new_2vpnapplicable, projectid$expand=msdyn_project_QueueItems($select=objectid)";
    console.log(url);
    req.open("GET", url, 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); // you will get the retrieved value in object we stored in result var.

                var retrivedvalue = result.new_2vpnapplicable; //get the id of the field
                //var retrivedformatedvalue = result["new_2vpnapplicable@OData.Community.Display.V1.FormattedValue"]; //get the formatted name of the field
                if (retrivedvalue != null) {
                    var value = new Array();
                    value[0] = new Object();
                    value[0].id = retrivedvalue;
                    //value[0].name = retrivedformatedvalue;
                    value[0].entityType = "msdyn_projects";
                    // console.log(value[0]);
                    Xrm.Page.get

Attribute("new_2vpnapplicable").setValue(fieldValueToCopy); //set the lookup value finally
                } else
                    alert("some textt!!!!!!") // optional
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send();
}

****** End of script

I tested the URL and got the desired results:

*** URL results

@odata.context "xxxxxxxxxxxxxxxx.crm.dynamics.com/.../v9.0$metadata#msdyn_projects(new_2vpnapplicable)/$entity"

@odata.etag "W/\"17715491\""

new_2vpnapplicable 100000001

msdyn_projectid "089cc620-95c8-e711-8119-e0071b6a5d41"

**** end link

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    a33ik Profile Picture
    84,331 Most Valuable Professional on at

    Hello,

    It's a bit hard to go through your code and find an error when system is not available. And the code is not the easiest one. I would highly recommend to master JavaScript troubleshooting - docs.microsoft.com/.../debug-javascript-code

    I understand that it's time investment but believe me - it'll help you in future.

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

    Based on the error message, I suspect some internal plugin is triggering which is causing this issue. I would suggest to try the same action i.e. set the same value to the same project record from UI and see if it works. If you get the same error then investigate/ troubleshoot that first.

    Also, in your script, you are setting the same value in the lookup which you have retrieved so worth check that piece of code.

    Hope this helps.

  • Community Member Profile Picture
    on at

    Hello Ravi,

    Thank you for your recommendation, though I do not understand it - "set the same value to the same project record from UI."

    The script is depicted above, can you inform me as to what line(s) of code need to be changed?

    Thank you,

    Lannie

  • RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi Lannie,

    I need to you do the same thing directly in CRM which you are doing with the script. So if you are setting a lookup field values, try to set the same value in CRM manually and see if it works.

  • Community Member Profile Picture
    on at

    Hello Ravi,

    Affirmative, I can manually change the field "new_2vpnapplicable" in Project. 
    I modified the script since the last posting, it is below:

    **********************  Script begin **************

    function VPNApplicable_Opt() {
    debugger;
        var fieldValueToCopy  = Xrm.Page.getAttribute("new_2vpnapplicable").getValue();
        var lookupObj = Xrm.Page.getAttribute("objectid").getValue();
        var newid = lookupObj[0].id.slice(1, -1);     // you will get perfect id like "EDCJDKDJDKJDJDKJDJKD" here.
        var req = new XMLHttpRequest();
     

       req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/msdyn_projects(" + newid + ")?$select=new_2vpnapplicable", true);
        /*
        var url = Xrm.Page.context.getClientUrl() + "/api/data/v9.0/msdyn_projects(" + newid + ")?$select=new_2vpnapplicable";
        console.log(url);
        req.open("GET", url, 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); // you will get the retrieved value in object we stored in result var.

                    var retrivedvalue = result.new_2vpnapplicable; //get the id of the field
                    //var retrivedformatedvalue = result["new_2vpnapplicable@OData.Community.Display.V1.FormattedValue"]; //get the formatted name of the field
                    if (retrivedvalue != null) {
                        var value = new Array();
                        value[0] = new Object();
                        value[0].id = retrivedvalue;
                        //value[0].name = retrivedformatedvalue;
                        value[0].entityType = "msdyn_projects";
                        // console.log(value[0]);
                        Xrm.Page.getAttribute("new_2vpnapplicable").setValue(fieldValueToCopy);   //set the lookup value finally
                    } else
                        alert("some textt!!!!!!") // optional
                } else {
                    Xrm.Utility.alertDialog(this.statusText);
                }
            }
        };
        req.send();
    }

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

    What error you are getting now with this script? And what exactly you are trying with script? Are you using it to update threcord using WEB API or retrieve a record from web api and populate in the form? Asking because you are using PATCH instead of GET as opposed to what is used in the example here community.dynamics.com/.../get-lookup-value-from-other-entity-and-set-it-on-the-form-using-web-api-in-microsoft-dynamics-crm

  • Community Member Profile Picture
    on at

    The alert pop-up states "Internal Server Error."  Using debugger, the value of "response:"  is:

    response: "{\"error\":{\"code\":\"0x0\",\"message\":\"Object reference not set to an instance of an object.\",\"innererror\":{\"message\":\"Object reference not set to an instance of an object.\",\"type\":\"System.NullReferenceException\",\"stacktrace\":\" at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.ValidatePatchInputProperties(EdmEntityObject entityDelta, CrmODataExecutionContext crmODataExecutionContext)\\r\\n at Microsoft.Crm.Extensibility.OData.EntityController.PatchEntityImplementation(String& entityName, String key, EdmEntityObject entityDelta)\\r\\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\\r\\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\\r\\n at lambda_method(Closure , Object , Object[] )\\r\\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\\r\\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---\\r\\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()\"}}}"

    ​​*** end of response

    Task:

    I am retrieving the value of an option field (new_2vpnapplicable) in Queue Items and populating a field in Projects with the same name and type.  I am using "PATCH" because I was following an example by Rawish Kumar - https://community.dynamics.com/crm/b/passiondynamics/archive/2018/01/13/get-lookup-value-from-other-entity-and-set-it-on-the-form-using-web-api-in-microsoft-dynamics-crm

  • Community Member Profile Picture
    on at

    Using GET instead of PATCH resolved the problem.

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 > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans