I have made two custom fields 'Pincode__c' of type text and 'Places__c' of type Long Text Area.I am inserting account record by providing 'Pincode__c' value and want the custom field 'Places__c' to get automatically updated with the value of Name field from the response that we get from API . For that to happen, I am calling future method from trigger and that future method is making the callout to 'https://api.postalpincode.in/pincode/110001'.
Below is the image of data which I used for creation of Account record.
The response from API is of the format as below:
{
"Message":"Number of Post office(s) found: 2",
"Status":"Success",
"PostOffice":[
{
"Name":"Baroda House",
"Description":"",
"BranchType":"Sub Post Office",
"DeliveryStatus":"Non-Delivery",
"Circle":"New Delhi",
"District":"Central Delhi",
"Division":"New Delhi Central",
"Region":"Delhi",
"State":"Delhi",
"Country":"India"
},
{
"Name": "Bengali Market",
"Description": null,
"BranchType": "Sub Post Office",
"DeliveryStatus": "Non-Delivery",
"Circle": "Delhi",
"District": "Central Delhi",
"Division": "New Delhi Central",
"Region": "Delhi",
"Block": "New Delhi",
"State": "Delhi",
"Country": "India",
"Pincode": "110001"
}
]
}
Below is the trigger which is internally calling the future method.
trigger Pincode_Trigger on Account (after insert) {
Map<Id,Account> accMap = Trigger.newMap;
Set<Id> keys = accMap.keySet();
FutureCall_Example.invoke(keys);
}
public class FutureCall_Example {
@future(callout=true)
public static void invoke(Set<Id> accIds)
{
List<Account> accounts = [SELECT ID,Places__c,Pincode__c from Account where ID IN:accIds];
for(Account a : accounts)
{
Http p = new HTTP();
HttpRequest request = new HttpRequest();
String url = 'https://api.postalpincode.in/pincode/' + a.Pincode__c;
request.setEndpoint(url);
request.setMethod('GET');
HttpResponse response = p.send(request);
String jsonString = response.getBody();
System.debug(jsonString);
System.JSONParser jp = JSON.createParser(jsonString);
String places='';
while(jp.nextToken()!=NULL)
{
if(jp.getText() == 'Name')
{
jp.nextToken();
places = places + ',' + jp.getText();
System.debug(places);
}
}
a.Places__c = places;
System.debug(a.Places__c);
}
}
}
I am not able to see the 'Places__c' field getting updated on the page layout of Account object, but when I am using system.debug() for that particular account in the code, I am able to see Places__c values. But the value is not visible on Account record page. Below is the image of account record page and debug logs after saving the record and after future method is completed successfully.
We can clearly see on account record page 'Places field has no value while on debug logs we can see the value of the 'Places field.