• virk
  • NEWBIE
  • 9 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 21
    Replies
I want to divide a datatable or fully control the presentation of it in vf page if there are specified number of records in the list returned by the controller.If there are more reords I want the table to be shifted on next page which is done by default but only for list having records greater than 14 records. I am using th following code but it does not work for me because if the second data table is displayed it has the footer row at the end of each table but I want it to appear only on the last table if it is divided by default. Can someone please help how can I control the datatable presentation myself in the code.

<apex:component >
    <apex:attribute name="cotationTechniques" description="ControllerObj" type="Cotation_technique_Op__c[]" required="true"/>
    <apex:attribute name="sumCumac" description="Somme des cumacs" type="Cotation_technique_Op__c" required="true"/>
    <!--<apex:attribute name="rows"  description="wrapper rows" type="RowWrapper[]" required="true"/>-->
    <apex:attribute name="rows"  description="wrapper rows" type="RowWrapper" required="true"/>
<apex:repeat value="{!rows.mapCotTechOp}" var="key" rendered="{!cotationTechniques.size != null && cotationTechniques.size > 6 && cotationTechniques.size < 14}"> <apex:datatable value="{!rows.mapCotTechOp[key]}" var="cotTech" styleClass="fosts" border="1" cellpadding="0" cellspacing="1" style="page-break-inside:avoid !important;"> <apex:column > <apex:facet name="header">Référence Action Standard</apex:facet> <apex:outputField value="{!cotTech.fost__r.Name}"/> </apex:column> <apex:column > <apex:facet name="header">Volume de kWh cumac</apex:facet> <apex:facet name="footer"><apex:outputField rendered = "{!key = '1'}" value="{!sumCumac.PIL_PRI_CEE_reel__c}"/></apex:facet> <apex:outputField value="{!cotTech.PIL_PRI_CEE_reel__c}"/> </apex:column> </apex:datatable> </apex:repeat> <apex:datatable id="AIFTable" value="{!cotationTechniques}" var="cotTech" styleClass="fosts" border="1" cellpadding="0" cellspacing="1" style="page-break-inside:avoid !important;" rendered="{!NOT(cotationTechniques.size > 6 && cotationTechniques.size < 14)}" > <apex:column > <apex:facet name="header">Référence Action Standard</apex:facet> <apex:outputField value="{!cotTech.fost__r.Name}"/> </apex:column> <apex:column > <apex:facet name="header">Volume de kWh cumac</apex:facet> <apex:facet name="footer"><apex:outputField value="{!sumCumac.PIL_PRI_CEE_reel__c}"/></apex:facet> <apex:outputField value="{!cotTech.PIL_PRI_CEE_reel__c}"/> </apex:column> </apex:datatable></apex:component>

If there are 6 records retuened in the list then it is displayed on the same page but if there are more than 6 and less than 14 records it shifts to next page and leaves the previous page empty. This is why I have put a condition on the first part if there are more than 6 and less than 14  records data table is divided in two tables else it is displayed as default. In default case if it has more than 14 records it is displayed good on two pages but the footer is shown on two tables rather I want footer only on second page or where the list ends.

Also the page is rendered as pdf.

Thanks.
  • November 23, 2017
  • Like
  • 0
Can someone help me in writing test for the following code? Specially for the bold text.


global class UpdateStatusAcc implements Database.Batchable<sObject> {
 
 LogAccountTasks__c logAccTasks;
 Boolean flag = false;
 //List<Account> toUpdate;
 global String query;
 global UpdateStatusAcc() {
  query = 'SELECT Id, AccountId__c, AccRecordTypeId__c, AccRTDeveloperName__c, Etat_actuel_de_la_relation_geo__c,Etat_futur_de_la_relation_geo__c, Flag__c, Type_de_reseau__c, CreationDate__c FROM LogAccountTasks__c WHERE flag__c=false';
 }
 
 global Database.QueryLocator start(Database.BatchableContext BC) {
  //String query =
  return Database.getQueryLocator(query);
 }
    global void execute(Database.BatchableContext BC, List<LogAccountTasks__c> lstLogAccountTasks) {
     System.debug('Test');
  List<Id> accIds = new List<Id>();
  List<LogAccountTasks__c> lstTasks; //= new <List>logAccountTasks();
  List<Id> lstAccIds;
  //List<Account> TrigNew;
  Map<id, Account> TrigoldMap;
  List<Account> lstmemoryAcc;
  Account tmpAcc;
  if (lstLogAccountTasks == null || !lstLogAccountTasks.isEmpty()) {
          return;
  }
  
  //Add the AccountId to the Ids List
  for(LogAccountTasks__c LogAcc : lstLogAccountTasks) {
   //Prepare oldMap
   System.debug('inside new list');
   lstAccIds.add(LogAcc.AccountId__c);
   //Prepare List for simulate Trignew
   tmpAcc = null;
   tmpAcc.Id = LogAcc.AccountId__c;
   tmpAcc.Etat_relation_GEO__c = LogAcc.Etat_futur_de_la_relation_geo__c;
   tmpAcc.RecordTypeId = LogAcc.AccRecordTypeId__c;
   tmpAcc.R_seau_int_gr__c = LogAcc.Type_de_reseau__c;
   lstmemoryAcc.add(tmpAcc);
  }

  //create Account object List
  //TrigNew = [SELECT Id, Name, RecordTypeID, R_seau_int_gr__c, Etat_relation_GEO__c FROM Account WHERE Id=:lstAccIds];
  //Create a virtual object of Account
//  for(lstLogAccountTasks)
        //TrigoldMap = new Map<Id, Account>([SELECT Id FROM Account], [SELECT Etat_relation_GEO__c FROM Account]);
        for (Account acc : [select Id, Etat_relation_GEO__c from Account  WHERE Id=:lstAccIds]) {
         System.debug('inside old map');
            TrigoldMap.put(acc.Id, acc);
        }
  UpdateStatus.hierarchyAccountDeploiment(lstmemoryAcc, TrigoldMap);
        UpdateStatus.hierarchyAccountTerminer(lstmemoryAcc, TrigoldMap);
        UpdateStatus.terminerFilByAccount(lstmemoryAcc);
/*  if (logAccountTasks != null && logAccountTasks.size() > 0) {
   for (Account a : logAccountTasks)
        a.Etat_relation_GEO__c = 'Déploiement';
  }
*/
//     update logAccountTasks;
//     flag=true;
 }
 
 global void finish(Database.BatchableContext BC) {
  //if(flag == true && logAccountTasks != null && logAccountTasks.size() > 0)
  // delete logAccountTasks;
  //System.debug('hello');
 }
 
}

