A typical need is to remember a previous value on a CRM form, so that if a user makes an error, we can set the field back to its original value. The problem is that when we run an on change event function on a field we of course get the new value. We want to know what the original value was.
Let’s say we have a CRM field called global_importantfield. We could make an extra field called global_oldvalueofimportantfield and put this on a hidden part of the form. Then by Javascripting you could set the value of global_oldvalueofimportantfield to the global_importantfield upon load. This is not an ideal solution since you then create uneccessary database fields. Also, if you have many fields where such initial / previous values are needed, you will need to create a lot of fields.
A smarter approach is to create a function that we on load will populate with our initial values. Then we can call upon this dummy function with the right “variable” from other Javascript functions. We can also change and modify the content of these variables from other functions. This is how it is done:
You have a jscript web resource for the entity. In this you have your functions and code.
1) Code that is run onload:
if ( Xrm.Page.getAttribute('global_importantfield').getValue() != null )
InitValues.IMPFIELD = Xrm.Page.getAttribute('global_importantfield').getValue();
else InitValues.IMPFIELD = "";
if ( Xrm.Page.getAttribute('global_anotherfield').getValue() != null )
InitValues.ANOTHERFIELD = Xrm.Page.getAttribute('global_anotherfield').getValue();
else InitValues.ANOTHERFIELD = "";
// End of onload code
2) Then you must have a dummy function in your jscript web resource:
function InitValues() { }
3) Usage in other functions
To use and manipulate these values - your can for example have the following code in the function that is run on-event for the global_importantfield:
var newcontent = Xrm.Page.getAttribute('global_importantfield').getValue();
alert("The new value is:" + newcontent );
alert("And here is the previous value" + InitValues.IMPFIELD);</pre>
If let’s say that the user confirms the choice, you might want to set the IMPFIELD to the new choice right away since it else will only be updated on a new save and load of the form:
InitValues.IMPFIELD = newcontent;