Dynamics 365 Javascript to access form field values

Leon Gentle picture Leon Gentle · Jan 20, 2017 · Viewed 12.5k times · Source

How can I access form field values using Javascript in Dynamics 365 online? This is what I've tried:

A script web resource with an "onload" event called on the form "load". This doesn't work. I get [Object object] but I expect a string. Debugging it shows no properties with the value of the field

function loadForm()
{
    var value1 =    Xrm.Page.data.entity.attributes.get("new_dealercode").getValue();
    alert(value1);
}

An HTML web resource that I include on the form, this does nothing, but I know it's being called because if I put an alert on it, it is alerted.

<html>
<head>
<script type="text/javascript">
    var value1 = window.parent.Xrm.Page.getAttribute("new_dealercoder").getValue();
    alert(value1);
</script><meta charset="utf-8">
</head><body><br></body>
</html>

What I'm trying to achieve: An Iframe with dynamic "src" based on a field value on the form.

Answer

Filburt picture Filburt · Jan 21, 2017

You can shorten your code to access Form field values to

Xrm.Page.getAttribute("new_dealercode").getValue();

If however you are addressing an OptionSet field (Dropdown Selection) you need to use

Xrm.Page.getAttribute("new_dealercode").getSelectedOption();

which returns an Option object with textand value property (see MSDN).
You will find that Lookup and DateTime fields are even more complicated to get and set.

If you need to retrieve properties of a Lookup attribute, you are dealing with an array of EntityReferences featuring the properties id, name and logicalname.

To obtain the id, access the first element in the array:

var dealerobj = Xrm.Page.getAttribute("new_dealercode").getValue();
var dealerid = dealerobj[0].id;

Caution! You may want to harden your code by checking for null values!


As for your second issue, you can access the source of iframeForm controls using

Xrm.Page.getControl("your_control_name_here").setSrc("$webresources\new_your.html")

Start at MSDN Client-side programming reference to find the full reference.