• AlSawtooth
  • NEWBIE
  • 50 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 22
    Replies
If the close date on my Opp is > than the date of a specific activity on the contact record (where subject = 'Report'), I want to check a custom box on the opportunity. I'm getting a compile error at the second map: Invalid foreign key relationship: Account.ActivityHistory__r at line 17 column 26
 
List<Account> activityaccount = [Select Name, (Select Subject, Id, WhoId, WhatId, ActivityDate from ActivityHistories where Subject = 'Research Report') from Account];
List<Contact> cons = [select Name, Id, AccountId from Contact where AccountId in :activityaccount];
List<Opportunity> opps = [select Amount, CloseDate, cv__Contact__c from Opportunity where cv__Contact__c in :cons];

Map<Id, Date> oppdatemap = new Map<Id, Date>();
for(Opportunity o: [select Id, CloseDate from Opportunity where Id in :opps]){
   oppdatemap.put(o.Id, o.CloseDate);
   }
   
Map<Id, Date> actdatemap = new Map<Id, Date>();
for(Account a: [select (select Id, ActivityDate from ActivityHistories where Id in :activityaccount) from Account]){
    actdatemap.put(a.Id, a.ActivityDate);
    }
    
Map<Date, Date> oppactdatemap = new Map<Date, Date>();
    oppactdatemap.put(oppdatemap.keyset(), actdatemap.keyset());
    
for(Opportunity o :trigger.newmap.keyset()){
    if(datemap.get(o.CloseDate) <= o.CloseDate){
            o.After_RR_Field__c = true;
        }
    }
What am I missing? (Is there a better way to do this?) Thank you!
 