thanks in advance.
  • August 21, 2017
  • Like
  • 0
Hello Salesforce Expertise

Can someone please help me in writing test method for this code?

 List<Id> accIds = new List<Id>();
  List<LogAccountTasks__c> lstTasks; //= new <List>logAccountTasks();
  List<Id> lstAccIds;
  //List<Account> TrigNew;
  Map<id, Account> TrigoldMap;
  List<Account> lstmemoryAcc;
  Account tmpAcc;
  if (lstLogAccountTasks == null || !lstLogAccountTasks.isEmpty()) {
          return;
  }
  
  //Add the AccountId to the Ids List
  for(LogAccountTasks__c LogAcc : lstLogAccountTasks) {
   //Prepare oldMap
   lstAccIds.add(LogAcc.AccountId__c);
   //Prepare List for simulate Trignew
   tmpAcc = null;
   tmpAcc.Id = LogAcc.AccountId__c;
   tmpAcc.Etat_relation_GEO__c = LogAcc.Etat_futur_de_la_relation_geo__c;
   tmpAcc.RecordTypeId = LogAcc.AccRecordTypeId__c;
   tmpAcc.R_seau_int_gr__c = logAcc.Type_de_reseau__c;
   lstmemoryAcc.add(tmpAcc);
  }
for (Account acc : [select Id, Etat_relation_GEO__c from Account  WHERE Id=:lstAccIds]) {
            TrigoldMap.put(acc.Id, acc);
        }
  UpdateStatus.hierarchyAccountDeploiment(lstmemoryAcc, TrigoldMap);
        UpdateStatus.hierarchyAccountTerminer(lstmemoryAcc, TrigoldMap);
        UpdateStatus.terminerFilByAccount(lstmemoryAcc);

This is really urgent.
  • August 18, 2017
  • Like
  • 0
Can someone please help me in writing the test method for the following code?

global class UpdateStatusAcc implements Database.Batchable<sObject> {
 
 String query;
 LogAccountTasks__c logAccTasks;
 Boolean flag = false;
 List<Account> toUpdate;
 global UpdateStatusAcc() {
  
 }
 
 global Database.QueryLocator start(Database.BatchableContext BC) {
  String query = 'SELECT Id, AccountId__c, AccRecordTypeId__c, AccRTDeveloperName__c, Etat_actuel_de_la_relation_geo__c,Etat_futur_de_la_relation_geo__c, Flag__c, Type_de_reseau__c, CreationDate__c FROM LogAccountTasks__c WHERE flag__c=true ';
  return Database.getQueryLocator(query);
 }
    global void execute(Database.BatchableContext BC, List<LogAccountTasks__c> lstLogAccountTasks) {
  List<Id> accIds = new List<Id>();
  List<LogAccountTasks__c> lstTasks; //= new <List>logAccountTasks();
  List<Id> lstAccIds;
  //List<Account> TrigNew;
  Map<id, Account> TrigoldMap;
  List<Account> lstmemoryAcc;
  Account tmpAcc;
  if (lstLogAccountTasks == null || !lstLogAccountTasks.isEmpty()) {
          return;
  }
  
  //Add the AccountId to the Ids List
  for(LogAccountTasks__c LogAcc : lstLogAccountTasks) {
   //Prepare oldMap
   lstAccIds.add(LogAcc.AccountId__c);
   //Prepare List for simulate Trignew
   tmpAcc = null;
   tmpAcc.Id = LogAcc.AccountId__c;
   tmpAcc.Etat_relation_GEO__c = LogAcc.Etat_futur_de_la_relation_geo__c;
   tmpAcc.RecordTypeId = LogAcc.AccRecordTypeId__c;
   tmpAcc.R_seau_int_gr__c = logAcc.Type_de_reseau__c;
   lstmemoryAcc.add(tmpAcc);
  }
  //create Account object List
  //TrigNew = [SELECT Id, Name, RecordTypeID, R_seau_int_gr__c, Etat_relation_GEO__c FROM Account WHERE Id=:lstAccIds];
  //Create a virtual object of Account
//  for(lstLogAccountTasks)
        //TrigoldMap = new Map<Id, Account>([SELECT Id FROM Account], [SELECT Etat_relation_GEO__c FROM Account]);
        for (Account acc : [select Id, Etat_relation_GEO__c from Account  WHERE Id=:lstAccIds]) {
            TrigoldMap.put(acc.Id, acc);
        }
  UpdateStatus.hierarchyAccountDeploiment(lstmemoryAcc, TrigoldMap);
/*  if (logAccountTasks != null && logAccountTasks.size() > 0) {
   for (Account a : logAccountTasks)
        a.Etat_relation_GEO__c = 'Déploiement';
  }
*/
//     update logAccountTasks;
//     flag=true;
 }
 
 global void finish(Database.BatchableContext BC) {
  //if(flag == true && logAccountTasks != null && logAccountTasks.size() > 0)
  // delete logAccountTasks;
  //System.debug('hello');
 }
 
}

