'Microsoft Dynamics CRM update number field from another entity

Can anyone help me with a JS code where I can update a number filed during a record creation?

For example: You have an entity call cars that have a number value "current mileage" and another entity called rental that has two number filed for car section (current mileage and received mileage).

Current mileage will store the mileage value of the selected car (example 300) and the received mileage will be manually inputted by the sales person (for example 100).

So when the sale person created a new rental record, and OnUpdate of the Car lookup field the Current mileage will show the sales person the current mileage of the selected car (300) in this case, so he just will need to add the new value (100). Next time when he create a rental and select from the looup the same car, the Current mileage will be populated with 400 (300+100), and so on.

I see this as JScript OnUpdate of the Car lookup filed, but i really dont know how to write such a code, i hope someone can give me a hint. I'm planning to reuse the code for other entities following the same logic.

I have the following JS code in DYnamics CRM attached on change of a lookupfiled:

new_car - (lookup) to select a car from the rental entity new_cars - schema name of the cars entity new_carsid - UUID of the car from the car entity new_totally_used - total mileage of a car new_outgoing_value - filed on the rental record where must the totally used value appears upon selection of a car

    function retrieveCarsDetails() {
//read lookup value
if (Xrm.Page.getAttribute("new_car").getValue() != null && Xrm.Page.getAttribute("new_car").getValue()[0].id != null) {
  var new_carsid = Xrm.Page.getAttribute("new_car").getValue()[0].id;
new_carsid=new_carsid.replace('{','').replace('}','');
  //pass entity, fields, we can use expand to get related entity fields
  Xrm.WebApi.retrieveRecord("new_cars", new_carsid, "?$select=new_totally_used").then(
    function success(result) {
      if (result != null) {
        //set text field
        if (result["new_outgoing_value"] != null)
          Xrm.Page.getAttribute("new_totally_used").setValue(result["new_outgoing_value"]);
      }
    },
    function(error) {
      alert(error.message);
    }
  );
}
}


Solution 1:[1]

You can create a new field(sum of current and received mileage) in the Rental entity. Update this new sum field, when the sales person updates the received mileage.

So, when the lookup is selected in the car entity, retrieve the sum field from the Rental entity and update the Current mileage in the Car entity with Sum field of Rental entity.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Reshma