• gazzer82
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 5
    Replies
I have a pageBlockTable in a visualforce page, in the table i am allowing users via JQuery .sortable to rearrange the order of the rows.

No, i want to store this sorting on page save, so i have created a new parameter on the product in Salesforce called sort_order that is a number field.

I would like to update the field, which is in the table and will eventually be hidden each time the rows are dragged, so that on save everything is stored.

I have the following code, which i am trying to get to loop through the table and update the fields appropriatley, but i can't work out the JQuery syntax for setting the value of the field.

Here is the code that creates the table:

            <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected">
                <apex:variable value="{!1}" var="index"> 
                <apex:pageblockTable value="{!shoppingCart}" var="s" id="shopping_cart" rowClasses="cartRow">
                    <tr data-SFid="{!index}">
                   
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Description.Label}">
                        <apex:inputField id="item_description" value="{!s.Description}" required="false"/>
                    </apex:column>
                   
                   
                   
                    <apex:column headerValue="Current ID">
                    <apex:inputField id="Current_ID" value="{!s.Sort_Order__c}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="Updated ID" value="{!index}" />
                   
                    <apex:column >
                        <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">
                            <!-- this param is how we send an argument to the controller, so it knows which row we clicked 'remove' on -->
                            <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                        </apex:commandLink>
                        <apex:variable value="{!index+1}" var="index">
                        </apex:variable>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>
                   
                   
                                       
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                        <apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                        <apex:inputField value="{!s.UnitPrice}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                   
                   </tr> 
                </apex:pageblockTable>
                </apex:variable>

It is the "Current ID" editable field, with the ID of Current_ID that i want to update.

And this is as far as i have gotten with the update script, i have it looping through the rows with the "Selected" id, but i'm not sure how to update/access the value.

    $( "[id$=shopping_cart] tbody" ).sortable({
                        update: function(event, ui) {
                        //init();
                        i = 0;
                        $("[id$=shopping_cart] tbody tr.cartRow").each(function() {
                              $this = $(this)
                              var value = $(this).find('Current_ID');
                              var value2 = $(value).find('value');
                              console.log("Checking Row " + i);
                              console.log(value);
                              console.log(value2).value;
                              i++;
                              });
                       
        })

Help greatly appreciated as i am way more an ObjectiveC person than i am a Javascript/JQuery person!

Thanks

Gareth

I have a custom page that is making a call out to the gogle maps API and displaying a map.

 

I am slo using the API to calculate the mileage betweent two location, and would like to update that info in a text field on the page, first parts works, second part doesn't. Here is the code i am am using.

 

If i look at the error log in Chrome is, Uncaught TypeError: Cannot set property 'innerHTML' of null?

 

Thanks

 

Gareth

 

 

<apex:page standardController="Opportunity">
<apex:pageBlock >
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<script type="text/javascript"
src="https://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 13px; color: red;">
<div id="map" style="width: 647px; height: 318px;"></div>

<script type="text/javascript">

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var startPostcode = "{!Opportunity.Warehouse_Postcode__c}";
var endPostcode = "{!Opportunity.R2_Shipping_Post_Code__c}";
var distanceInMeters;
var distanceInMiles;
var durationInSeconds;
var durationInMinutes;
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);

var request = {
origin: startPostcode,
destination: endPostcode,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {

distanceInMeters = response.routes[0].legs[0].distance.value;
distanceInMiles = Math.floor(distanceInMeters / 1609.344);
durationInSeconds = response.routes[0].legs[0].duration.value;
durationInMinutes = Math.floor(durationInSeconds / 60);


directionsDisplay.setDirections(response);
document.getElementById('00Nb0000004zOiz_ileinner').innerHTML = distanceInMiles;

}
});


</script>
</body>
</html>
</apex:pageBlock>
</apex:page>

Bit stuck on another one i'm afraid, i am trying to write a unit test for a bulk APEX class.

 

The class has a calllout to the google api, so i have created a static resource which i am feeding in via a mock, so i can complete testing of processing the JSON that is returned. However for some reason the response is always empty.

 

Now the very odd thing is that if i use exactly the same callout/JSON code, and the same mock code on a previous @future call, then it does return fine.

 

Here is the class:

 

global class mileage_bulk implements Database.Batchable<sObject>,

  Database.AllowsCallouts