Test Code

@isTest
private class UpdateStatusAccTest {
 
 @isTest(seeAllData=true) static void test_updateStatusAcc() {
  
  List<LogAccountTasks__c> lstAccountTasks = new List<LogAccountTasks__c>();
   String aId = '00561000001DTdh';
   LogAccountTasks__c logAccountTask;
   //0123E00000006VZQAY
  // Implement test code
     Test.startTest();
   List<Account> lstTestAcc = [SELECT Id, Name, RecordTypeId, RecordType.DeveloperName, Etat_relation_geo__c, R_seau_int_gr__c FROM Account WHERE Etat_relation_geo__c='Terminé' LIMIT 4];
         // TEST SUR statut "Déploiement"
         for(Account myacc : lstTestAcc) {
             logAccountTask = new LogAccountTasks__c();
             logAccountTask.Name =myacc.Name;
             logAccountTask.AccRecordTypeId__c = aId;
             logAccountTask.AccRTDeveloperName__c = myacc.RecordType.DeveloperName;
             logAccountTask.AccountId__c = myacc.Id;
             logAccountTask.Etat_actuel_de_la_relation_geo__c = 'Terminé';
             logAccountTask.Etat_futur_de_la_relation_geo__c = 'Déploiement';
             logAccountTask.Flag__c = true;
             logAccountTask.CreationDate__c = Date.today();
             logAccountTask.Type_de_reseau__c = myacc.R_seau_int_gr__c;            
             lstAccountTasks.add(logAccountTask);
         }
         // TEST SUR statut "Terminé"
   lstTestAcc = [SELECT Id, Name, RecordTypeId, RecordType.DeveloperName, Etat_relation_geo__c, R_seau_int_gr__c FROM Account WHERE Etat_relation_geo__c='Déploiement' LIMIT 4];
         for(Account myacc : lstTestAcc) {
             logAccountTask = new LogAccountTasks__c();
             logAccountTask.Name =myacc.Name;
             logAccountTask.AccRecordTypeId__c = aId;
             logAccountTask.AccRTDeveloperName__c = myacc.RecordType.DeveloperName;
             logAccountTask.AccountId__c = myacc.Id;
             logAccountTask.Etat_actuel_de_la_relation_geo__c = 'Déploiement';
             logAccountTask.Etat_futur_de_la_relation_geo__c = 'Terminé';
             logAccountTask.Flag__c = true;
             logAccountTask.CreationDate__c = Date.today();
             logAccountTask.Type_de_reseau__c = myacc.R_seau_int_gr__c;            
             lstAccountTasks.add(logAccountTask);
         }
         insert lstAccountTasks;
        
         List<Account> lstAccount;
         for(LogAccountTasks__c logAccTask : lstAccountTasks){
          Account acc = new Account();
          acc.Id = logAccTask.AccountId__c;
          acc.Etat_relation_GEO__c = logAccTask.Etat_futur_de_la_relation_geo__c;
          acc.RecordTypeId = logAccTask.AccRecordTypeId__c;
    acc.R_seau_int_gr__c = logAccTask.Type_de_reseau__c;
    lstAccount.add(acc);
         }
     UpdateStatusAcc updateSatusAcc = new UpdateStatusAcc();
  ID idBatch = Database.executeBatch(updateSatusAcc);
      System.assert(!lstAccountTasks.isEmpty());
      System.assertNOTEquals(logAccountTask.AccountId__c,null);
         System.debug('test_updateStatusAcc ('+ idBatch +') : simulation tasks ');
     Test.stopTest();
     //List<Account> lstAccountLogResults = [SELECT Id FROM Account];
     //System.debug('list result' + lstAccountLogResults.size());
 
 }
 
}

I have already written some test code given as follows.

But I am not sure of the last snippet of Account objects. Whether it is right or not.

Thanks in advance.


 
  • August 17, 2017
  • Like
  • 0
Can someone help me in writing a single query to retrieve old data and new data for the oparticular condition in if satatement?

List Account accs = Trigger.newMap.keySet() ;

 for (Account a : accs)
            if (a.RecordTypeID == '012D00000002qdE' && a.R_seau_int_gr__c == true && a.Etat_relation_GEO__c == 'Déploiement' && (oldmap == null || oldMap.get(a.Id).Etat_relation_GEO__c != 'Déploiement'))
            {
                hasHierarchy = true;
                accIds.add(a.id);
                while (hasHierarchy)
                {
                    List<Account> res = [SELECT id, Etat_relation_GEO__c FROM Account WHERE Etat_relation_GEO__c != 'Terminé' AND parentId IN :accIds];
                    accIds.clear();
                    if (res == null || res.size() == 0)
                        hasHierarchy = false;
                    for (Account aa : res)
                    {
                        accIds.add(aa.id);
                        toUpdate.add(aa);
                    }
                }
            }
 
  • August 16, 2017
  • Like
  • 0
This is called from a trigger which passes the list of new map and old map.

 public static void hierarchyAccountDeploiment(List<Account> accs, Map<Id, Account> oldMap)
    {
        List<Id> accIds = new List<Id>();
        Boolean hasHierarchy;
        List<Account> toUpdate = new List<Account>();

        for (Account a : accs)
            if (a.RecordTypeID == '012D00000002qdE' && a.R_seau_int_gr__c == true && a.Etat_relation_GEO__c == 'Déploiement' && (oldmap == null || oldMap.get(a.Id).Etat_relation_GEO__c != 'Déploiement'))
            {
                hasHierarchy = true;
                accIds.add(a.id);
                while (hasHierarchy)
                {
                    List<Account> res = [SELECT id, Etat_relation_GEO__c FROM Account WHERE Etat_relation_GEO__c != 'Terminé' AND parentId IN :accIds];
                    accIds.clear();
                    if (res == null || res.size() == 0)
                        hasHierarchy = false;
                    for (Account aa : res)
                    {
                        accIds.add(aa.id);
                        toUpdate.add(aa);
                    }
                }
            }
        for (Account a : toUpdate)
            a.Etat_relation_GEO__c = 'Déploiement';
        if (toUpdate != null && toUpdate.size() > 0)
            update toUpdate;
    }

Any help will be really helpful.
  • August 11, 2017
  • Like
  • 0
Can someone help me in writing a code snippet for these methods:

public static void hierarchyAccountDeploiment(List<Account> accs, Map<Id, Account> oldMap)
    {
        List<Id> accIds = new List<Id>();
        Boolean hasHierarchy;
        List<Account> toUpdate = new List<Account>();

        for (Account a : accs)
            if (a.RecordTypeID == '012D00000002qdE' && a.R_seau_int_gr__c == true && a.Etat_relation_GEO__c == 'Déploiement' && (oldmap == null || oldMap.get(a.Id).Etat_relation_GEO__c != 'Déploiement'))
            {
                hasHierarchy = true;
                accIds.add(a.id);
                while (hasHierarchy)
                {
                    List<Account> res = [SELECT id, Etat_relation_GEO__c FROM Account WHERE Etat_relation_GEO__c != 'Terminé' AND parentId IN :accIds];
                    accIds.clear();
                    if (res == null || res.size() == 0)
                        hasHierarchy = false;
                    for (Account aa : res)
                    {
                        accIds.add(aa.id);
                        toUpdate.add(aa);
                    }
                }
            }
        for (Account a : toUpdate)
            a.Etat_relation_GEO__c = 'Déploiement';
        if (toUpdate != null && toUpdate.size() > 0)
            update toUpdate;
    }


    public static void hierarchyAccountTerminer(List<Account> accs, Map<Id, Account> oldMap)
    {
        List<Id> accIds = new List<Id>();
        Boolean hasHierarchy;
        List<Account> toUpdate = new List<Account>();

        for (Account a : accs)
            if (a.RecordTypeID == '012D00000002qdE' && a.R_seau_int_gr__c == true && a.Etat_relation_GEO__c == 'Terminé' && (oldmap == null || oldMap.get(a.Id).Etat_relation_GEO__c != 'Terminé'))
            {
                hasHierarchy = true;
                accIds.add(a.id);
                while (hasHierarchy)
                {
                    List<Account> res = [SELECT id, Etat_relation_GEO__c FROM Account WHERE parentId IN :accIds];
                    accIds.clear();
                    if (res == null || res.size() == 0)
                        hasHierarchy = false;
                    for (Account aa : res)
                    {
                        accIds.add(aa.id);
                        toUpdate.add(aa);
                    }
                }
            }
        for (Account a : toUpdate)
            a.Etat_relation_GEO__c = 'Terminé';
        if (toUpdate != null && toUpdate.size() > 0)
            update toUpdate;
    }

public static void terminerFilByAccount(List<Account> accs)
    {
        List<Id> accIds = new List<Id>();
        List<Contexte__c> toUpdate = new List<Contexte__c>();

        for (Account a : accs)
            if (a.Etat_relation_GEO__c == 'Terminé')
                accIds.add(a.id);
        for (Contexte__c fil : [SELECT id, Statut__c FROM Contexte__c WHERE (PART_ETX__c IN :accIds OR PART_Siege__c IN :accIds OR PART_CA__c IN :accIds) AND Statut__c != 'Terminé'])
            if (allowedToChangeStatus(fil.Statut__c, 'Terminé'))
            {
                fil.Statut__c = 'Terminé';
                toUpdate.add(fil);
            }
        if (toUpdate != null && toUpdate.size() > 0)
            update toUpdate;
    }

I am calling these methods from a trigger

Trigger method

if (trigger.isAfter && (trigger.isInsert || trigger.isUpdate))
    {
        UpdateStatus.hierarchyAccountDeploiment(trigger.new, trigger.oldMap);
        UpdateStatus.hierarchyAccountTerminer(trigger.new, trigger.oldMap);
        UpdateStatus.terminerFilByAccount(trigger.new);
    }

I want to autmate this. If there is a batch callling this trigger it should check the log table of thousands of records for the fields change in status and run the soql, call the respective methods and empty the table of satus change.

I am totally new to this kind of coding any sort of help will be kind.

Thanks,
  • August 10, 2017
  • Like
  • 0
Hello All,

I want to get substring of a date string in visualforce page inside fullcalendar. Can someone please help how to get it? I am trying to use

{uniteActiviteATP.substring(6,10)};

where uniteActiviteATP is string type data from controller and having a date in side it.

thanks in advance.
  • June 02, 2014
  • Like
  • 0
Hello,

I want to test a trigger to calculate Location latitude and location longitude for a contact which is calling another method which is using webservice callout to calculate these parameters. However in my code I am not using this callout if the test is running and passing hard coded response instead. 

here is my code:

@future(callout=true)
    public static void GeoCodeAddress(id contactid)
    {
        // format the string for the Bing Maps engine
        shouldIRun.stopTrigger();
       
        String FormattedAddress;
        try
        {
        FormattedAddress = BuildAddressString(contactId);
        }
        catch (exception e)
        {
            return;
        }

        String key = 'AqiKi39Ge5Y57NRLwSrXTft8MU8UIHH5BR-lPz3tYyNBwU6Fzf-lSIjpxV7C5utk';//getAPIKey();
        integer n = 0;
        if (!String.isBlank(FormattedAddress)) {
           
            string GeoCodeRequestURL = 'http://dev.virtualearth.net/REST/v1/Locations?'+ FormattedAddress + '&key=' + key;// + '&maxResults=1';
            if (test.IsRunningTest() == false) {
           
            // Setup and make the HTTP callout
            HttpRequest GeoCodeRequest = new HttpRequest();
            Http GeoCodeHttp = new Http();              
            GeoCodeRequest.setMethod('GET');           
            GeoCodeRequest.setEndpoint(GeoCodeRequestURL);
            GeoCodeRequest.setTimeout(120000);
           
                 HttpResponse GeoCodeResponse = GeoCodeHttp.send(GeoCodeRequest);
                 ParseGeoCodeJSONReponse(GeoCodeResponse.getBody(), contactId);
               
             //CurrentGeoCodeResult = ParseGeoCodeJSONReponse(GeoCodeResponse.getBody()); 
             } else {
                 System.debug('Tst method');
                 String GeoCodeResponse1 = '{"Point": { "coordinates": [ -86.8142376, 33.5195411, 0 ] } } ';
                 ParseGeoCodeJSONReponse(GeoCodeResponse1, contactId);
                 //CurrentGeoCodeResult = ParseGeoCodeJSONReponse(GeoCodeResponse);           
             } // Istest == false   
       }
    } // GeoCodeAddress

    /**
     * Builds the string for use in the URL from the address of the given contact
     * @param contactid Id of the contact whose address we want to build
     * @return String
     */
   private static string BuildAddressString(id contactId) {
   
      // Example String: /US/WA/98052/Redmond/1%20Microsoft%20Way
      // Note that 1+Microsoft+Way is techinically in the UTF-8 spec the same as above
      // however, Microsoft doesn't follow that and must have %20 so we can't use urlEncode function
      contact c = [SELECT MailingCity,MailingCountry,MailingPostalCode,MailingState,MailingStreet,Location__Latitude__s,Location__Longitude__s FROM contact WHERE id =: contactId];
      // create an address string
        String Address = '';      
         if(c.MailingCity != null){
           if(c.MailingCountry != null) {
               c.MailingCountry = c.MailingCountry.Replace(' ', '%20');
               Address += 'CountryRegion=' + c.MailingCountry;        
            } else {
               Address = 'CountryRegion=' + 'FR';
           }// Country
           if(c.MailingCity != null){
               c.MailingCity = c.MailingCity.Replace(' ', '%20');
               Address += '&locality=' + c.MailingCity;
           } // Postal Code
           if(c.MailingPostalCode != null) {
               c.MailingPostalCode = c.MailingPostalCode.Replace(' ', '%20');
                Address += '&postalCode=' + c.MailingPostalCode;
           } // City
                 
           if(c.MailingStreet != null) {
             // Bing has some issues:
             //     1. It wants %20 instead of spaces
             //     2. It won't geocode PO Boxes to the city - so remove them
             //     3. It doesn't like the # symbol in the address so remove them
             //     4. It won't process an address than ends in a period
          
               c.MailingStreet = c.MailingStreet.Replace(' ', '%20');                             
               c.MailingStreet = c.MailingStreet.toUpperCase();
               c.MailingStreet = c.MailingStreet.Replace('P.O. BOX', '');
               c.MailingStreet = c.MailingStreet.Replace('#', '');
          
               // Bing has problems with addresses that end in periods, so just remove them
               if (c.MailingStreet.EndsWith('.') == true ) {
                   c.MailingStreet = c.MailingStreet.RemoveEnd('.');
               }
                   Address += '&addressLine=' + c.MailingStreet;                      
               } // Street   
                // remove any line breaks
                Address = Address.replace('\n',' ');
                Address = Address.replace('\r',' ');                   
        }                       
        return Address;
    }
   
    /**
     * Parses a geocoded response and updates the given contact with these informations
     * @param ResponseBody A json response to parse
     * @param contactId Id of the contact we want to update
     * @return void
     */
    private static void ParseGeoCodeJSONReponse(String ResponseBody, Id contactId) {

        //GeoCodeResult ReturnGeoCodeResult = IncomingGeoCodeResult;
         
       JSONParser parser = JSON.createParser(ResponseBody);
       
       String StatusResult = '';
       
       contact c = [SELECT Location__Latitude__s,Location__Longitude__s FROM contact WHERE id =: contactId];
        
       while (parser.nextToken() != null) {
          if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
              (parser.getText() == 'statusDescription')) {
                  parser.nextToken();
                  StatusResult = parser.getText();
                  //ReturnGeoCodeResult.Status = StatusResult;
                  break;
          } // if status         
       }  // loop thru looking for Status
    
        if (test.IsRunningTest() == true)
            StatusResult='OK';
       
            if (StatusResult == 'OK') {
                // parse the results from the start again
                parser = JSON.createParser(ResponseBody);
                while (parser.nextToken() != null) {
                  if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
                  (parser.getText() == 'coordinates')) {
                      // skip to the [
                      parser.nextToken();
                      // now get the first value
                      parser.nextToken();
                      c.Location__Latitude__s = parser.getDoubleValue();                         
                      // now get the 2nd value
                      parser.nextToken();                                                                                                                 
                      c.Location__Longitude__s = parser.getDoubleValue();
                  } // if point   
                } // while (parser.nextToken() != null)
             } 
         if (test.IsRunningTest() == false) {
              update c;
         }
    }
       
}


but test fails saying that "Methods defined as TestMethod do not support Web service callouts, test skipped". In developer console this method finishes properly and after it enters in to another tirgger inside managed package and fails. Please help if someone has any idea. Is there any way to avoid triggers inside managed package from running on execution of test method testing trigger on the same object?

Thanks in advance.
  • April 30, 2014
  • Like
  • 0
Hello,

How can I show header on visual force page with google map in the page. Now if I try to set shoheader to true in <apex:page> tag it stops displaiyng the header.. Please if anyone can give any idea it will be great..
  • January 09, 2014
  • Like
  • 0