I'm trying to count the total number of distinct years for which a given account has associated opportunities. This code works fine in individual cases, but breaks during bulk updates. Any ideas?
trigger UpdateOppYears on Opportunity (after update, after insert, after delete) {
if(Trigger.IsUpdate || Trigger.IsInsert){

    List<Account> accs = 
        [SELECT Id, Years_of_Opps__c FROM Account WHERE Id IN
             (SELECT AccountId FROM Opportunity WHERE Id in:Trigger.newMap.keySet() 
              AND AccountId != null
              AND StageName = 'Received')];
    
     for(Account a: accs) {
        AggregateResult[] groupedResult = 
            [SELECT AccountId, COUNT_DISTINCT(CloseYear__c) NumberOfDistinctYears FROM Opportunity o
                WHERE AccountId = :a.Id
                AND o.StageName = 'Received'
                GROUP BY AccountId];
         Decimal aggregateCount = (Decimal)groupedResult[0].get('NumberOfDistinctYears');
         a.Years_of_Opps__c = aggregateCount;
    }
    
    update accs;

 
I want to populate a field that tells me how many years (consecutive or otherwise) an opportunity has been closed for a specific account. Why can't I do CloseDate.year() inside the aggregate function? (If I try to run count_distinct on a variable, I also get an error message).

Thank you!!
 
trigger YearsOfOpps on Opportunity (after update, after insert) {
List<Account> accs = 
        [SELECT Id, Years_of_Opps__c FROM Account WHERE Id IN
             (SELECT AccountId FROM Opportunity WHERE Id in:Trigger.newMap.keySet())];
    
     for(Account a: accs) {
        AggregateResult[] groupedResult = 
            [SELECT AccountId, COUNT_DISTINCT(CloseDate.year()) Yearr FROM Opportunity 
//the line above is throwing the compile error
                WHERE AccountId = :a.Id
                GROUP BY Account];
         Decimal aggregateYears = (Decimal)groupedResult[0].get('Yearr');
         a.Years_of_Opps__c = aggregateYears;
    }
    
    update accs;
}
}

 
I've looked through a lot of questions on this error and none of the solutions I've seen (-e v -g, move config to another folder, etc) seem to be working for me. Any suggestions are greatly appreciated!

Here is my process-conf.xml file:
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="accountInsert"
class="com.salesforce.dataloader.process.ProcessRunner"
singleton="false">
<description>accountInsert job gets the account record from the CSV file
and inserts it into Salesforce.</description>
<property name="name" value="accountInsert"/>
<property name="configOverrideMap">
<map>
<entry key="sfdc.debugMessages" value="true"/>
<entry key="sfdc.debugMessagesFile"
value="C:\Program Files (x86)\salesforce.com\Data Loader\samples\data\debugMessagesFile"/>
<entry key="sfdc.endpoint" value="https://www.salesforce.com"/>
<entry key="sfdc.username" value="masked@masked.com"/>
<!--Password below has been encrypted using key file,
therefore, it will not work without the key setting:
process.encryptionKeyFile.
The password is not a valid encrypted value,
please generate the real value using the encrypt.bat utility -->
<entry key="sfdc.password" value="a288a76104221ee474bd48aa44aa49da1a11645e2ca9c62bd8eeda86c143e5f2d3f9389b890741a3"/>
<!--the password above was created through encrypt.bat -e PasswordSecurityToken plus a path the the Key file-->
<entry key="process.encryptionKeyFile"
value="C:\Program Files (x86)\salesforce.com\Data Loader\key.txt"/>
<entry key="sfdc.timeoutSecs" value="600"/>
<entry key="sfdc.loadBatchSize" value="200"/>
<entry key="sfdc.entity" value="Account"/>
<entry key="process.operation" value="insert"/>
<entry key="process.mappingFile" value="c:\Program Files (x86)\salesforce.com\Data Loader\samples\testaccountmatch.sdl"/>
<entry key="dataAccess.name"
value="C:\Program Files (x86)\salesforce.com\Data Loader\samples\data\Test Account Insert.csv"/>
<entry key="process.outputSuccess"
value="c:\Program Files (x86)\salesforce.com\Data Loader\samples\data\outputSuccess.csv"/>
<entry key="process.outputError"
value="c:\Program Files (x86)\salesforce.com\Data Loader\samples\data\outputError.csv"/>
<entry key="dataAccess.type" value="csvRead"/>
<entry key="process.initialLastRunDate"
value="2005-12-01T00:00:00.000-0800"/>
</map>
</property>
</bean>
</beans>

Here's my command line error:
c:\Program Files (x86)\salesforce.com\Data Loader\bin>process.bat "c:\Program Files (x86)\salesforce.com\Data Loader\samples" accountInsert
2015-01-06 09:27:28,326 INFO  [main] controller.Controller initLog (Controller.java:389) - Using built-in logging configuration, no log-conf.xml in c:\Program Files (x86)\salesforce.com\Data Loader\bin\log-conf.xml
2015-01-06 09:27:28,326 INFO  [main] controller.Controller initLog (Controller.java:391) - The log has been initialized
2015-01-06 09:27:28,326 INFO  [main] process.ProcessConfig getBeanFactory (ProcessConfig.java:103) - Loading process configuration from config file: c:\Program Files (x86)\salesforce.com\Data Loader\samples\process-conf.xml
2015-01-06 09:27:28,419 INFO  [main] xml.XmlBeanDefinitionReader loadBeanDefinitions (XmlBeanDefinitionReader.java:315) - Loading XML bean definitions from file [c:\Program Files (x86)\salesforce.com\Data Loader\samples\process-conf.xml]
2015-01-06 09:27:28,466 INFO  [accountInsert] controller.Controller initConfig (Controller.java:327) - config dir created at c:\Program Files (x86)\salesforce.com\Data Loader\samples
2015-01-06 09:27:28,466 INFO  [accountInsert] controller.Controller initConfig (Controller.java:338) - config file created at c:\Program Files (x86)\salesforce.com\Data Loader\samples\config.properties
2015-01-06 09:27:28,482 INFO  [accountInsert] controller.Controller initConfig (Controller.java:355) - The controller config has been initialized
2015-01-06 09:27:28,482 INFO  [accountInsert] process.ProcessRunner run (ProcessRunner.java:116) - Initializing process engine
2015-01-06 09:27:28,482 INFO  [accountInsert] process.ProcessRunner run (ProcessRunner.java:119) - Loading parameters
2015-01-06 09:27:28,934 ERROR [accountInsert] config.Config decryptProperty (Config.java:692) - Error loading parameter: sfdc.password of type: java.lang.String

javax.crypto.BadPaddingException: Given final block not properly padded
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at com.salesforce.dataloader.security.EncryptionUtil.decryptString(EncryptionUtil.java:210)
        at com.salesforce.dataloader.config.Config.decryptProperty(Config.java:686)
        at com.salesforce.dataloader.config.Config.postLoad(Config.java:638)
        at com.salesforce.dataloader.config.Config.loadParameterOverrides(Config.java:664)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:120)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:100)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:253)
2015-01-06 09:27:28,934 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:238) - Unable to run process accountInsert
java.lang.RuntimeException: com.salesforce.dataloader.exception.ParameterLoadException: Error loading parameter: sfdc.password of type: java.lang.String
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:162)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:100)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:253)
Caused by: com.salesforce.dataloader.exception.ParameterLoadException: Error loading parameter: sfdc.password of type: java.lang.String
        at com.salesforce.dataloader.config.Config.decryptProperty(Config.java:693)
        at com.salesforce.dataloader.config.Config.postLoad(Config.java:638)
        at com.salesforce.dataloader.config.Config.loadParameterOverrides(Config.java:664)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:120)
        ... 2 more
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at com.salesforce.dataloader.security.EncryptionUtil.decryptString(EncryptionUtil.java:210)
        at com.salesforce.dataloader.config.Config.decryptProperty(Config.java:686)

javax.crypto.BadPaddingException: Given final block not properly padded
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at com.salesforce.dataloader.security.EncryptionUtil.decryptString(EncryptionUtil.java:210)
        at com.salesforce.dataloader.config.Config.decryptProperty(Config.java:686)
        at com.salesforce.dataloader.config.Config.postLoad(Config.java:638)
        at com.salesforce.dataloader.config.Config.loadParameterOverrides(Config.java:664)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:120)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:100)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:253)
2015-01-06 09:27:28,934 FATAL [main] process.ProcessRunner topLevelError (ProcessRunner.java:238) - Unable to run process accountInsert
java.lang.RuntimeException: com.salesforce.dataloader.exception.ParameterLoadException: Error loading parameter: sfdc.password of type: java.lang.String
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:162)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:100)
        at com.salesforce.dataloader.process.ProcessRunner.main(ProcessRunner.java:253)
Caused by: com.salesforce.dataloader.exception.ParameterLoadException: Error loading parameter: sfdc.password of type: java.lang.String
        at com.salesforce.dataloader.config.Config.decryptProperty(Config.java:693)
        at com.salesforce.dataloader.config.Config.postLoad(Config.java:638)
        at com.salesforce.dataloader.config.Config.loadParameterOverrides(Config.java:664)
        at com.salesforce.dataloader.process.ProcessRunner.run(ProcessRunner.java:120)
        ... 2 more
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
        at com.salesforce.dataloader.security.EncryptionUtil.decryptString(EncryptionUtil.java:210)
        at com.salesforce.dataloader.config.Config.decryptProperty(Config.java:686)
        ... 5 more
My trigger seems to work in the debug log but doesn't update the value in the UI - I have no idea why! There is a lookup on the Opp to a custom Segment object; I'm trying to update the Source Code from the Segment onto a Source Code field on the Opp.
 
trigger UpdateSourceCode on Opportunity (before insert, before update) {

List<Opportunity> opp = [select Id, Segment__c 
                                            from Opportunity 
                                            where Id in :trigger.new and Source__c = null and Segment__c != null];
                                            
List<Segment__c> segments = [select Id, Source_Code__c 
                                            from Segment__c 
                                            where Source_Code__c != null];

Map<Id, Segment__c> segmap = new Map<Id, Segment__c>(segments);

for(Opportunity o : opp){
    if(segmap.containskey(o.Segment__c)){
    System.debug('Does segmap contain key: ' + segmap.containskey(o.Segment__c));
        List<Segment__c> OneSeg = [select Source_Code__c from Segment__c];
        System.debug('oneseg size: ' + OneSeg.size());
        if(OneSeg.size()>0){
            o.Source__c = OneSeg[0].Source_Code__c;
            System.debug('opp source code: ' + o.Source__c);
            System.debug('effort segment source code: ' + OneSeg[0].Source_Code__c);
            //these two debugs are the same (correct) value - so why isn't it updating?
              }
        }    
    }

}

 
I have the following debugs in my code:
System.debug(parser.nextToken());
System.debug(parser.getCurrentToken());
System.debug(parser.getCurrentName());
System.debug(parser.getText());