{

global Database.QueryLocator start(Database.BatchableContext BC)

{

String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c,Shipping_Postcode_2__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';

return Database.getQueryLocator(query);

//system.debug('Executing'+query);

}

 

global void execute(Database.BatchableContext BC, List<Opportunity> scope)

{

system.debug(scope);

for(Opportunity a : scope)

{

 

        String startPostcode = null;

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        String endPostcode = null;

        String endPostcodeEncoded = null;

        if (a.R2_Shipping_Post_Code__c != null){

        endPostcode =   a.R2_Shipping_Post_Code__c;

        Pattern nonWordChar = Pattern.compile('[^\\w]');

endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');

        endPostcodeEncoded =   EncodingUtil.urlEncode(endPostcode, 'UTF-8');

            }   

        Double totalDistanceMeter = null;

        Integer totalDistanceMile = null;

       String responseBody = null;

       Boolean firstRecord = false;

        

        String ukPrefix = 'UKH';

        if (a.R2_Job_Ref__c != null){    

        if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){

        system.debug('Is Hemel Job');

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        } else {

        system.debug('Is Bromsgrove Job');

        startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');

        }

        }

        

        // build callout

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');

        req.setMethod('GET');

        req.setTimeout(60000);

        system.debug('request follows');

        system.debug(req);

 

try{  

            // callout

            HttpResponse res = h.send(req);

            

            // parse coordinates from response

            

            JSONParser parser = JSON.createParser(res.getBody());

            

            responseBody = res.getBody();

            system.debug(responseBody);

            

            while (parser.nextToken() != null) {

                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 

                    (parser.getText() == 'distance')){

                       parser.nextToken(); // object start

                       while (parser.nextToken() != JSONToken.END_OBJECT){

                           String txt = parser.getText();

                           parser.nextToken();

                           //system.debug(parser.nextToken());

                           //system.debug(txt);

                           if (firstRecord == false){

                           //if (txt == 'text'){

                               //totalDistanceMile = parser.getText();

                               system.debug(parser.getText());

                           //}

                           if (txt == 'value'){

                               totalDistanceMeter = parser.getDoubleValue();

                               double inches = totalDistanceMeter*39.3701;

                               totalDistanceMile = (integer)inches/63360;

                               system.debug(parser.getText());

                               firstRecord = true;

                           }

                           }

                       }

                    

                }

            }

  

           

        } catch (Exception e) {

        }

 

//system.debug(accountId);

        system.debug(a);

        system.debug(endPostcodeEncoded);

        system.debug(totalDistanceMeter);

        system.debug(totalDistanceMile);

           

            // update coordinates if we get back 

            if (totalDistanceMile != null){

            system.debug('Entering Function to Update Object');

                a.DistanceM__c = totalDistanceMile;

                a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;

                //update a;        

            }  

}

update scope;

}

 

 

global void finish(Database.BatchableContext BC)

{

}

}

 

and here is the test class;

 

/**

 * This class contains unit tests for validating the behavior of Apex classes

 * and triggers.

 *

 * Unit tests are class methods that verify whether a particular piece

 * of code is working properly. Unit test methods take no arguments,

 * commit no data to the database, and are flagged with the testMethod

 * keyword in the method definition.

 *

 * All test methods in an organization are executed whenever Apex code is deployed

 * to a production organization to confirm correctness, ensure code

 * coverage, and prevent regressions. All Apex classes are

 * required to have at least 75% code coverage in order to be deployed

 * to a production organization. In addition, all triggers must have some code coverage.

 * 

 * The @isTest class annotation indicates this class only contains test

 * methods. Classes defined with the @isTest annotation do not count against

 * the organization size limit for all Apex scripts.

 *

 * See the Apex Language Reference for more information about Testing and Code Coverage.

 */

@isTest

private class mileage_bulk_tests{

 

    static testMethod void myUnitTest() {

         Opportunity opp1 = new Opportunity(name = 'Google Test Opportunity',R2_Job_Ref__c = 'UKH12345',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());

 insert opp1;

 Opportunity opp2 = new Opportunity(name = 'Google Test Opportunity 2',StageName = 'qualified',CloseDate = Date.today());

 insert opp2;

 Opportunity opp3 = new Opportunity(name = 'Google Test Opportunity 3',R2_Job_Ref__c = 'UKB56789',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());

insert opp3;

 

 

StaticResourceCalloutMock mock = new StaticResourceCalloutMock();

mock.setStaticResource('googleMapsJSON');

mock.setStatusCode(200); // Or other appropriate HTTP status code

mock.setHeader('Content-Type', 'application/json'); // Or other appropriate MIME type like application/xml

 

//Set the mock callout mode

Test.setMock(HttpCalloutMock.class, mock);

 

system.debug(opp1);

system.debug(opp1.id);

 

//Call the method that performs the callout

Test.startTest();

mileage_bulk b = new mileage_bulk();

database.executeBatch((b), 10);

Test.stopTest();

    }

}

 

