Tuesday, October 9, 2012

CRM 2011-Trigger a workflow process from cutom ribbon button using javascript

1.Create a new  web resource (javascipt) with following code

function TriggerWorkflow(workflowGuid) {


  /*Generate Soap Body.*/
  var soapBody = "<soap:Body>" +
                 "  <Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
                 "    <Request xsi:type=\'ExecuteWorkflowRequest\'>" +
                 "      <EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
                 "      <WorkflowId>" + workflowGuid + "</WorkflowId>" +
                 "    </Request>" +
                 "  </Execute>" +
                 "</soap:Body>";

  /*Wrap the Soap Body in a soap:Envelope.*/
  var soapXml = "<soap:Envelope " +
                "  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' " +
                "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
                "  xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
                GenerateAuthenticationHeader() +
                soapBody +
                "</soap:Envelope>";

  /* Create the XMLHTTP object for the execute method.*/
  var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  xmlhttp.open("POST", "/MSCRMservices/2007/crmservice.asmx", false);
  xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");

  /* Send the XMLHTTP object. */
  xmlhttp.send(soapXml);
alert("The workflow has been triggered successfully");

}

2.Create the workflow process
3.Create a new button using visual ribbon editor and pass parameter  as follows
 
 
Function Name:TriggerWorkflow
Library: $webresource:<created web resource name>
String parameter Value: < Id of workflow process to be launched>
Reference:

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");
}

CRM 2011 conformation alert before saving a record(to prevent save)

function ConfirmonSave(ExecutionObj) {
    var mode = ExecutionObj.getEventArgs().getSaveMode();
    if(mode == "58") {
        var ans = confirm("There are Associated Process Schedule Waypoints ! Do you really want close ?");
        if (ans == true) {
            Xrm.Page.getAttribute("jmh_forceclose").setValue(1);

        }
        else {
            ExecutionObj.getEventArgs().preventDefault()
        }
    }
}

Note:
Call the above method in OnSave event of Form and Select the "Pass execution context as first parameter".
 the above example is for mark as complete(mode="58") conformation .


Thanks to
Athul MT

Reference:
http://athulmt.blogspot.in/2012/09/how-to-restrict-saving-of-record-in-crm.html

http://msdn.microsoft.com/en-us/library/gg509060.aspx

Crm 2011 Ribbon button to open form of a record using javascript





   1.  Create a new  web resource (javascipt) with following code

  function OpenForm(recordtype) {
         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 = context.getQueryStringParameters().id

   var entityEtc = context.getQueryStringParameters().etc

     var 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 += "&extraqs=" + encodeURIComponent("?_CreateFromId=" + entityId + "&_CreateFromType=" + entityEtc) ;
   var URL = recordUrl + params;
     window.open(URL, "_blank", "width=900px,height=600px,resizable=1");
     }
Note:to open already existing record use the following
 var recordUrl = serverUrl + "/main.aspx?";

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

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

    var URL = recordUrl + params;

Note:to pass parameter and set field values use extraqs
    params += "&extraqs=" + encodeURIComponent("?_CreateFromId=" + entityId + "&_CreateFromType=" + entityEtc + "&" + lookupfield + "=" + lookupfieldid + "&" + lookupfield + "name=" + lookupfieldname);


Note : to set regarding field 
  var serverUrl = context.getServerUrl();
    if (serverUrl.match(/\/$/)) { serverUrl = serverUrl.substring(0, serverUrl.length - 1); }
    var recordUrl = serverUrl + "/userdefined/edit.aspx?";
    var params = "contactInfo=&etc=10004&pId=";
    params += currentformid;
    params += "&pType=3";
   var URL = recordUrl + params;
    window.open(URL, "_blank", "width=900px,height=600px,resizable=1");



//get the above url  by using fiddler

Reference:

http://msdn.microsoft.com/en-us/library/gg334375.aspx

http://www.renauddumont.be/en/2011/crm-2011-ouvrir-une-fenetre-a-laide-dun-bouton-custom-et-dun-peu-de-javascript
2 2.Create a new button using visual ribbon editor and pass parameter   as follows

 Function Name: OpenForm
Library: $webresource:<created web resource name>
String parameter Value: <record type to be created>

Wednesday, October 3, 2012

CRM 2011- Disable Sub grid

function VisibleGunTransactionEntries() {
var statusreason=Xrm.Page.data.entity.attributes.get("statuscode");
var reason = statusreason.getValue();
if (reason != 170000000) {

    var objNavItem = Xrm.Page.ui.navigation.items.get("nav_jmh_jmh_guntransaction_jmh_guntransactionentry_guntransaction");
        objNavItem.setVisible(false);
        disableSubgrid('subgrid1');
}
}
function disableSubgrid(subgridName) {
    document.getElementById(subgridName + "_span").disabled = "true";
}

Monday, October 1, 2012

CRM 2011- Set ribbon button visiblity using javascript by Custom Rule



1. Create a web resource (jscript) with the following code.

function GetRelatedRecords() {
    var baseEntityGUID = Xrm.Page.data.entity.getId();
    var query = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"
        + " <entity name='jmh_guncurrentlocation'>"
  + "  <attribute name='jmh_locationdetail' />"
  + "    <attribute name='createdon' />"
   + " <attribute name='jmh_locationrfd' />"
   + " <attribute name='jmh_locationcustomer' />"
   + " <attribute name='jmh_gun' />"
    + " <attribute name='jmh_store' />"
   + " <attribute name='jmh_guncurrentlocationid' />"
   + " <order attribute='jmh_locationdetail' descending='false' />"
   + "<filter type='and'>"
    + "  <condition attribute='statecode' operator='eq' value='0' />"
     + " <condition attribute='jmh_gun' operator='eq' uiname='45' uitype='jmh_gun' value='" + baseEntityGUID + "' />"
    + "</filter></entity></fetch>";
    var retrievedRecords = XrmServiceToolkit.Soap.Fetch(query);
    //alert(retrievedRecords.length);
    if (retrievedRecords.length != 0) {

        var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
        var resultXml = XrmServiceToolkit.Soap.Execute(request);
        var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
        for (var index = 0; index < retrievedRecords.length; index++) {

            var storeid = retrievedRecords[index].attributes['jmh_store'].id;

//            alert(buid);
//            alert(storeid);
            if (buid.toString() == storeid.toString()) {
                return true;
            }
        }
        return false;

    }
    else {
        return false;
    }
}

2.Create a button using visual ribbon editor and specify the created javascript method in cutom rule
 
Note : the above javascript to retrive related entities using Fetch in xrmservicetoolkit