Friday, February 3, 2012

Update Record Using oData Call

Problem:
              Need to update existing record from the JavaScript by using the oData call in Microsoft CRM 2011.

Solution:
             For updating the existing record I have used the same record which I have created in my last post "Insert New Record In Micosoft CRM 2011 Using oData Call ", where I have created new record by using odata call in JavaScript. You can see in the Image 1, here you can see that I have highlighted the Main Phone and the address : City , mean I am going to update these fields Main Phone and the address of the account is going to update using the code here.

Image 1
Code for updating record using oData call in JavaScript is listed in List 1 here you can see that I have first created object for updating the account record then I have used the Address1 to update the City, Line1, Postal code and State or Province of the address and then at the end I have used the Main Phone to be updated.
List 1

After creating the account object for update, next is to create the request object for the oData call, here I have created updateAccountRequest which is used to update the account record. Next is open function of the request which take "POST" as first argument as we are posting data to the server and in the next parameter for the URL note that here we have to pass the Id of the record which is going to be updated by this call. The statement which need to be noted is listed in the List 2 here you can see that in case of update we need to use this extra statement so that record will be updated. For X-HTTP-Method you can refer to the following link Here you can find detail of X-HTTP-Method. We have use the marge request which updates only the properties indicated in the request body, and leaves untouched anything not mentioned in its current state.

List 2

Next is the send function of the HttpRequest to send the updated object and also attached the callback function with the request object.  Here you can see that I have passed record Id to the callback function so that if record is updated successfully then Id will be shown to the client with message and one thing that you can also pass parameter to the completed or callback function which is attached with the request object, mean if you want to send some information which you need in the callback function.
In the callback function I just check the status of the the request for 204 and 1223 as it is the update option and it will return different status. In case of successful it will display message to the client and the if you refresh the active account then you can see the Main Phone and the Address1 : City are update for the record you can see in the Image 2 as below.

Image 2
This is how you can use the oData call to update the record by using JavaScript. I have used simple attribute to update on load of the form you can use this technique.
 
All and any comments / bugs / suggestions are welcomed!

No comments: