Thursday, October 4, 2012

CRM 2011 - Ribbon button to create a record using javascript

// JScript source code
function CreateNewTransaction() {

    var newGunTransaction = new XrmServiceToolkit.Soap.BusinessEntity("jmh_guntransaction");
    newGunTransaction.attributes["jmh_transactiondate"] = new Date();
    var cols = ["jmh_store"];
    var UserGUID = Xrm.Page.context.getUserId();
    var retrievedUser = XrmServiceToolkit.Soap.Retrieve("systemuser", UserGUID, cols);

    var currentUserStoreId = retrievedUser.attributes['jmh_store'].id;
    newGunTransaction.attributes["jmh_store"] = { id: currentUserStoreId, logicalName: "jmh_store", type: "EntityReference" };
    var gunid = Xrm.Page.data.entity.getId();
    var columns = ["jmh_owningcustomer", "jmh_owningrfd"];
    var retrievedGun = XrmServiceToolkit.Soap.Retrieve("jmh_gun", gunid, columns);
    if (retrievedGun.attributes['jmh_owningcustomer'] != null) {

var customerid = retrievedGun.attributes['jmh_owningcustomer'].id;

        newGunTransaction.attributes["jmh_customer"] = { id: customerid, logicalName: "contact", type: "EntityReference" };
    }
    if (retrievedGun.attributes['jmh_owningrfd'] != null) {

        var rfdid = retrievedGun.attributes['jmh_owningrfd'].id;

        newGunTransaction.attributes["jmh_rfd"] = { id: rfdid, logicalName: "account", type: "EntityReference" };
    }
   
    var gunTransactionId = XrmServiceToolkit.Soap.Create(newGunTransaction);
    //    alert(gunTransactionId);
    var newGunTransactionentry = new XrmServiceToolkit.Soap.BusinessEntity("jmh_guntransactionentry");
    newGunTransactionentry.attributes["jmh_gun"] = { id: gunid, logicalName: "jmh_gun", type: "EntityReference" };
    newGunTransactionentry.attributes["jmh_guntransaction"] = { id: gunTransactionId, logicalName: "jmh_guntransaction", type: "EntityReference" };
    var gunTransactionEntryId = XrmServiceToolkit.Soap.Create(newGunTransactionentry);
    OpenForm('jmh_guntransaction', gunTransactionId.toString());

}

function OpenForm(recordtype,formid) {
    var serverUrl;
    var errorMessage = "Context is not available.";
    var context;
    if (typeof GetGlobalContext != "undefined") {
        context = GetGlobalContext();
    }
    else {
        if (typeof Xrm != "undefined") {

            context = Xrm.Page.context;
        }
        else {
            alert(errorMessage);
            return;
        }
    }
    var entityId = formid;


     serverUrl = context.getServerUrl();
    if (serverUrl.match(/\/$/)) { serverUrl = serverUrl.substring(0, serverUrl.length - 1); }
    var recordUrl = serverUrl + "/main.aspx?";

    var params = "etn=" + recordtype;
    params += "&pagetype=entityrecord";

    params +="&id="+ encodeURIComponent("{" + entityId+"}");

    var URL = recordUrl + params;
    window.open(URL, "_blank", "width=900px,height=600px,resizable=1");
}

No comments:

Post a Comment