I have master detail relationship between Book and Lents object. I want a control in order to avoida  book to be issued second time. I have added following code on Lent object creation before inserting I am checking if Book is already in OldMap it should give an error mesage else it should insert the record. But the code is not working:

 

trigger UpdateCount on Lent__c (before insert,after insert,after delete) {
List<Contact> counts_toUpdate = new List<Contact>();
Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

if(trigger.isinsert){
List<Lent__c> counts =[select Book__c,Contact__c, Contact__r.Count__c,Book__r.Name
from Lent__c where id IN :Trigger.new FOR UPDATE];

for(Lent__c lent:counts){
if((lent.Book__c!= null) && (lent.Book__c != Trigger.oldMap.get(lent.id).Book__c))
{
lent.Book__c.addError('Another new lead has the same email address.');
}else{
contact_newCount_Map.put(lent.Contact__c, Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);
}}
}
else if(trigger.isdelete){
Set<Id> contactIds = new Set<Id>();
for (Lent__c l : Trigger.old)
contactIds.add(l.Contact__c);
//List<Lent__c> counts = [select Contact__c, Contact__r.Count__c
//from Lent__c where id IN :contactIds];
Map<Id,Contact> oldContacts = new Map<Id,Contact>([SELECT Count__c From Contact where Id IN :contactIds]);
for(Lent__c lent : Trigger.old)
contact_newCount_map.put(lent.Contact__c, Integer.valueOf(oldContacts.get(lent.Contact__c).Count__c == null ? 0 : oldContacts.get(lent.Contact__c).Count__c ) -1);
}

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){
con.Count__c=contact_newCount_Map.get(con.id);
counts_toUpdate.add(con);
}

update counts_toUpdate;
}

 

Someone please help.

  • September 02, 2013
  • Like
  • 0

I want to update a count on Contact object after a new record is inserted or deleted on Lents object. My code is working fine to update the count by 1 but is not decreasing its value by 1 please help me:

 

trigger UpdateCount on Lent__c (after insert,after delete) {
List<Contact> counts_toUpdate = new List<Contact>();
Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

if(trigger.isinsert){
List<Lent__c> counts =[select Contact__c, Contact__r.Count__c
from Lent__c where id IN :Trigger.new FOR UPDATE];
for(Lent__c lent:counts){
contact_newCount_Map.put(lent.Contact__c, Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);
}
}
else{
Set<Id> contactIds = new Set<Id>();
for (Lent__c l : Trigger.old)
contactIds.add(l.Contact__c);
List<Lent__c> counts = [select Contact__c, Contact__r.Count__c
from Lent__c where id IN :contactIds];
Map<Id,Contact> oldContacts = new Map<Id,Contact>([SELECT Count__c From Contact where Id IN :contactIds]);
for(Lent__c lent : counts)
contact_newCount_map.put(lent.Contact__c, Integer.valueOf(oldContacts.get(lent.Contact__c).Count__c == null ? 0 : oldContacts.get(lent.Contact__c).Count__c ) -1);
}

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){
con.Count__c=contact_newCount_Map.get(con.id);
counts_toUpdate.add(con);
}

update counts_toUpdate;
}

  • September 01, 2013
  • Like
  • 0

I am trying to update  a count field on standard object Contact after insert or delete of Lents object. The code is as following but it does not work for deletion:

 

trigger UpdateCount on Lent__c (after insert,after delete) {

List<Contact> counts_toUpdate = new List<Contact>();

Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

 

if(trigger.isinsert){

List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c

from Lent__c where id IN :Trigger.new FOR UPDATE];

for(Lent__c lent:counts){

contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);

}

}

else{

List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c

from Lent__c where id IN :Trigger.old FOR UPDATE];

for(Lent__c lent:counts){

contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) - 1);

}

}

 

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){

con.Count__c=contact_newCount_Map.get(con.id);

counts_toUpdate.add(con);

}

 

update counts_toUpdate;

}

 

Please help in finding the problem.

trigger UpdateCount on Lent__c (after insert,after delete) {
List<Contact> counts_toUpdate = new List<Contact>();
Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

if(trigger.isinsert){
List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c
from Lent__c where id IN :Trigger.new FOR UPDATE];
for(Lent__c lent:counts){
contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);
}
}
else{
List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c
from Lent__c where id IN :Trigger.old FOR UPDATE];
for(Lent__c lent:counts){
contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) - 1);
}
}

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){
con.Count__c=contact_newCount_Map.get(con.id);
counts_toUpdate.add(con);
}

update counts_toUpdate;
}
  • September 01, 2013
  • Like
  • 0

I am new to salesforce. There is a custom object Lenst which has Master-Details relationship with Standard object Contact I want to write a trigger which updates count field on Contact after there is new record inserted or deleted to Lents object. Here is my code snippet 

 

trigger UpdateCount on Lent__c (after insert) {
    List<Contact> counts_toUpdate = new List<Contact>();
 
    
     if(Trigger.isInsert){  
    List<Lent__c> counts = [select Contact__r.Count__c
    from Lent__c where id IN :Trigger.new FOR UPDATE]; 
    for(Lent__c lent:lentsForContact){
           lent.Contact__r.Count__c = lent.Contact__r.Count__c + 1;  // Line where I get exception
            counts_toUpdate.add(lent.Contact__r);
        }
        update counts_toUpdate;
}
}

 

At line 11 I get the following exception.

 

Error: Invalid data.
Review all error messages below to correct your data.
The trigger Apex UpdateCount caused an unexpected exception. Contact the administrator: UpdateCount: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateCount: line 11, column 1

 

Please help me its very urgent for me as I am stuck here from last one day.

 

  • August 31, 2013
  • Like
  • 0
Can someone help me in writing a single query to retrieve old data and new data for the oparticular condition in if satatement?

List Account accs = Trigger.newMap.keySet() ;

 for (Account a : accs)
            if (a.RecordTypeID == '012D00000002qdE' && a.R_seau_int_gr__c == true && a.Etat_relation_GEO__c == 'Déploiement' && (oldmap == null || oldMap.get(a.Id).Etat_relation_GEO__c != 'Déploiement'))
            {
                hasHierarchy = true;
                accIds.add(a.id);
                while (hasHierarchy)
                {
                    List<Account> res = [SELECT id, Etat_relation_GEO__c FROM Account WHERE Etat_relation_GEO__c != 'Terminé' AND parentId IN :accIds];
                    accIds.clear();
                    if (res == null || res.size() == 0)
                        hasHierarchy = false;
                    for (Account aa : res)
                    {
                        accIds.add(aa.id);
                        toUpdate.add(aa);
                    }
                }
            }
 
  • August 16, 2017
  • Like
  • 0
This is called from a trigger which passes the list of new map and old map.

 public static void hierarchyAccountDeploiment(List<Account> accs, Map<Id, Account> oldMap)
    {
        List<Id> accIds = new List<Id>();
        Boolean hasHierarchy;
        List<Account> toUpdate = new List<Account>();

        for (Account a : accs)
            if (a.RecordTypeID == '012D00000002qdE' && a.R_seau_int_gr__c == true && a.Etat_relation_GEO__c == 'Déploiement' && (oldmap == null || oldMap.get(a.Id).Etat_relation_GEO__c != 'Déploiement'))
            {
                hasHierarchy = true;
                accIds.add(a.id);
                while (hasHierarchy)
                {
                    List<Account> res = [SELECT id, Etat_relation_GEO__c FROM Account WHERE Etat_relation_GEO__c != 'Terminé' AND parentId IN :accIds];
                    accIds.clear();
                    if (res == null || res.size() == 0)
                        hasHierarchy = false;
                    for (Account aa : res)
                    {
                        accIds.add(aa.id);
                        toUpdate.add(aa);
                    }
                }
            }
        for (Account a : toUpdate)
            a.Etat_relation_GEO__c = 'Déploiement';
        if (toUpdate != null && toUpdate.size() > 0)
            update toUpdate;
    }

Any help will be really helpful.
  • August 11, 2017
  • Like
  • 0
Hello,
I am completely new to salesforce and sort of stuck on just trying to update the API versions from sandox to salesforce.
I selected the triggers and tried to deploy to production. the validation fails with the following error:
*** Deployment Log ***
Result: FAILED
Date: August 10, 2017 10:45:07 AM CDT

# Deployed From:
   Project name: sandbox


# Deploy Results:
   File Name:    package.xml
   Full Name:  package.xml
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

   File Name:    triggers/ContractTrigger.trigger
   Full Name:  ContractTrigger
   Action:  UPDATED
   Result:  SUCCESS
   Problem: n/a

# Test Results:

Run Failures:
  ActionPlanDetailController.checkGetRelatedObjectName System.AssertException: Assertion Failed: Pre deploy test failed, This may be because of custom validation rules in your Org. You can check ignore apex errors or temporarily deactivate your validation rules for Contracts and try again.
  ActionPlanObjectTriggerTest.testContractTrigger System.AssertException: Assertion Failed: Pre deploy test failed, This may be because of custom validation rules in your Org. You can check ignore apex errors or temporarily deactivate your validation rules for Contracts and try again.
  ActionPlansUtilitiesTest.APUtestGenerateObjectFeed System.Exception: Assertion Failed: Pre deploy test failed, This may be because of custom validation rules in your Org. You can check ignore apex errors or temporarily deactivate your validation rules for Contracts and try again.
  ActionPlansUtilitiesTest.APUtestGetRecordOwnerId System.Exception: Assertion Failed: Pre deploy test failed, This may be because of custom validation rules in your Org. You can check ignore apex errors or temporarily deactivate your validation rules for Contracts and try again.
  ActionPlansUtilitiesTest.APUtestSaveMasiveMethodPart2 System.Exception: Assertion Failed: Pre deploy test failed, This may be because of custom validation rules in your Org. You can check ignore apex errors or temporarily deactivate your validation rules for Contracts and try again.
  ContractTrigger Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
________________________________________________________________________________________________________

I appreciate any help or pointers in this direction. I am just trying to update the existing API versions and have not modifying any code.
Thanks in advance.
 
Hello,

How can I show header on visual force page with google map in the page. Now if I try to set shoheader to true in <apex:page> tag it stops displaiyng the header.. Please if anyone can give any idea it will be great..
  • January 09, 2014
  • Like
  • 0

I have master detail relationship between Book and Lents object. I want a control in order to avoida  book to be issued second time. I have added following code on Lent object creation before inserting I am checking if Book is already in OldMap it should give an error mesage else it should insert the record. But the code is not working:

 

trigger UpdateCount on Lent__c (before insert,after insert,after delete) {
List<Contact> counts_toUpdate = new List<Contact>();
Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

if(trigger.isinsert){
List<Lent__c> counts =[select Book__c,Contact__c, Contact__r.Count__c,Book__r.Name
from Lent__c where id IN :Trigger.new FOR UPDATE];

for(Lent__c lent:counts){
if((lent.Book__c!= null) && (lent.Book__c != Trigger.oldMap.get(lent.id).Book__c))
{
lent.Book__c.addError('Another new lead has the same email address.');
}else{
contact_newCount_Map.put(lent.Contact__c, Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);
}}
}
else if(trigger.isdelete){
Set<Id> contactIds = new Set<Id>();
for (Lent__c l : Trigger.old)
contactIds.add(l.Contact__c);
//List<Lent__c> counts = [select Contact__c, Contact__r.Count__c
//from Lent__c where id IN :contactIds];
Map<Id,Contact> oldContacts = new Map<Id,Contact>([SELECT Count__c From Contact where Id IN :contactIds]);
for(Lent__c lent : Trigger.old)
contact_newCount_map.put(lent.Contact__c, Integer.valueOf(oldContacts.get(lent.Contact__c).Count__c == null ? 0 : oldContacts.get(lent.Contact__c).Count__c ) -1);
}

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){
con.Count__c=contact_newCount_Map.get(con.id);
counts_toUpdate.add(con);
}