I get (in order):
DEBUG| FIELD_NAME
DEBUG| FIELD_NAME
DEBUG| originalId 
DEBUG| null
Why is getText() null? My code uses a while looop to go through a ton of these, and they all have the same pattern - and getText() is null for all of them.

Thank you!
 
I'm writing a trigger to sidestep an error from a packaged class. The package class includes the variable
public static boolean RIP = false;

then, the packaged code does some stuff and eventually throws an error if RIP = false. I'm writing some code to basically mimic (and improve!) the packaged code, but I don't know how to include the RIP variable in my code so that I don't get the error message (since it defaults to false). Does that make sense?

If I try to call the class.variable, I get a compile error saying the variable doesn't exist (I assume because it's packaged code?).

Thank you!
Hello,

I'm getting a NullPointerException that directs me to JSON Parser code. I have a VF button that's controlled by a Controller, which calls out to a class that makes API calls. Here is the controller:
 
public class TestAPIVFController {

    private final TObject__c t;
    public TestAPIVFController(ApexPages.StandardController stdController) {
        this.t = (TObject__c)stdController.getRecord();
    }
     
    public PageReference autoRun() {
 
        String theId = ApexPages.currentPage().getParameters().get('id');
 
        if (theId == null) {
            return null;
        }
 
        testapi ta = new testapi();
        ta.loginmeth();
        ta.teammeth();
        
        
        PageReference pageRef = new PageReference('/' + theId);
        pageRef.setRedirect(true);
        return pageRef;
        }
    }
Here is the method that's giving me trouble (from the debug log, it's appearing on line 26, which is "JSONParser parser = JSON.createParser(res.getbody());"
public void loginmeth(){
    Http http = new Http();
    HttpRequest req = new HttpRequest();
        req.setHeader('Connection', 'Close');
        String url = '[my string - this works fine]';
        req.setEndpoint(url);
        req.setMethod('POST');

    System.debug('request:'+req.toString());

    HttpResponse res;

    System.debug('response:'+ http.send(req));

    JSONParser parser = JSON.createParser(res.getbody());
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){
                String fieldName = parser.getText();
                parser.nextToken();
                if(fieldName == 'token') {
                    sig = parser.getText();
                    }
                } 
            }
}

The API call itself is fine, based on testing in the browser - it's just when I try to run this through the VF button that I get errors.
I'm trying to deactivate a trigger from prod using the IDE.

My code coverage in prod is 85% overall, and in sandbox 75% overall. When I validate in IDE, I get an error message saying that I have a code coverage error (74%).

Why am I getting that, if my prod coverage is 85%?
Hello,

I'm getting an error that I think is recursion-based and I'm not sure how to fix it. Basically, I'm trying to update the DD field on my DDCustom__c object with a value from my Opportunity field UpdateDD__c (which is a lookup).
 
trigger UpdateDD2 on DDCustom__c (after update, after insert) {

  List<DDCustom__c> des = [select Id, DD__r.Id, Opportunity__r.Id from DDCustom__c where Id in :Trigger.newMap.keySet()];
  List<Opportunity> opp = [select Id, UpdateDD__c, UpdateDD__r.Id from Opportunity where Id = : des[0].cv__Opportunity__r.Id and UpdateDD__c != null];
  List<DDCustom__c> des2 = new List<DDCustom__c>();
  
  Set<DDCustom__c> desSet = new Set<DDCustom__c>();
  
  for(DDCustom__c d : des){
  
      if(des2.size()>0){
          desSet.addAll(des2);
          }
  
      if((! desSet.contains(d)) && (opp[0].UpdateDD__c != null) && (d.DD__r.Id != opp[0].UpdateDD__r.Id)){
           d.DD__r.Id = opp[0].UpdateDD__r.Id;
              des2.add(d);
              }
      }
 
   update des2;
   }

 
