Tuesday, September 20, 2011

Update Optionset, lookup data using OData service, JSON

Here I am going to update Optionset and Lookup fields using Odata Service in CRM 2011. In the SDK sample you will find only to update Text fields. After spending some time on Odata service, i got the solution to update Option set and Lookup fields.

        Here i am going to update Account information using Odata service.

function updateOptionset() {
    // Gets the record Guid
    var id = Xrm.Page.data.entity.getId();    
    var changes = {
      // Text field
        Telephone1: "123456789",
     // Option set field    
       Address1_AddressTypeCode: {  Value: 3 },
      // Lookup field
       ParentAccountId: {         
           Id: "8F8338A9-9AB2-E011-9E6D-000C29B0167C", // Guid of the parent account
           LogicalName: "account"
       }
    };
  
    //updateRecord exists in JQueryRESTDataOperationFunctions.js
    updateRecord(id, changes, "AccountSet", updateAccountCompleted, null);
}

function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback) {
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();

    //The XRM OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //id is required
    if (!id) {
        alert("record id is required.");
        return;
    }
    //odataSetName is required, i.e. "AccountSet"
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(entityObject);

    //Asynchronous AJAX function to Update a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");

            //Specify the HTTP method MERGE to update just the changes you are submitting.             
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //The MERGE does not return any data at all, so we'll add the id 
            //onto the data object so it can be leveraged in a Callback. When data 
            //is used in the callback function, the field will be named generically, "id"
            data = new Object();
            data.id = id;
            if (successCallback) {
                successCallback(data, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}


function errorHandler(xmlHttpRequest, textStatus, errorThrow) {  
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}

//Called upon successful Account update.
function updateAccountCompleted(data, textStatus, XmlHttpRequest) {   
    //Get back the Account JSON object
    var account = data;
    alert("Account updated: id = " + account.id);
}

Hope it helps!!!!

Adding New Group to Ribbon in CRM 2011

we have seen adding a button and renaming buttons in my previous posts. Now i am going to add a new group to the Ribbon.
Default Account Ribbon at Form Level.
After Adding New Group to Account Ribbon

1. Export the Solution to customize. And open the Customization.XML file for editing.(solution must contain sitemap)
2. Open Account RibbonDiffXml ribbon definition and then edit with the following logic
source code for the sample

 <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="Sample.account.form.CustomGroup.CustomAction" Location="Mscrm.Form.account.MainTab.Groups._children" Sequence="61">
            <CommandUIDefinition>
              <Group Id="Sample.account.form.CustomGroup.Group" Command="Sample.account.form.CustomGroup.Command" Title="Custom Group" Sequence="11" Template="Mscrm.Templates.Flexible2" Image32by32Popup="/_imgs/Workplace/remove_32.png">
                <Controls Id="Sample.account.form.CustomGroup.Controls">
                  <Button Id="Sample.account.form.CustomGroup.CustomButton1" Command="Sample.account.form.CustomGroup.CustomButton1.Command" Sequence="10" LabelText="Custom Button1" ToolTipTitle="Custom Button ToolTip" ToolTipDescription="Custom Button1 Tooltip Description " TemplateAlias="o1" Image16by16="/_imgs/ribbon/ActivityClose_16.png" Image32by32="/_imgs/ribbon/ActivtiyClose_32.png" />
                  <Button Id="Sample.account.form.CustomGroup.CustomButton2" Command="Sample.account.form.CustomGroup.CustomButton2.Command" Sequence="20" LabelText="Custom Button2" ToolTipTitle="Custom Button ToolTip" ToolTipDescription="Custom Button2 Tooltip Description " TemplateAlias="o1" Image16by16="/_imgs/ribbon/delete16.png" Image32by32="/_imgs/Workplace/remove_32.png" />
                </Controls>
              </Group>
            </CommandUIDefinition>
          </CustomAction>
          <CustomAction Id="Sample.account.form.CustomGroup.MaxSize.CustomAction" Location="Mscrm.Form.account.MainTab.Scaling._children" Sequence="71">
            <CommandUIDefinition>
              <MaxSize Id="Sample.account.form.CustomGroup.MaxSize" GroupId="Sample.account.form.CustomGroup.Group" Sequence="11" Size="LargeLarge" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="Sample.account.form.CustomGroup.CustomButton2.Command">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <JavaScriptFunction Library="$Webresource:new_accountmainlib" FunctionName="MyFunction" />
              
            </Actions>
          </CommandDefinition>
          <CommandDefinition Id="Sample.account.form.CustomGroup.Command">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions />
          </CommandDefinition>
          <CommandDefinition Id="Sample.account.form.CustomGroup.CustomButton1.Command">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <Url Address="http://google.com" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules />
          <EnableRules />
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>

3. Now import the solution and check the changes.

Hope it helps!!!!!