update counts_toUpdate;
}

 

Someone please help.

  • September 02, 2013
  • Like
  • 0

I want to update a count on Contact object after a new record is inserted or deleted on Lents object. My code is working fine to update the count by 1 but is not decreasing its value by 1 please help me:

 

trigger UpdateCount on Lent__c (after insert,after delete) {
List<Contact> counts_toUpdate = new List<Contact>();
Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

if(trigger.isinsert){
List<Lent__c> counts =[select Contact__c, Contact__r.Count__c
from Lent__c where id IN :Trigger.new FOR UPDATE];
for(Lent__c lent:counts){
contact_newCount_Map.put(lent.Contact__c, Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);
}
}
else{
Set<Id> contactIds = new Set<Id>();
for (Lent__c l : Trigger.old)
contactIds.add(l.Contact__c);
List<Lent__c> counts = [select Contact__c, Contact__r.Count__c
from Lent__c where id IN :contactIds];
Map<Id,Contact> oldContacts = new Map<Id,Contact>([SELECT Count__c From Contact where Id IN :contactIds]);
for(Lent__c lent : counts)
contact_newCount_map.put(lent.Contact__c, Integer.valueOf(oldContacts.get(lent.Contact__c).Count__c == null ? 0 : oldContacts.get(lent.Contact__c).Count__c ) -1);
}

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){
con.Count__c=contact_newCount_Map.get(con.id);
counts_toUpdate.add(con);
}

update counts_toUpdate;
}

  • September 01, 2013
  • Like
  • 0

I am trying to update  a count field on standard object Contact after insert or delete of Lents object. The code is as following but it does not work for deletion:

 

trigger UpdateCount on Lent__c (after insert,after delete) {

List<Contact> counts_toUpdate = new List<Contact>();

Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

 

if(trigger.isinsert){

List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c

from Lent__c where id IN :Trigger.new FOR UPDATE];

for(Lent__c lent:counts){

contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);

}

}

else{

List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c

from Lent__c where id IN :Trigger.old FOR UPDATE];

for(Lent__c lent:counts){

contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) - 1);

}

}

 

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){

con.Count__c=contact_newCount_Map.get(con.id);

counts_toUpdate.add(con);

}

 

update counts_toUpdate;

}

 

Please help in finding the problem.

trigger UpdateCount on Lent__c (after insert,after delete) {
List<Contact> counts_toUpdate = new List<Contact>();
Map<String, Integer> contact_newCount_Map=new Map<String, Integer>(); //for each contact the CountNumber

if(trigger.isinsert){
List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c
from Lent__c where id IN :Trigger.new FOR UPDATE];
for(Lent__c lent:counts){
contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) + 1);
}
}
else{
List<Lent__c> counts = [select  Contact__c, Contact__r.Count__c
from Lent__c where id IN :Trigger.old FOR UPDATE];
for(Lent__c lent:counts){
contact_newCount_Map.put(lent.Contact__c,  Integer.valueOf(lent.Contact__r.Count__c==null ? 0 : lent.Contact__r.Count__c) - 1);
}
}

for(Contact con : [select id, Count__c from Contact WHERE ID IN : contact_newCount_Map.KeySet()]){
con.Count__c=contact_newCount_Map.get(con.id);
counts_toUpdate.add(con);
}

update counts_toUpdate;
}
  • September 01, 2013
  • Like
  • 0

I am new to salesforce. There is a custom object Lenst which has Master-Details relationship with Standard object Contact I want to write a trigger which updates count field on Contact after there is new record inserted or deleted to Lents object. Here is my code snippet 

 

trigger UpdateCount on Lent__c (after insert) {
    List<Contact> counts_toUpdate = new List<Contact>();
 
    
     if(Trigger.isInsert){  
    List<Lent__c> counts = [select Contact__r.Count__c
    from Lent__c where id IN :Trigger.new FOR UPDATE]; 
    for(Lent__c lent:lentsForContact){
           lent.Contact__r.Count__c = lent.Contact__r.Count__c + 1;  // Line where I get exception
            counts_toUpdate.add(lent.Contact__r);
        }
        update counts_toUpdate;
}
}

 

At line 11 I get the following exception.

 

Error: Invalid data.
Review all error messages below to correct your data.
The trigger Apex UpdateCount caused an unexpected exception. Contact the administrator: UpdateCount: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateCount: line 11, column 1

 

Please help me its very urgent for me as I am stuck here from last one day.

 

  • August 31, 2013
  • Like
  • 0

I just wanted to check my understanding of the System.isBatch() method. Essentially if your implementing batchable would you expect System.isBatch() to be true?

 

global class myClass implements Database.Batchable<sObject>{

	global final String query;
	
	/* Constructor */
	global myClass(String q){
		query = q;
	}

	global Database.QueryLocator start(Database.BatchableContext bc){
  		System.debug('*** Batch start  ***');
		return Database.getQueryLocator(query); 
	}
	
	global void execute(Database.BatchableContext BC, List<sObject> myList) {
		
		// Run Stuff.
		System.debug(System.isBatch());
		
	}
	
	global void finish(Database.BatchableContext BC){
		System.debug('*** Batch finish ***');
	}
 
}