Friday, October 5, 2012

Create Mark Complete Function Button in Custom Entity.


I have one requirement that i have to create same functionality that we have in Phone call Activity like Mark Complete.

Please Follow the Below steps to create Mark Complete Functionality.

1.First Go to Settings->Customization->Select Entity->Field->open Status Reason Field->Select In Active Dropdown->Add new ->Completed and save and publish.

2.Now Go to We Resource and Add PNG File for Mark Complete Button with name new_imgComplete.

3.Go to Setting->Solution(Under Customization)->Then Create a New Solution->Save and Close.

4.Open the Newly Created Solution->Add Existing->Entity and select the Entity to which you want to Add the Mark Complete Button.->Save and Close.

5.Now select the Solution and Export(Unmanaged) the Solution.

6.Open customizations.xml File.

7. under <RibbonDiffXml>.......</RibbonDiffXml> paste the Following line

<RibbonDiffXml>
 <CustomActions>
          <CustomAction Id="Form.CustomAction" Location="Mscrm.Form.hov_meeting.MainTab.Save.Controls._children" Sequence="1">
            <CommandUIDefinition>
              <Button Id="Form.Button.CompleteMeeting" Command="Form.CommandDef" LabelText="$LocLabels:Lable.Text" ToolTipTitle="$LocLabels:Lable.ToolTip" ToolTipDescription="$LocLabels:Lable.ToolTip" TemplateAlias="o1" Image32by32="$webresource:new_imgComplete" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="Form.CommandDef">
            <EnableRules>
              <EnableRule Id="EnableRule.NotNew" />
              <EnableRule Id="EnableRule.WebClient" />
              <EnableRule Id="EnableRule.CustomButton" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="DisplayRule.FormStateNotNew" />
              <DisplayRule Id="DisplayRule.WebClient" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction Library="$webresource:new_MeetingFunctions" FunctionName="MarkComplete" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules>
            <DisplayRule Id="DisplayRule.FormStateNotNew">
              <FormStateRule State="Create" InvertResult="true" />
            </DisplayRule>
            <DisplayRule Id="DisplayRule.WebClient">
              <CrmClientTypeRule Type="Web" />
            </DisplayRule>
          </DisplayRules>
          <EnableRules>
            <EnableRule Id="EnableRule.CustomButton">
              <CustomRule Library="$webresource:new_MeetingFunctions" FunctionName="test" />
            </EnableRule>
            <EnableRule Id="EnableRule.NotNew">
              <FormStateRule State="Create" InvertResult="true" />
            </EnableRule>
            <EnableRule Id="EnableRule.WebClient">
              <CrmClientTypeRule Type="Web" />
            </EnableRule>
          </EnableRules>
        </RuleDefinitions>
        <LocLabels>
          <LocLabel Id="Lable.Text">
            <Titles>
              <Title languagecode="1033" description="Mark Complete" />
            </Titles>
          </LocLabel>
          <LocLabel Id="Lable.ToolTip">
            <Titles>
              <Title languagecode="1033" description="Mark Complete" />
            </Titles>
          </LocLabel>
        </LocLabels>
</RibbonDiffXml>

8.Now Zip the all File again with the same name that you export the solution and import again in solution.

9.Now create one .js file with name new_MeetingFunctions and Add the script in WebResource.be sure that if you give the another name then you have to change it in Customizations.xml file under

<Actions>
         <JavaScriptFunction Library="$webresource:new_MeetingFunctions" FunctionName="MarkComplete" />
</Actions>

10.Now paste the Following lines in .js File

function MarkComplete()
{
   alert(Xrm.Page.context.getServerUrl());
    //SetStateRequest(Entity Name, Xrm.Page.data.entity.getId(), 1,100000000);
    SetStateRequest("hov_meeting", Xrm.Page.data.entity.getId(), 1,100000000);
    window.location.reload(true);
}

function RetrieveOptionsetLabel(entityLogicalName ,RetrieveAttributeName,optionValue,AssignAttributeName,Id  )
{
    // Calling Metadata service to get Optionset Label
    SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, optionValue,AssignAttributeName,Id); }, errorDisplay);

}

function successRetrieveEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue,AssignAttributeName,Id)
{

    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue)
                {

                    //Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);
   var serverUrl = location.protocol + '//' + location.host + '/' + Xrm.Page.context.getOrgUniqueName(); //Xrm.Page.context.getServerUrl();

var meetinglink = "<a href='javascript: void(0);' onclick=\"window.open(\'" + serverUrl + "/main.aspx?etn=hov_meeting&pagetype=entityrecord&id={" + Id + "}\', \'windowname1\', \'resizable=1, scrollbars=1\');  return false;\" style='color:blue;text-decoration:underline !important'>" + option.OptionMetadata.Label.UserLocalizedLabel.Label + "</a>";

                    document.getElementById("header_" + AssignAttributeName + "_d").childNodes[0].innerHTML=meetinglink;
                    success = true;
                    break;
                }
            }
        }
    }
}



function SetStateRequest(_entityname, entityid, _state, _status)
{
    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:SetStateRequest\" 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>EntityMoniker</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + entityid + "</a:Id>";
    requestMain += "              <a:LogicalName>" + _entityname + "</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>State</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _state + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Status</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _status + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>SetState</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";
    var req = new XMLHttpRequest();
    req.open("POST", _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");
    var successCallback = null;
    var errorCallback = null;
    req.onreadystatechange = function () { SetStateResponse(req, successCallback, errorCallback); };
    req.send(requestMain);
}

function SetStateResponse(req, successCallback, errorCallback)
{

    if (req.readyState == 4)
    {
        if (req.status == 200)
        {
            if (successCallback != null)
            { successCallback(); }
        }
        else
        {
            _getError(req.responseXML);
        }
    }
}

function successCallback()
{
alert('test');
}

function _getServerUrl()
{
    var OrgServicePath = "/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 = location.protocol + '//' + location.host+ '/' + Xrm.Page.context.getOrgUniqueName();
           //If you are using the Trail vesrion of CRM means CRM Online then
           // serverUrl = location.protocol + '//' + location.host;
        }
        else
        { throw new Error("Unable to access the server URL"); }
    }
    if (serverUrl.match(/\/$/))
    {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }
    return serverUrl + OrgServicePath;
}

function _getError(faultXml)
{
    var errorMessage = "Unknown Error (Unable to parse the fault)";
    if (typeof faultXml == "object")
    {
        try
        {
            var bodyNode = faultXml.firstChild.firstChild;
            //Retrieve the fault node
            for (var i = 0; i < bodyNode.childNodes.length; i++)
            {
                var node = bodyNode.childNodes[i];
                if ("s:Fault" == node.nodeName)
                {
                    for (var j = 0; j < node.childNodes.length; j++)
                    {
                        var faultStringNode = node.childNodes[j];
                        if ("faultstring" == faultStringNode.nodeName)
                        {
                            errorMessage = faultStringNode.text;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        catch (e) { };
    }
    return new Error(errorMessage);
}

function GetOptionsetLabel(entityLogicalName ,RetrieveAttributeName,optionValue,AssignAttributeName)
{
    // Calling Metadata service to get Optionset Label
    SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successGetEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, optionValue,AssignAttributeName); }, errorDisplay);

}

function successGetEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue,AssignAttributeName)
{
    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue)
                {
                    Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);  
                    success = true;
                    break;
                }
            }
        }
    }
}

function GetRequestObject()
{
    if (window.XMLHttpRequest)
        return new window.XMLHttpRequest;
    else
    {
        try
        {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex)
        {
            return null;
        }
    }
}

function errorDisplay(XmlHttpRequest, textStatus, errorThrown)
{
     alert(errorThrown);
}

function trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

11.Now Open the Form and Add Javascript Library  from Web Resource. and Save it and publish the Form.

12.Thats it and just check now.Create the Record from and Save and Close.and again open the Record and Click on Mark Complete Button.

No comments:

Post a Comment