sdata crud

SUGGESTED

The following is an example of how to update a field, in this case an Oppo_OpportunityUId, via client side 'Custom Content' using an sdata2/sagecrm2 (CRUD) call. In this example the aim is to copy the hidden Opportunity Id to a new field so that it can be exposed to the end user as a unique reference identifier. We make use of the SID in order to bypass the need for authentication.

<script>
crm.ready(function(){
// Manage Opportunity UId field
if ($("#oppo_opportunityuid").length > 0)
{
// Edit Mode
crm.fields("oppo_opportunityuid").collapse();
var OppoId = parseInt(crm.getArg("Key7"));
var OppoUId = parseInt($("#oppo_opportunityuid").val());
if (!isNaN(OppoId) && isNaN(OppoUId))
{
crm.fields("oppo_opportunityuid").val(OppoId);
}
}
else
{
// View Mode
var OppoId = parseInt(crm.getArg("Key7"));
var OppoUId = parseInt($("#_HIDDENoppo_opportunityuid").val());
if (!isNaN(OppoId) && (isNaN(OppoUId) || OppoUId == 0))
{
// Build the sdata2 url
var strUrl = crm.url(location.href, {parts:"sap"});
strUrl = strUrl.split("eware.dll")[0];
strUrl += "sagecrm2/-/opportunity('" + OppoId + "')";
strUrl += "?SID=" + crm.getArg("SID", crm.url());
// Build the data Object to update the UId
var objOppo = {
"Oppo_OpportunityUId": OppoId
};
// Ajax Update Call
$.ajax({
type: "POST",
url: strUrl,
data: JSON.stringify(objOppo),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) { $("#_Dataoppo_opportunityuid").text(data.oppo_OpportunityUID); },
error: function(jqXHR, textStatus, errorThrown) { alert("Failed to update UId: " + errorThrown); }
});
}
}
});
</script>

  • 0
    SUGGESTED

    I found this extremely helpful in 2020, but had to tweak the building of the data URL in the following way.

    Define 2 external functions:

    const getHostnameFromRegex = (url) => {
      // run against regex
      const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
      // extract hostname (will be null if no match is found)
      return matches && matches[1];
    }
    
    const httpOrS = (url) => {
        return url.split(/:(.+)/)[0] + "://";
    }

    and use them as follows:

    // Build the sdata url
    var strUrl = httpOrS(location.href);
    strUrl += getHostnameFromRegex(location.href);
    strUrl = "/sdata/crmj/sagecrm2/-/opportunity('" + oppoID + "')";
    strUrl += "?SID=" + crm.getArg("SID", crm.url());