cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Palani
Frequent Visitor

Need sample code for context.webAPI.updateRecord method (ComponentFramework) in my PCF

Hello expert community,

 

I am trying to use context.webAPI.updateRecord method (ComponentFramework) in my PCF for updating some of the lookup fields and also to close an Opportunity as Won or Lost. 

 

I tried several ways but I am not able to make the updateRecord method work.  Its giving me error message related to datatype of the attributes.  I am looking for some sample code for the following.

1.  Using context.webAPI.updateRecord method for updating lookup fields.

2.  Using context.webAPI.updateRecord method for closing an Opportunity as Won or Lost.  Note, I don't see the execute method in context.WebAPI, so am wondering if updateRecord must be used for closing a record

 

I tried to pass the EntityReference object returned by the context.utils.lookupObjects method to update a lookup field (parentaccountid) of Opportunity using the updateRecord method as shown below but that did not work.  I tried using _parentaccountid_value, but the error message I received said we cannot update some properties directly in CRM

 

 

 

let oppForUpdate = { "parentaccountid": selectedItem[0] }; //didn't work
//let oppForUpdate = { "_parentaccountid_value": selectedItem[0].id }; //didn't work

this._context.webAPI.updateRecord("opportunity", recordGuid, recordToUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

 

 

 

For updating an Opportunity as Won or Lost I am trying to pass below data to the updateRecord method again.

 

 

 

    let oppCloseAsWon = { "statecode": 1 };

    let oppCloseAsLost = { "statecode": 2, "statuscode": 4 };

 

 

 

Regards,

Palani K.B.

2 ACCEPTED SOLUTIONS

Accepted Solutions
v-xida-msft
Community Support
Community Support

Hi @Palani ,

Do you want to use the context.webAPI.updateRecord method to update LookUp field and Option Set type column in your Opportunity Entity?

 

Based on the formula that you mentioned, I think there is something wrong with it. Firstly, in order to get the guid value (accountid) of the selected account from the LookUp dialog launched using context.utils.lookupObjects method, please use the following formula:

selectedItem[0].id.guid

Note: The id attribute under the EntityReference object is also a Object value rather than a guid string value. Please check the following article for more details:

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/reference/entityreference

 

For updating LookUp field (parentaccountid):

Actually, the LookUp field is a object value in underlying data structure of CDS Entity, it should contain the following two attributes:

logicalname
id

So you need to declare your oppForUpdate variable as below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         }
                   }

or

let oppForUpdate = { 
                      "parentaccountid@odata.bind": "/accounts(" + selectedItem[0].id.guid + ")"
                   }

Please check the following article for more details:

https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webap...

So the whole formula should like below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         }
                   };
this._context.webAPI.updateRecord("opportunity", recordGuid, oppForUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

Note: I assume that the parentaccountid LookUp field reference values from the Account Entity.

 

For updating Option Set field in your Opportunity Entity, I think your variable declare is correct. Combined with above feature, you should declare the oppForUpdate object as below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         },
                       "statecode": 2,
                       "statuscode": 4
                   }

The whole formula should like below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         },
                       "statecode": 2,
                       "statuscode": 4
                   };
this._context.webAPI.updateRecord("opportunity", recordGuid, oppForUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

or

let oppForUpdate = { 
                       "parentaccountid@odata.bind": "/accounts(" + selectedItem[0].id.guid + ")",
                       "statecode": 2,
                       "statuscode": 4
                   };
this._context.webAPI.updateRecord("opportunity", recordGuid, oppForUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

Please check the following blog for more details:

https://somacrm.wordpress.com/2018/05/15/dynamics-365-xrm-webapi-update-record-example/

 

Please take a try with above solution, then check if the issue is solved.

 

Best regards,

Community Support Team _ Kris Dai
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

View solution in original post

Hi @Palani , 

The execute Method for the webAPI is not documented, so it's not supported for now. Calling special requests is similar to calling custom actions, because you need there also the execute method.

The execute method is there and works, even if in the typescript definition is not provided. So you could use it...

 

A supported approach is to implement your own XmlHttpRequest  to call the webAPI.

Maybe this thread will help you (there is even an answer for "WinOpportunity" there): https://powerusers.microsoft.com/t5/Power-Apps-Pro-Dev-ISV/How-to-call-custom-actions-using-PCF/m-p/...

Hope it helps.

 

Kind regards,

Diana

Kind regards,
Diana
----------
Please click "Accept as Solution" if my post answered your question so that others may find it more quickly. If you found this post helpful consider giving it a "Thumbs Up."

View solution in original post

7 REPLIES 7
v-xida-msft
Community Support
Community Support

Hi @Palani ,

Do you want to use the context.webAPI.updateRecord method to update LookUp field and Option Set type column in your Opportunity Entity?

 

Based on the formula that you mentioned, I think there is something wrong with it. Firstly, in order to get the guid value (accountid) of the selected account from the LookUp dialog launched using context.utils.lookupObjects method, please use the following formula:

selectedItem[0].id.guid

Note: The id attribute under the EntityReference object is also a Object value rather than a guid string value. Please check the following article for more details:

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/reference/entityreference

 

For updating LookUp field (parentaccountid):

Actually, the LookUp field is a object value in underlying data structure of CDS Entity, it should contain the following two attributes:

logicalname
id

So you need to declare your oppForUpdate variable as below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         }
                   }