Here is my trigger (thanks to help from Ashlekh (https://developer.salesforce.com/forums/ForumsProfile?communityId=09aF00000004HMG&userId=005F0000003FjAE&showHeader=false)!):

trigger UpdateEmployerAddress on Contact (before insert, before update)
{
    Set<String> setoforgs = new Set<String>();
    for (Contact inloop : Trigger.new){
        if(inloop.Employer_Lookup__c !=null){
            setoforgs.add(inloop.Employer_Lookup__c);}
    }
    Map<id,Organization__c> orgs = new Map<id,Organization__c>( [SELECT Id, Mailing_Street__c, Mailing_City__c, Mailing_State__c, Mailing_Zip_Code__c, Mailing_Country__c
                                            FROM Organization__c  WHERE Id in :setoforgs]);
 
    for (Contact inloop : Trigger.new){
        if(inloop.Employer_Lookup__c !=null){
              
          if(orgs.size()>0 &&  orgs.containsKey(inloop.Employer_Lookup__c)){
              Organization__c o = orgs.get(inloop.Employer_Lookup__c);
              inloop.cv__Employer_Street__c = o.Mailing_Street__c;
              inloop.cv__Employer_City__c = o.Mailing_City__c;
              inloop.cv__Employer_State__c = o.Mailing_State__c;
              inloop.cv__Employer_Postal_Code__c = o.Mailing_Zip_Code__c;
              inloop.cv__Employer_Country__c = o.Mailing_Country__c;
          }
        }
    }
}

Here is my test class, but I'm only getting 43% coverage. What else can I add to the test class to cover the rest of the trigger?
@isTest
private class UpdateEmployerAddressTest {

    static testMethod void EmpTestMethod() {
       Organization__c o1 = new Organization__c();
       o1.Name ='Test Org';
       o1.Mailing_Street__c = '123 Main Street';
       o1.Mailing_City__c = 'Brooklyn';
       insert (o1);

       Contact cons = new Contact();
       cons.LastName = 'Tester';
       cons.cv__Employer__c='Test Org';    
       insert(cons);
       
       Contact cons2 = new Contact();
       cons2.LastName = 'Tester2';
       cons2.cv__Employer__c = 'Nope';
       insert(cons2);
       
       System.assertNotEquals(o1.Id, cons2.Employer_Lookup__c);
       System.assertNotEquals(o1.Mailing_City__c, cons2.cv__Employer_City__c);
      }
    }

Thanks!!
I have a trigger that's calling from a class, and I'm getting a NullPointerException on the first line of the 3rd method (List<Contact> constoupdate = [select Id, FACheckbox__c from Contact where Id in :Trigger.newMap.keySet()];). Anyone know why this is happening?

(Also, I know I probably have a recursion problem here, which I'm hoping to solve with a static variable - but one issue at a time!)

Trigger:
trigger TestTrigger on Contact (before insert, before update, after insert, after update) {
	if(Trigger.isBefore) {
    TriggerClass.MethodBeforeT();	
    }
    else if(Trigger.isAfter) {
    TriggerClass.MethodAfterT();
    }

TriggerClass.MethodLast();
    
}

Class:
public with sharing class TriggerClass {

public static void MethodBeforeT (){
	List<RecordType> type1 = [select Id from RecordType where Name = 'Type 1' and SobjectType = 'Contact' limit 1];
	List <RecordType> type2 = [select Id from RecordType where Name = 'Type 2' and SobjectType = 'Contact' limit 1];
	
	for (Contact cons :(List <Contact>) Trigger.new){
	if(cons.Checkbox__c = true && cons.RecordTypeId == type1[0].Id){
			cons.RecordTypeId = type2[0].Id;}
	}
	}
	
public static void MethodAfterT (){
	List<CustomE__c> customes = new List <CustomE__c>();
	List<Contact> constoupdate = [select Id, FirstName, LastName, Email, Checkbox__c from Contact where Id in :Trigger.newMap.keySet()];
	List<Contact> constoupdate2 = new List <Contact>();

	for (Contact c :constoupdate){
	if(c.Checkbox__c = true){
	CustomE__c e = new CustomE__c();
		e.Contact__c = c.Id;
		e.First_Name__c = c.FirstName;
		e.Last_Name__c = c.LastName;
		e.Email__c = c.Email;
	customes.add(e);
	constoupdate2.add(c);
	}}
	insert customes;
}

public static void MethodLast (){
	List<Contact> constoupdate = [select Id, Checkbox__c from Contact where Id in :Trigger.newMap.keySet()];
	List<Contact> constoupdate2 = new List <Contact>();
	
	for(Contact c :constoupdate){
		c.Checkbox__c = false;
		constoupdate2.add(c);}
		update constoupdate2;
}
}


trigger UpdateEmployerAddress on Contact (before insert, before update) {
    Set<String> setoforgs = new Set<String>();
    for (Contact inloop : Trigger.new) {
    
    if(inloop.Employer_Lookup__c !=null) {
    
     List<Organization__c> orgs = 
         [SELECT Id, Mailing_Street__c, Mailing_City__c, Mailing_State__c, Mailing_Zip_Code__c, Mailing_Country__c 
          FROM Organization__c 
          WHERE Id = :inloop.Employer_Lookup__c];
             
          if(orgs.size()>0){
          
          for (Organization__c o :orgs){
          
          inloop.cv__Employer_Street__c = o.Mailing_Street__c;
          inloop.cv__Employer_City__c = o.Mailing_City__c;
          inloop.cv__Employer_State__c = o.Mailing_State__c;
          inloop.cv__Employer_Postal_Code__c = o.Mailing_Zip_Code__c;
          inloop.cv__Employer_Country__c = o.Mailing_Country__c;}
                
                
}}}}

I'm trying to count the total number of distinct years for which a given account has associated opportunities. This code works fine in individual cases, but breaks during bulk updates. Any ideas?
trigger UpdateOppYears on Opportunity (after update, after insert, after delete) {
if(Trigger.IsUpdate || Trigger.IsInsert){

    List<Account> accs = 
        [SELECT Id, Years_of_Opps__c FROM Account WHERE Id IN
             (SELECT AccountId FROM Opportunity WHERE Id in:Trigger.newMap.keySet() 
              AND AccountId != null
              AND StageName = 'Received')];
    
     for(Account a: accs) {
        AggregateResult[] groupedResult = 
            [SELECT AccountId, COUNT_DISTINCT(CloseYear__c) NumberOfDistinctYears FROM Opportunity o
                WHERE AccountId = :a.Id
                AND o.StageName = 'Received'
                GROUP BY AccountId];
         Decimal aggregateCount = (Decimal)groupedResult[0].get('NumberOfDistinctYears');
         a.Years_of_Opps__c = aggregateCount;
    }
    
    update accs;

 
My trigger seems to work in the debug log but doesn't update the value in the UI - I have no idea why! There is a lookup on the Opp to a custom Segment object; I'm trying to update the Source Code from the Segment onto a Source Code field on the Opp.
 
trigger UpdateSourceCode on Opportunity (before insert, before update) {

List<Opportunity> opp = [select Id, Segment__c 
                                            from Opportunity 
                                            where Id in :trigger.new and Source__c = null and Segment__c != null];
                                            
List<Segment__c> segments = [select Id, Source_Code__c 
                                            from Segment__c 
                                            where Source_Code__c != null];

Map<Id, Segment__c> segmap = new Map<Id, Segment__c>(segments);

for(Opportunity o : opp){
    if(segmap.containskey(o.Segment__c)){
    System.debug('Does segmap contain key: ' + segmap.containskey(o.Segment__c));
        List<Segment__c> OneSeg = [select Source_Code__c from Segment__c];
        System.debug('oneseg size: ' + OneSeg.size());
        if(OneSeg.size()>0){
            o.Source__c = OneSeg[0].Source_Code__c;
            System.debug('opp source code: ' + o.Source__c);
            System.debug('effort segment source code: ' + OneSeg[0].Source_Code__c);
            //these two debugs are the same (correct) value - so why isn't it updating?
              }
        }    
    }

}

 
I have the following debugs in my code:
System.debug(parser.nextToken());
System.debug(parser.getCurrentToken());
System.debug(parser.getCurrentName());
System.debug(parser.getText());

I get (in order):
DEBUG| FIELD_NAME
DEBUG| FIELD_NAME
DEBUG| originalId 
DEBUG| null
Why is getText() null? My code uses a while looop to go through a ton of these, and they all have the same pattern - and getText() is null for all of them.

Thank you!
 
I'm writing a trigger to sidestep an error from a packaged class. The package class includes the variable
public static boolean RIP = false;

then, the packaged code does some stuff and eventually throws an error if RIP = false. I'm writing some code to basically mimic (and improve!) the packaged code, but I don't know how to include the RIP variable in my code so that I don't get the error message (since it defaults to false). Does that make sense?

If I try to call the class.variable, I get a compile error saying the variable doesn't exist (I assume because it's packaged code?).

Thank you!
Hello,

I'm getting a NullPointerException that directs me to JSON Parser code. I have a VF button that's controlled by a Controller, which calls out to a class that makes API calls. Here is the controller:
 
public class TestAPIVFController {

    private final TObject__c t;
    public TestAPIVFController(ApexPages.StandardController stdController) {
        this.t = (TObject__c)stdController.getRecord();
    }
     
    public PageReference autoRun() {
 
        String theId = ApexPages.currentPage().getParameters().get('id');
 
        if (theId == null) {
            return null;
        }
 
        testapi ta = new testapi();
        ta.loginmeth();
        ta.teammeth();
        
        
        PageReference pageRef = new PageReference('/' + theId);
        pageRef.setRedirect(true);
        return pageRef;
        }
    }
Here is the method that's giving me trouble (from the debug log, it's appearing on line 26, which is "JSONParser parser = JSON.createParser(res.getbody());"
public void loginmeth(){
    Http http = new Http();
    HttpRequest req = new HttpRequest();
        req.setHeader('Connection', 'Close');
        String url = '[my string - this works fine]';
        req.setEndpoint(url);
        req.setMethod('POST');

    System.debug('request:'+req.toString());

    HttpResponse res;

    System.debug('response:'+ http.send(req));

    JSONParser parser = JSON.createParser(res.getbody());
        while (parser.nextToken() != null) {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){
                String fieldName = parser.getText();
                parser.nextToken();
                if(fieldName == 'token') {
                    sig = parser.getText();
                    }
                } 
            }
}

The API call itself is fine, based on testing in the browser - it's just when I try to run this through the VF button that I get errors.
I'm trying to deactivate a trigger from prod using the IDE.

My code coverage in prod is 85% overall, and in sandbox 75% overall. When I validate in IDE, I get an error message saying that I have a code coverage error (74%).

Why am I getting that, if my prod coverage is 85%?
Hello,

I'm getting an error that I think is recursion-based and I'm not sure how to fix it. Basically, I'm trying to update the DD field on my DDCustom__c object with a value from my Opportunity field UpdateDD__c (which is a lookup).
 
trigger UpdateDD2 on DDCustom__c (after update, after insert) {

  List<DDCustom__c> des = [select Id, DD__r.Id, Opportunity__r.Id from DDCustom__c where Id in :Trigger.newMap.keySet()];
  List<Opportunity> opp = [select Id, UpdateDD__c, UpdateDD__r.Id from Opportunity where Id = : des[0].cv__Opportunity__r.Id and UpdateDD__c != null];
  List<DDCustom__c> des2 = new List<DDCustom__c>();
  
  Set<DDCustom__c> desSet = new Set<DDCustom__c>();
  
  for(DDCustom__c d : des){
  
      if(des2.size()>0){
          desSet.addAll(des2);
          }
  
      if((! desSet.contains(d)) && (opp[0].UpdateDD__c != null) && (d.DD__r.Id != opp[0].UpdateDD__r.Id)){
           d.DD__r.Id = opp[0].UpdateDD__r.Id;
              des2.add(d);
              }
      }
 
   update des2;
   }

 
Here is my trigger (thanks to help from Ashlekh (https://developer.salesforce.com/forums/ForumsProfile?communityId=09aF00000004HMG&userId=005F0000003FjAE&showHeader=false)!):

trigger UpdateEmployerAddress on Contact (before insert, before update)
{
    Set<String> setoforgs = new Set<String>();
    for (Contact inloop : Trigger.new){
        if(inloop.Employer_Lookup__c !=null){
            setoforgs.add(inloop.Employer_Lookup__c);}
    }
    Map<id,Organization__c> orgs = new Map<id,Organization__c>( [SELECT Id, Mailing_Street__c, Mailing_City__c, Mailing_State__c, Mailing_Zip_Code__c, Mailing_Country__c
                                            FROM Organization__c  WHERE Id in :setoforgs]);
 
    for (Contact inloop : Trigger.new){
        if(inloop.Employer_Lookup__c !=null){
              
          if(orgs.size()>0 &&  orgs.containsKey(inloop.Employer_Lookup__c)){
              Organization__c o = orgs.get(inloop.Employer_Lookup__c);
              inloop.cv__Employer_Street__c = o.Mailing_Street__c;
              inloop.cv__Employer_City__c = o.Mailing_City__c;
              inloop.cv__Employer_State__c = o.Mailing_State__c;
              inloop.cv__Employer_Postal_Code__c = o.Mailing_Zip_Code__c;
              inloop.cv__Employer_Country__c = o.Mailing_Country__c;
          }
        }
    }
}

Here is my test class, but I'm only getting 43% coverage. What else can I add to the test class to cover the rest of the trigger?
@isTest
private class UpdateEmployerAddressTest {

    static testMethod void EmpTestMethod() {
       Organization__c o1 = new Organization__c();
       o1.Name ='Test Org';
       o1.Mailing_Street__c = '123 Main Street';
       o1.Mailing_City__c = 'Brooklyn';
       insert (o1);

       Contact cons = new Contact();
       cons.LastName = 'Tester';
       cons.cv__Employer__c='Test Org';    
       insert(cons);
       
       Contact cons2 = new Contact();
       cons2.LastName = 'Tester2';
       cons2.cv__Employer__c = 'Nope';
       insert(cons2);
       
       System.assertNotEquals(o1.Id, cons2.Employer_Lookup__c);
       System.assertNotEquals(o1.Mailing_City__c, cons2.cv__Employer_City__c);
      }
    }

Thanks!!
Hi All,

Please correct my trigger. When a case is created it should insert a task.The "Assigned to"(Owner) field should be the lookup to Account that is on the case and from there to another custom object called underwriters inside this field called UW_User__c.

trigger TriggerToInsertTask on Case (after insert) {
List<RecordType> rdType = [Select Id from RecordType where SObjectType = 'Case' and Name = 'Bintech' Limit 1];
List<Case> ca = [Select Id,Type,RecordType.Name,Account.Commercial_Lines_Underwriter__r.UW_User__c,CreatedDate From Case Where RecordType.Name = 'Bintech' and Type = 'Loss Runs' Limit 1];
List<Task> tk = new List<Task>();
for(Case c: Trigger.new){
Task ts = new Task();
if(c.Account!=NULL && c.Policy__c!=NULL &&c.RecordType.Name=='Bintech')
ts.WhatId = ca[0].Id;
//ts.RecordType.Id = '012E000000022ZQ';
ts.Subject = 'Loss Run Case Follow-Up';
ts.Priority = 'Medium';
ts.ActivityDate = Date.valueOf(ca[0].CreatedDate)+7;
ts.OwnerId  =  ca[0].Account.Commercial_Lines_Underwriter__r.UW_User__c;
       }
  insert ca;
}

Thanks!