简体   繁体   English

CRM 2011-使用JavaScript启用潜在客户实体的工作流加载吗?

[英]CRM 2011 - Enable workflow onload of lead entity using javascript?

I've checked through the forum and cant seem to get what i need to work. 我已经通过论坛检查过,似乎无法得到我需要的工作。

On the lead entity, when a user creates a new lead a Workflow runs just before to change some lead fields. 在潜在顾客实体上,当用户创建新潜在顾客时,工作流将在更改某些潜在顾客字段之前运行。

I found out this is only possible through javascript and onload in the entity settings. 我发现这只能通过javascript和onload在实体设置中实现。

I've created the Workflow and a JavaScript file and set it to run onload. 我创建了工作流和一个JavaScript文件,并将其设置为在加载时运行。 The Javascript i have used is: 我使用的Javascript是:

function callworkfow(workflowId, entityId) {
var request =
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<request i:type="b:ExecuteWorkflowRequest" 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:KeyValuePairOfstringanyType>
  <c:key>B3D77337-D5FD-E211-BB05-005056AF0003</c:key>
  <c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/">EntityIdValue</c:value>
      </a:KeyValuePairOfstringanyType>
      <a:KeyValuePairOfstringanyType>
        <c:key>2EF8C158-182B-444A-A9DF-FF2DC5E44514</c:key>
        <c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization /">WorkflowIdValue</c:value>
      </a:KeyValuePairOfstringanyType>
    </a:Parameters>
    <a:RequestId i:nil="true" />
    <a:RequestName>ExecuteWorkflow</a:RequestName>
  </request>
    </Execute>
  </s:Body>
</s:Envelope>

var xhr = new XMLHttpRequest();
xhr.open('POST', '/XRMServices/2011/Organization.svc/web', true);

xhr.setRequestHeader('Accept', 'application/xml, text/xml, */*');
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute');

xhr.onreadystatechange = function () { alert(xhr.status); };
xhr.send(request);
}

However this fails to load. 但是,这无法加载。

If anyone could help me i would be very grateful. 如果有人可以帮助我,我将不胜感激。 Just need the JavaScript to simply load a Workflow. 只需要JavaScript即可简单地加载工作流。 Oh and with cross platform compatibility. 哦,并且具有跨平台兼容性。


function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}

var ExistingCase = curentUserId = Xrm.Page.context.getUserId();
if (ExistingCase.getValue() != null) {
    var ExistingCaseGUID = ExistingCase.getValue()[0].id;
    var ExistingCaseName = ExistingCase.getValue()[0].name;
    SetLookupValue("new_accountmanager", ExistingCaseGUID, ExistingCaseName, "incident");
}

please check following code, it worked fine for me last time i used it: 请检查以下代码,上次使用它对我来说效果很好:

if (typeof (SDK) == "undefined")
   { SDK = { __namespace: true }; }
       //This will establish a more unique namespace for functions in this library. This will reduce the 
       // potential for functions to be overwritten due to a duplicate name when the library is loaded.
       SDK.Workflow = {
           _getServerUrl: function () {
               ///<summary>
               /// Returns the URL for the SOAP endpoint using the context information available in the form
               /// or HTML Web resource.
               ///</summary>
               var ServicePath = "/XRMServices/2011/Organization.svc/web";
               var serverUrl = "";
               if (typeof GetGlobalContext == "function") {
                   var context = GetGlobalContext();
                   serverUrl = context.getServerUrl();
               }
               else {
                   if (typeof Xrm.Page.context == "object") {
                         serverUrl = Xrm.Page.context.getServerUrl();
                   }
                   else
                   { throw new Error("Unable to access the server URL"); }
                   }
                  if (serverUrl.match(/\/$/)) {
                       serverUrl = serverUrl.substring(0, serverUrl.length - 1);
                   } 
                   return serverUrl + ServicePath;
               }, 
           ExecuteRequest: function () {
               var requestMain = ""
               requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
               requestMain += "  <s:Body>";
               requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
               requestMain += "      <request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
               requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
               requestMain += "          <a:KeyValuePairOfstringanyType>";
               requestMain += "            <c:key>EntityId</c:key>";
               requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">267d4790-e41a-e311-b6a7-3c4a92db481b</c:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "          <a:KeyValuePairOfstringanyType>";
               requestMain += "            <c:key>WorkflowId</c:key>";
               requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">a6832cc5-1d82-48f5-a940-e41269726204</c:value>";
               requestMain += "          </a:KeyValuePairOfstringanyType>";
               requestMain += "        </a:Parameters>";
               requestMain += "        <a:RequestId i:nil=\"true\" />";
               requestMain += "        <a:RequestName>ExecuteWorkflow</a:RequestName>";
               requestMain += "      </request>";
               requestMain += "    </Execute>";
               requestMain += "  </s:Body>";
               requestMain += "</s:Envelope>";
               var req = new XMLHttpRequest();
               req.open("POST", SDK.Workflow._getServerUrl(), false)
               req.setRequestHeader("Accept", "application/xml, text/xml, */*");
               req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
               req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
               req.send(requestMain);
               //work with the response here
               var strResponse = req.responseXML.xml;
               alert(strResponse.toString());
           },
 __namespace: true
};