Help greatly appreciated!

 

Thanks

 

Gareth

 

I am obviously missing something obvious, but this query just doesn't work, and i can't work out why, can somebody assist?

 

SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c,Shipping_Postcode_2__c
FROM Opportunity
WHERE Shipping_Postcode_2__c != R2_Shipping_Post_Code__c AND R2_Shipping_Post_Code__c != null

 

Thanks!

 

Gareth

Hi All,

 

I am trying to write my first APEX Batch script and failing miserable at it, this is what i have so far, but it keeps failing with the error "Attempt to de-reference a null object" which i am a little confused about as the only comparison i have to null is on the SOQL query, which i have tested and works fine in isolation.

 

Here is the code, woudl really appreciate some pointers.

 

I am exectuting manually using:

 

mileage_bulk b = new mileage_bulk();

database.executeBatch((b), 10);

 

And the class is as follows:

 

global class mileage_bulk implements Database.Batchable<sObject>,

  Database.AllowsCallouts

{

global Database.QueryLocator start(Database.BatchableContext BC)

{

String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';

return Database.getQueryLocator(query);

}

 

global void execute(Database.BatchableContext BC, List<Opportunity> scope)

{

system.debug(scope);

for(Opportunity a : scope)

{

 

        String startPostcode = null;

        String endPostcode =   a.R2_Shipping_Post_Code__c;

        Pattern nonWordChar = Pattern.compile('[^\\w]');

endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');

        String endPostcodeEncoded =   EncodingUtil.urlEncode(endPostcode, 'UTF-8');

        Double totalDistanceMeter = null;

        Integer totalDistanceMile = null;

       String responseBody = null;

       Boolean firstRecord = false;

        

        String ukPrefix = 'UKH';    

        if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        } else {

        startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');

        }

        // build callout

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');

        req.setMethod('GET');

        req.setTimeout(60000);

 

try{  

            // callout

            HttpResponse res = h.send(req);

            

            // parse coordinates from response

            JSONParser parser = JSON.createParser(res.getBody());

            

            responseBody = res.getBody();

            //system.debug(responseBody);

            

            while (parser.nextToken() != null) {

                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 

                    (parser.getText() == 'distance')){

                       parser.nextToken(); // object start

                       while (parser.nextToken() != JSONToken.END_OBJECT){

                           String txt = parser.getText();

                           parser.nextToken();

                           //system.debug(parser.nextToken());

                           //system.debug(txt);

                           if (firstRecord == false){

                           //if (txt == 'text'){

                               //totalDistanceMile = parser.getText();

                               //system.debug(parser.getText());

                           //}

                           if (txt == 'value'){

                               totalDistanceMeter = parser.getDoubleValue();

                               double inches = totalDistanceMeter*39.3701;

                               totalDistanceMile = (integer)inches/63360;

                               system.debug(parser.getText());

                               firstRecord = true;

                           }

                           }

                       }

                    

                }

            }

            

            // update coordinates if we get back 

            if (totalDistanceMile != null){

                //a.DistanceM__c = totalDistanceMile;

                //a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;

                //a.Location__Longitude__s = lon;

                //update a;        

            }    

           

        } catch (Exception e) {

        }

 

//system.debug(accountId);

        system.debug(a);

        system.debug(endPostcodeEncoded);

        system.debug(totalDistanceMeter);

        system.debug(totalDistanceMile);

 

}

}

 

 

global void finish(Database.BatchableContext BC)

{

}

}

Hi, please exucse the newbie question, but i have been reasearching this for hours with little success.

 

I have an APEX trigger setup that has an APEX callback that updates a value on an Opportunity after pulling some data in from a web service.

 

That all works fine.

 

What i want to do now is setup and actionpoll on the page that refershes that field when the value is changed. I assume i need to do this by creating a new customforce page and adding it to the page layout. However, i cannot get the custom page to showup whe changing the page layout?

 

