If I were putting the FetchXML into a C# program, no problem because that language supports having multi-line strings. And I could use Format.string() to insert my parameters into the code so I don't have to concatenate that either.
Not so much in Javascript. So I did some research and found some articles on how it could be done. I can put the FetchXML between comments and then use a regular expression to make it into a legit string. As long as nobody turns on 'compression' on the web server, it should continue to work. The code looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fetchGetProduct() { | |
try { | |
// Get the price of the product requested | |
var sFetch = (function () {/* | |
<fetch count="1" > | |
<entity name="product" > | |
<attribute name="price" /> | |
<filter type="and"> | |
<condition attribute="productid" operator="eq" value="{0}" /> | |
</filter> | |
</entity> | |
</fetch> | |
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; | |
// use this trick to insert the GUID into the fetch query at position {0} | |
var v1 = Xrm.Page.getAttribute("new_quickaddproductid").getValue()[0].id; | |
sFetch = sFetch.format(v1); | |
// alert(sFetch); | |
_oService = new FetchUtil(_sOrgName, _sServerUrl); | |
// get the price from CRM, and use updatePrice() as the callback | |
_oService.Fetch(sFetch, updatePrice); | |
} | |
catch (e) { | |
} | |
} | |
function updatePrice(results) { | |
// given the results of the FetchXML | |
// get the list price from the product it returned | |
if (results.length > 0) { | |
var listprice = results[0].attributes["price"].value; | |
// update the price field on the custom form | |
Xrm.Page.getAttribute("new_quickaddamount").setValue(parseFloat(listprice)); | |
} | |
} | |
// this function lets me replace a positional parameter in | |
// First, checks if it isn't implemented yet. | |
if (!String.prototype.format) { | |
String.prototype.format = function () { | |
var args = arguments; | |
return this.replace(/{(\d+)}/g, function (match, number) { | |
return typeof args[number] != 'undefined' | |
? args[number] | |
: match | |
; | |
}); | |
}; | |
} |