or

let oppForUpdate = { 
                      "parentaccountid@odata.bind": "/accounts(" + selectedItem[0].id.guid + ")"
                   }

Please check the following article for more details:

https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webap...

So the whole formula should like below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         }
                   };
this._context.webAPI.updateRecord("opportunity", recordGuid, oppForUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

Note: I assume that the parentaccountid LookUp field reference values from the Account Entity.

 

For updating Option Set field in your Opportunity Entity, I think your variable declare is correct. Combined with above feature, you should declare the oppForUpdate object as below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         },
                       "statecode": 2,
                       "statuscode": 4
                   }

The whole formula should like below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.guid
                                         },
                       "statecode": 2,
                       "statuscode": 4
                   };
this._context.webAPI.updateRecord("opportunity", recordGuid, oppForUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

or

let oppForUpdate = { 
                       "parentaccountid@odata.bind": "/accounts(" + selectedItem[0].id.guid + ")",
                       "statecode": 2,
                       "statuscode": 4
                   };
this._context.webAPI.updateRecord("opportunity", recordGuid, oppForUpdate).then
			(
				function (updatedRecord: ComponentFramework.EntityReference) {
					console.log("UpdateOpportunityRecord:  Record updated successfully.  ");
				},
				function (errorResponse: any) {
					console.log("UpdateOpportunityRecord:  Record update failed.  " + errorResponse.toString());
				}
			);

Please check the following blog for more details:

https://somacrm.wordpress.com/2018/05/15/dynamics-365-xrm-webapi-update-record-example/

 

Please take a try with above solution, then check if the issue is solved.

 

Best regards,

Community Support Team _ Kris Dai
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

@v-xida-msft 

 

Hi Kris Dai,

 

Thank you so much for your suggestion and really sorry I could not let you know my findings sooner.

 

Here below are my findings.

 

1.  The object selectedItem[0].id does not have a property called guid.  It contains the GUID of the record in curly braces and I had to remove the curly braces in order to use the GUID for updating the record using WebAPI (let selectedItemGUIDstring = selectedItem[0].id.replace("{""").replace("}""");)

 

2.  For updating Lookup fields using webAPI.updateRecord, the below format worked for me.

                    let valueToUpdatestring = "/accounts(" + selectedItemGUID + ")";
                    let oppForUpdate = { "parentaccountid@odata.bind": valueToUpdate };
 
Here below is the code I am using now to update the lookup field based on the response from the
context.utils.lookupObjects method

 

	private LookUpDialog(entityName: string, fieldName: string): void {
		var lookUpOptions: any = {
			entityTypes: [entityName]
		};
		var lookUpPromise: any = this._context.utils.lookupObjects(lookUpOptions);
		lookUpPromise.then((selectedItem: any) => {	
				if (selectedItem && selectedItem[0]) {
					let selectedItemGUID: string = selectedItem[0].id.replace("{", "").replace("}", "");
					let valueToUpdate: string = "/accounts(" + selectedItemGUID + ")";
					let oppForUpdate = { "parentaccountid@odata.bind": valueToUpdate };
					this.UpdateOpportunityRecord(this._props.recordDetails?.recordId as string, oppForUpdate);
				}
			},
			(error: any) => {
				// Error handling code here
			}
		);
	}

 

 

I am still having issues updating the statecode and statuscode of the record using the below format.  Kindly help me there if I am doing something wrong.  

 

Here below is the object I am using 

image.png

 

Here's the error I am receiving and the error message is generic.

image.png

 

Also, I could not find the execute method as part of the WebAPI object yet. Please confirm if that is not yet supported.

 

Kindly share an example for setting DateTime fields too.

 

Your help is much appreciated.

 

Thanks and Regards,

Palani K.B.  

Hi @Palani ,

Firstly, I agree with your modification on my formula almost. Do you mean that the 

updateRecord

function is not available under the webAPI Client API on your side?

 

I have made a test on my side, and don't have the issue that you mentioned. The screenshot as below:

4.JPG

 

Before you could use the webAPI functionality in your PCF Project, you must have enabled the webAPI uses-feature in your ControlManifest.Input.xml file as below:

5.JPG

<feature-usage>
      <uses-feature name="WebAPI" required="true" />
</feature-usage>

More details about the uses-feature element in PCF, please check the following article:

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/manifest-schema-reference/f...

 

Best regards, 

Community Support Team _ Kris Dai
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

@v-xida-msft 

 

Hi Kris,

 

I am able to see the updateRecord method under the WebAPI client api.  However, I am not able to see the Execute method which we use to execute various other types of requests in CDS.

https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webap...

 

Note, I have already included the feature-usage and uses-feature property in my ControlManifest.Input.xml file and I am able to successfully use retrieveRecord, retrieveMultipleRecords and updateRecord method too, but I am not able to use this updateRecord method to close an Opportunity record as Won or Lost.  When I try to set the statecode and statuscode as shown in the screenshot below, I am getting an error message.

 

image.png

 

image.png

 

Can you please share an example of how to close an Opportunity as Won or Lost using updateRecord method. 

 

Regards,

Palani K.B.

Hi @Palani ,

You mean the formula I provided above could update a LookUp field properly, but not a Option Set type column?

 

Please consider initialize the object variable in your .ts file as below:

let oppForUpdate = { 
                      "parentaccountid": {
                                            "logicalname": "account",
                                            "id": selectedItem[0].id.replace("{", "").replace("}", "")
                                         },
                       "statecode": {
                                      "value": 0,
                                      "label": "Active"
                                    },
                       "statuscode": {
                                         "value": 1,
                                         "label": "Active"
                                     }
                   }

The Option Set type column is essentially a Entity Reference Object, which contains the following two attributes:

2.JPG

 

Please consider take a try with above solution, then check if the issue is solved.

 

Best regards,

Community Support Team _ Kris Dai
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Hi @Palani , 

The execute Method for the webAPI is not documented, so it's not supported for now. Calling special requests is similar to calling custom actions, because you need there also the execute method.

The execute method is there and works, even if in the typescript definition is not provided. So you could use it...

 

A supported approach is to implement your own XmlHttpRequest  to call the webAPI.

Maybe this thread will help you (there is even an answer for "WinOpportunity" there): https://powerusers.microsoft.com/t5/Power-Apps-Pro-Dev-ISV/How-to-call-custom-actions-using-PCF/m-p/...

Hope it helps.

 

Kind regards,

Diana

Kind regards,
Diana
----------
Please click "Accept as Solution" if my post answered your question so that others may find it more quickly. If you found this post helpful consider giving it a "Thumbs Up."

@DianaBirkelbach Thanks a lot for your suggestion.  This is what I was looking for.  This would help me move forward now.  I will accept your answer as a solution.

 

@v-xida-msft Hi Kris, I tried your latest suggestion for updating the optionset value as mentioned by you but it did not work again and threw an error as shown below.  However, your suggestion for the lookup field did help me and thanks a lot for that. 

 

image.png

 

Error Message: 

"An error occurred while validating input parameters: Microsoft.OData.ODataException: An unexpected 'StartObject' node was found for property named 'statecode' when reading from the JSON reader. A 'PrimitiveValue' node was expected.
   at Microsoft.OData.JsonLight.ODataJsonLightPropertyAndValueDeserializer.ReadPrimitiveValue(Boolean insideJsonObjectValue, IEdmPrimitiveTypeReference expectedValueTypeReference, Boolean validateNullValue, String propertyName)
   at Microsoft.OData.JsonLight.ODataJsonLightPropertyAndValueDeserializer.ReadNonEntityValueImplementation(String payloadTypeName, IEdmTypeReference expectedTypeReference, PropertyAndAnnotationCollector propertyAndAnnotationCollector, CollectionWithoutExpectedTypeValidator collectionValidator, Boolean validateNullValue, Boolean isTopLevelPropertyValue, Boolean insideResourceValue, String propertyName, Nullable`1 isDynamicProperty)
   at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadEntryDataProperty(IODataJsonLightReaderResourceState resourceState, IEdmProperty edmProperty, String propertyTypeName)
   at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithValue(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean isDeltaResourceSet)
   at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.<ReadResourceContent>b__0(PropertyParsingResult propertyParsingResult, String propertyName)
   at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func`2 readPropertyAnnotationValue, Action`2 handleProperty)
   at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState)
   at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource()
   at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties)
   at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector)
   at Microsoft.OData.ODataReaderCore.ReadImplementation()
   at Microsoft.OData.ODataReaderCore.InterceptException[T](Func`1 action)
   at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader)
   at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
   at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)"

Regards,
Palani K.B.

Helpful resources

Users online (2,784)