I would also really appreciate some help with the actual page and controller code if anyone is willing, i think i kinda have it, but it's all a bit foreign to someone coming from an ObjC background!

 

Thanks

 

Gareth

I have a pageBlockTable in a visualforce page, in the table i am allowing users via JQuery .sortable to rearrange the order of the rows.

No, i want to store this sorting on page save, so i have created a new parameter on the product in Salesforce called sort_order that is a number field.

I would like to update the field, which is in the table and will eventually be hidden each time the rows are dragged, so that on save everything is stored.

I have the following code, which i am trying to get to loop through the table and update the fields appropriatley, but i can't work out the JQuery syntax for setting the value of the field.

Here is the code that creates the table:

            <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected">
                <apex:variable value="{!1}" var="index"> 
                <apex:pageblockTable value="{!shoppingCart}" var="s" id="shopping_cart" rowClasses="cartRow">
                    <tr data-SFid="{!index}">
                   
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Description.Label}">
                        <apex:inputField id="item_description" value="{!s.Description}" required="false"/>
                    </apex:column>
                   
                   
                   
                    <apex:column headerValue="Current ID">
                    <apex:inputField id="Current_ID" value="{!s.Sort_Order__c}" style="width:70px" required="false" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="Updated ID" value="{!index}" />
                   
                    <apex:column >
                        <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">
                            <!-- this param is how we send an argument to the controller, so it knows which row we clicked 'remove' on -->
                            <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                        </apex:commandLink>
                        <apex:variable value="{!index+1}" var="index">
                        </apex:variable>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>
                   
                   
                                       
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                        <apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                        <apex:inputField value="{!s.UnitPrice}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                   
                   </tr> 
                </apex:pageblockTable>
                </apex:variable>

It is the "Current ID" editable field, with the ID of Current_ID that i want to update.

And this is as far as i have gotten with the update script, i have it looping through the rows with the "Selected" id, but i'm not sure how to update/access the value.

    $( "[id$=shopping_cart] tbody" ).sortable({
                        update: function(event, ui) {
                        //init();
                        i = 0;
                        $("[id$=shopping_cart] tbody tr.cartRow").each(function() {
                              $this = $(this)
                              var value = $(this).find('Current_ID');
                              var value2 = $(value).find('value');
                              console.log("Checking Row " + i);
                              console.log(value);
                              console.log(value2).value;
                              i++;
                              });
                       
        })

Help greatly appreciated as i am way more an ObjectiveC person than i am a Javascript/JQuery person!

Thanks

Gareth

I have a custom page that is making a call out to the gogle maps API and displaying a map.

 

I am slo using the API to calculate the mileage betweent two location, and would like to update that info in a text field on the page, first parts works, second part doesn't. Here is the code i am am using.

 

If i look at the error log in Chrome is, Uncaught TypeError: Cannot set property 'innerHTML' of null?

 

Thanks

 

Gareth

 

 

<apex:page standardController="Opportunity">
<apex:pageBlock >
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<script type="text/javascript"
src="https://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 13px; color: red;">
<div id="map" style="width: 647px; height: 318px;"></div>

<script type="text/javascript">

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var startPostcode = "{!Opportunity.Warehouse_Postcode__c}";
var endPostcode = "{!Opportunity.R2_Shipping_Post_Code__c}";
var distanceInMeters;
var distanceInMiles;
var durationInSeconds;
var durationInMinutes;
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);

var request = {
origin: startPostcode,
destination: endPostcode,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {

distanceInMeters = response.routes[0].legs[0].distance.value;
distanceInMiles = Math.floor(distanceInMeters / 1609.344);
durationInSeconds = response.routes[0].legs[0].duration.value;
durationInMinutes = Math.floor(durationInSeconds / 60);


directionsDisplay.setDirections(response);
document.getElementById('00Nb0000004zOiz_ileinner').innerHTML = distanceInMiles;

}
});


</script>
</body>
</html>
</apex:pageBlock>
</apex:page>

Bit stuck on another one i'm afraid, i am trying to write a unit test for a bulk APEX class.

 

The class has a calllout to the google api, so i have created a static resource which i am feeding in via a mock, so i can complete testing of processing the JSON that is returned. However for some reason the response is always empty.

 