UPDATE:-------------- 更新:--------------

My previous answer was direct to question. 我以前的回答是直接质疑的。 Now providing new answer due to question comments. 现在由于问题评论而提供新的答案。 As it's said in comments workflows can be run only over existing records, but as you said you want to change some field on creation form: record is not saved yet. 正如评论中所说,工作流只能在现有记录上运行,但是正如您所说的,您想更改创建表单上的某些字段:记录尚未保存。 To do that you must use Xrm object as it is shown below: 为此,必须使用Xrm对象,如下所示:

function OnLoadingForm() {
    var FormType = Xrm.Page.ui.getFormType();
    if (FormType != null) {
        switch (FormType) {
            case 1:
                //  It's a "create" form
                var test = "Mr.";                    
                Xrm.Page.getAttribute("salutation").setValue(test);
                break;
            case 2:
                //  It's a "update" form                              
                break;
            case 3:
                // It's a "readonly" form
                break;
            case 4:
                // It's a "disabled" form
                break;
            case 6:
                // It's a  "bulkedit" form
                break;
            default:
                break;
        }
    }
}

This code works on classic CRM forms (Information forms in customizations). 此代码适用于经典CRM表单(自定义中的信息表单)。 New release may change this. 新版本可能会改变这一点。 "salutation" is name of field from customizations. "salutation"是来自定制的字段名称。 Notice that this field change is only on form and will be saved to CRM DB after user clicks Save button. 请注意,此字段更改仅在表单上,​​并且在用户单击“保存”按钮后将保存到CRM DB。

UPDATE 2:----------- Due to new circumstances new code snippet: 更新2:-------------由于新情况,新的代码段为:

function OnLoadingForm() {
    // Get the current FormType
    var FormType = Xrm.Page.ui.getFormType();      
    if (FormType != null) {
        switch (FormType) {
            case 1:
                //  It's a "create" form                

                var curentUserId = Xrm.Page.context.getUserId();
                var serverUrl;
                if (Xrm.Page.context.getClientUrl !== undefined) {
                    serverUrl = Xrm.Page.context.getClientUrl();
                } else {
                    serverUrl = Xrm.Page.context.getServerUrl();
                }
                var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc"; 
                var userRequest = new XMLHttpRequest(); 
                userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false); 
                userRequest.setRequestHeader("Accept", "application/json"); 
                userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8"); 
                userRequest.send();
                if (userRequest.status === 200) {
                    var retrievedUser = JSON.parse(userRequest.responseText).d; 
                    var userFullName = retrievedUser.FullName;        
                    SetLookupValue("new_accountmanager", curentUserId, userFullName, "systemuser");
                }
                else {
                    return "error";
                }
                break;
            case 2:
                //  It's a "update" form               
                break;
            case 3:
                // It's a "readonly" form
                break;
            case 4:
                // It's a "disabled" form
                break;
            case 6:
                // It's a  "bulkedit" form
                break;
            default:
                break;
        }
    }
}

function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM