Automatically fill in a custom entity using JavaScript even when the GUID of the parent entity is unknown within Dynamics 365

Recently delving into client-side scripting, I have been tirelessly searching through Google and various communities for answers without success. Allow me to present my issue for a clearer understanding of the predicament.

I have established two custom entities called cts_agent and cts_cases. My goal is to automatically populate all fields in cts_cases that are read-only, with the exception of the agent id field (a whole number) which is linked to the cts_agent entity form.

If it were an entity reference field, I could use a query expression to retrieve details from the agents_form and populate the information in my cts_form. However, I need to write a JavaScript query that can take the agent id, fetch the details, and present them in a JSON format to populate the cts_cases form. This dynamic retrieval of guid value and auto-populating cts_cases with JSON data present two challenges that I am struggling to overcome. I have managed to code a static version:

var req = new XMLHttpRequest();

req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/cts_agents(00000000-0000-0000-0000-000000000000)?$select=cts_addressline1,cts_addressline2,cts_addressline3,cts_city,cts_country,cts_email,cts_fax,cts_mobilenumber,cts_name,cts_phonenumber,cts_state,cts_zipcode", 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 cts_addressline1 = result["cts_addressline1"];

        var cts_addressline2 = result["cts_addressline2"];

        var cts_addressline3 = result["cts_addressline3"];

        var cts_city = result["cts_city"];

        var cts_country = result["cts_country"];

        var cts_email = result["cts_email"];

        var cts_fax = result["cts_fax"];

        var cts_mobilenumber = result["cts_mobilenumber"];

        var cts_name = result["cts_name"];

        var cts_phonenumber = result["cts_phonenumber"];

        var cts_state = result["cts_state"];

        var cts_zipcode = result["cts_zipcode"];

        var cts_zipcode_formatted = result["Email"];

    } else {

        Xrm.Utility.alertDialog(this.statusText);

    }

}

};

req.send();

Answer №1

One option is to set up a filter in the arguments. Another approach is to utilize the various Xrm.WebApi functions for a more straightforward query syntax.

$filter=agentid eq 123
//where agentid represents your integer identifier field

For instance:

Xrm.WebApi.retrieveMultipleRecords("cts_agent","?$select=cts_addressline1,cts_addressline2,cts_addressline3,cts_city,cts_country,cts_email,cts_fax,cts_mobilenumber,cts_name,cts_phonenumber,cts_state,cts_zipcode&$filter=agentid eq 123")
.then(
result => {
//you can access the results here - retrieve multiple returns an array of records.
if(result.entities.length > 0)
{
var cts_addressline1 = result.entities[0].cts_addressline1;
//etc...
}
},
err => {
console.error(err);
});

If you need the unique id (guid) of the agent, you can simply retrieve it from result.entities[0].cts_agentid

Answer №2

Facing obstacles with dynamically retrieving the guid value and automatically populating the cts_cases with json data

For the first issue, you previously received assistance from another source. As explained, you can query the entity record using any unique attribute value you have.

Regarding the second part - once you have obtained the guid, you can pass it as a parameter to Xrm.Navigation.openForm to open the cts_cases entity form. Upon form load, utilize this parameter to retrieve details from the agent record and assign the json attribute values to the corresponding cts_cases form fields. Alternatively, you can also pass the values as parameters while opening the form for minimal attributes. Learn more

var entityFormOptions = {};
entityFormOptions["entityName"] = "cts_cases";

// Setting default values for the Contact form
var formParameters = {};
formParameters["cts_addressline1"] = result["cts_addressline1"]
//other attributes can be added here

// Opening the form.
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
    function (success) {
        console.log(success);
    },
    function (error) {
        console.log(error);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to fetching a JSON Object from a URL using Node.js and Express

As a newcomer to Node.js and Express, I am venturing into my first real project with these technologies. In this simple Node.js/Express project, my goal is to retrieve a JSON object from a URL. Additionally, I plan to create another URL that shows HTML co ...

Getting the value of a property from a dynamic object that has a keyword as its name

When attempting to access a property of a JSON object using Newtonsoft's Json.NET library, I encountered the following issue: using Newtonsoft.Json.Linq; dynamic myJsonData = JObject.Parse("{ \"out\":123, \"xyz\": 456 }"); Consol ...

"Encountering XML parse error - Unable to locate any element when working with JSON

When trying to use JSON to add data into my database using the POST method, I encounter an issue: XML Parsing Error: no element found Location: moz-nullprincipal:{7c3ebd98-a00f-4a72-8a89-8094946cef8e Line Number 1, Column 1: Even though the browser is ab ...

Tips for designing a three-dimensional egg shape using Three.js?

I'm looking to create a unique egg shape using Three.js, but I seem to be missing the correct equation. Below is the code I currently have, utilizing LatheGeometry. Can anyone provide some guidance? var r0 = 40 var r1 = r0/4; var inc = Math.PI/r0; po ...

The express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Why do all the cards suddenly come to life when I press the activate button on just one card?

Whenever I try to activate a specific card by clicking the active button, all the cards end up getting activated. I have used the className variable and manually set it to "card mb-3 border-3". My intention is for the className to change when clicking th ...

Every time I attempt to reuse my components, they keep piling up on top of each other

I'm facing an issue where I need to reuse components I've created multiple times while rendering dynamic content. However, when I attempt to render them, they end up stacking on top of each other in the same position. Each time I render ...

I encountered a "ReferenceError: db is not defined" while trying to call a function in Express.js with MongoDB intergr

The structure of the code is as follows: var express = require('express'); var router = express.Router(); var mongo = require('mongodb').MongoClient; function getData(){ db.collection("collection_name").find({}).toArray(function (er ...

Tips for pinpointing a particular item within a JSON document

I am struggling with how to manipulate my JSON file using JavaScript. Each object in the array is associated with an ID, and I want to be able to target specific objects based on their position in the array. For example, how can I append object[1] from arr ...

When using Python's pyshark library with the parameter use_json=True, it encounters issues with

I am currently using the pyshark library to extract JSON data. Below is the code snippet I'm utilizing: import pyshark import json capture = pyshark.LiveCapture(interface='eth0', bpf_filter='http', use_json=True) for packet in c ...

Fastify endpoint failing to respond to designated URL

Within my code, there is a router setup: fastify.get('/:link', (req, reply) => { req.params.url = req.host+req.url; reply.view("template.ejs",req.params); }); I am trying to capture URLs and process them in the template. All URLs are ...

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...

How can you merge two arrays with identical property values in Javascript?

Is there a way to combine arrays with the same property value without using map due to different indexes? var array1 = [ {'label':"label1",'position':0}, {'label':"label3",'position':2}, {&ap ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Whenever Sinon.stub() is invoked, it provides a unique value each time

Below is the code that I am currently writing tests for: 'use strict'; var internals = {}; var _ = require('lodash'); module.exports = { initialize: function (query) { internals.query = query; }, createField: fu ...

Steps for positioning an item above CardActionArea

I would like to figure out how to position an object above the CardActionArea. For example, if I have a button on top of the CardActionArea and click on that button, both the CardAction and Button actions will be triggered simultaneously. I want it so that ...

What is the best way to send a JavaScript variable to PHP for storage in a WordPress database?

I am currently in the process of developing a star rating system within Wordpress and am looking to store the rating data in the Wordpress database. To achieve this, I have saved the star rating PHP code as a template within my Wordpress theme folder. Belo ...

Issue arising when attempting to dynamically load an image using Vue and Webpack

I recently set up an application using the Vue CLI, and within one of my components, I have included the following code snippet: <template> <div v-loading="loading"> <el-carousel :interval="4000" type="card" height="350px"> & ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

The lodash debounce function is being triggered multiple times instead of just once, causing issues with my react hooks in a react native environment

Currently, I am implementing a search feature for multiple objects in an array that triggers onChange of the text Input. To optimize this process, we need to incorporate a debouncing function to prevent unnecessary API calls to the search function. Howeve ...