Now the very odd thing is that if i use exactly the same callout/JSON code, and the same mock code on a previous @future call, then it does return fine.

 

Here is the class:

 

global class mileage_bulk implements Database.Batchable<sObject>,

  Database.AllowsCallouts

{

global Database.QueryLocator start(Database.BatchableContext BC)

{

String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c,Shipping_Postcode_2__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';

return Database.getQueryLocator(query);

//system.debug('Executing'+query);

}

 

global void execute(Database.BatchableContext BC, List<Opportunity> scope)

{

system.debug(scope);

for(Opportunity a : scope)

{

 

        String startPostcode = null;

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        String endPostcode = null;

        String endPostcodeEncoded = null;

        if (a.R2_Shipping_Post_Code__c != null){

        endPostcode =   a.R2_Shipping_Post_Code__c;

        Pattern nonWordChar = Pattern.compile('[^\\w]');

endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');

        endPostcodeEncoded =   EncodingUtil.urlEncode(endPostcode, 'UTF-8');

            }   

        Double totalDistanceMeter = null;

        Integer totalDistanceMile = null;

       String responseBody = null;

       Boolean firstRecord = false;

        

        String ukPrefix = 'UKH';

        if (a.R2_Job_Ref__c != null){    

        if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){

        system.debug('Is Hemel Job');

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        } else {

        system.debug('Is Bromsgrove Job');

        startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');

        }

        }

        

        // build callout

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');

        req.setMethod('GET');

        req.setTimeout(60000);

        system.debug('request follows');

        system.debug(req);

 

try{  

            // callout

            HttpResponse res = h.send(req);

            

            // parse coordinates from response

            

            JSONParser parser = JSON.createParser(res.getBody());

            

            responseBody = res.getBody();

            system.debug(responseBody);

            

            while (parser.nextToken() != null) {

                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 

                    (parser.getText() == 'distance')){

                       parser.nextToken(); // object start

                       while (parser.nextToken() != JSONToken.END_OBJECT){

                           String txt = parser.getText();

                           parser.nextToken();

                           //system.debug(parser.nextToken());

                           //system.debug(txt);

                           if (firstRecord == false){

                           //if (txt == 'text'){

                               //totalDistanceMile = parser.getText();

                               system.debug(parser.getText());

                           //}

                           if (txt == 'value'){

                               totalDistanceMeter = parser.getDoubleValue();

                               double inches = totalDistanceMeter*39.3701;

                               totalDistanceMile = (integer)inches/63360;

                               system.debug(parser.getText());

                               firstRecord = true;

                           }

                           }

                       }

                    

                }

            }

  

           

        } catch (Exception e) {

        }

 

//system.debug(accountId);

        system.debug(a);

        system.debug(endPostcodeEncoded);

        system.debug(totalDistanceMeter);

        system.debug(totalDistanceMile);

           

            // update coordinates if we get back 

            if (totalDistanceMile != null){

            system.debug('Entering Function to Update Object');

                a.DistanceM__c = totalDistanceMile;

                a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;

                //update a;        

            }  

}

update scope;

}

 

 

global void finish(Database.BatchableContext BC)

{

}

}

 

and here is the test class;

 

/**

 * This class contains unit tests for validating the behavior of Apex classes

 * and triggers.

 *

 * Unit tests are class methods that verify whether a particular piece

 * of code is working properly. Unit test methods take no arguments,

 * commit no data to the database, and are flagged with the testMethod

 * keyword in the method definition.

 *

 * All test methods in an organization are executed whenever Apex code is deployed

 * to a production organization to confirm correctness, ensure code

 * coverage, and prevent regressions. All Apex classes are

 * required to have at least 75% code coverage in order to be deployed

 * to a production organization. In addition, all triggers must have some code coverage.

 * 

 * The @isTest class annotation indicates this class only contains test

 * methods. Classes defined with the @isTest annotation do not count against

 * the organization size limit for all Apex scripts.

 *

 * See the Apex Language Reference for more information about Testing and Code Coverage.

 */

@isTest

private class mileage_bulk_tests{

 

    static testMethod void myUnitTest() {

         Opportunity opp1 = new Opportunity(name = 'Google Test Opportunity',R2_Job_Ref__c = 'UKH12345',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());

 insert opp1;

 Opportunity opp2 = new Opportunity(name = 'Google Test Opportunity 2',StageName = 'qualified',CloseDate = Date.today());

 insert opp2;

 Opportunity opp3 = new Opportunity(name = 'Google Test Opportunity 3',R2_Job_Ref__c = 'UKB56789',R2_Shipping_Post_Code__c = 'AL35QW',StageName = 'qualified',CloseDate = Date.today());

insert opp3;

 

 

StaticResourceCalloutMock mock = new StaticResourceCalloutMock();

mock.setStaticResource('googleMapsJSON');

mock.setStatusCode(200); // Or other appropriate HTTP status code

mock.setHeader('Content-Type', 'application/json'); // Or other appropriate MIME type like application/xml

 

//Set the mock callout mode

Test.setMock(HttpCalloutMock.class, mock);

 

system.debug(opp1);

system.debug(opp1.id);

 

//Call the method that performs the callout

Test.startTest();

mileage_bulk b = new mileage_bulk();

database.executeBatch((b), 10);

Test.stopTest();

    }

}

 

Help greatly appreciated!

 

Thanks

 

Gareth

 

I am obviously missing something obvious, but this query just doesn't work, and i can't work out why, can somebody assist?

 

SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c,Shipping_Postcode_2__c
FROM Opportunity
WHERE Shipping_Postcode_2__c != R2_Shipping_Post_Code__c AND R2_Shipping_Post_Code__c != null

 

Thanks!

 

Gareth

Hi All,

 

I am trying to write my first APEX Batch script and failing miserable at it, this is what i have so far, but it keeps failing with the error "Attempt to de-reference a null object" which i am a little confused about as the only comparison i have to null is on the SOQL query, which i have tested and works fine in isolation.

 

Here is the code, woudl really appreciate some pointers.

 

I am exectuting manually using:

 

mileage_bulk b = new mileage_bulk();

database.executeBatch((b), 10);

 

And the class is as follows:

 

global class mileage_bulk implements Database.Batchable<sObject>,

  Database.AllowsCallouts

{

global Database.QueryLocator start(Database.BatchableContext BC)

{

String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';

return Database.getQueryLocator(query);

}

 

global void execute(Database.BatchableContext BC, List<Opportunity> scope)

{

system.debug(scope);

for(Opportunity a : scope)

{

 

        String startPostcode = null;

        String endPostcode =   a.R2_Shipping_Post_Code__c;

        Pattern nonWordChar = Pattern.compile('[^\\w]');

endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');

        String endPostcodeEncoded =   EncodingUtil.urlEncode(endPostcode, 'UTF-8');

        Double totalDistanceMeter = null;

        Integer totalDistanceMile = null;

       String responseBody = null;

       Boolean firstRecord = false;

        

        String ukPrefix = 'UKH';    

        if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        } else {

        startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');

        }

        // build callout

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');

        req.setMethod('GET');

        req.setTimeout(60000);

 

try{  

            // callout

            HttpResponse res = h.send(req);

            

            // parse coordinates from response

            JSONParser parser = JSON.createParser(res.getBody());

            

            responseBody = res.getBody();

            //system.debug(responseBody);

            

            while (parser.nextToken() != null) {

                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 

                    (parser.getText() == 'distance')){

                       parser.nextToken(); // object start

                       while (parser.nextToken() != JSONToken.END_OBJECT){

                           String txt = parser.getText();

                           parser.nextToken();

                           //system.debug(parser.nextToken());

                           //system.debug(txt);

                           if (firstRecord == false){

                           //if (txt == 'text'){

                               //totalDistanceMile = parser.getText();

                               //system.debug(parser.getText());

                           //}

                           if (txt == 'value'){

                               totalDistanceMeter = parser.getDoubleValue();

                               double inches = totalDistanceMeter*39.3701;

                               totalDistanceMile = (integer)inches/63360;

                               system.debug(parser.getText());

                               firstRecord = true;

                           }

                           }

                       }

                    

                }

            }

            

            // update coordinates if we get back 

            if (totalDistanceMile != null){

                //a.DistanceM__c = totalDistanceMile;

                //a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;

                //a.Location__Longitude__s = lon;

                //update a;        

            }    

           

        } catch (Exception e) {

        }

 

//system.debug(accountId);

        system.debug(a);

        system.debug(endPostcodeEncoded);

        system.debug(totalDistanceMeter);

        system.debug(totalDistanceMile);

 

}

}

 

 

global void finish(Database.BatchableContext BC)

{

}

}