• Shawn Reichner 29
  • NEWBIE
  • 424 Points
  • Member since 2017

  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 21
    Questions
  • 103
    Replies
What workflow rule do I run to populate a currency field with the value from another currency field on the same object (opp page)? 

Tried using TEXT () and VALUE () but kept getting errors.
Hi I am trying to figure out to how trigger works for updating checkbox on Case object when checkboxfield of other custom object is set to true ,Lets say I have a custom field Required__c on Destination object and I have a Criteria__c  field on Case object, whenever required__c is true I want to update the criteria__c on case object to true , can anyone please guide me on this 

Thanks in advance
  • November 03, 2017
  • Like
  • 0
Is there an easy way to find out how many records in a custom object have Notes and attachments in them?
I schedule a data export report, but that did not work. I'm working with Salesforce support.
Meanwhile, want to find out if there is a way to find out how many records have attachments.
 
Hello gurus,
I'm trying to be a better developer by writing the test code first.  I can't create all the needed test objects.  Account, Contact, Case are created and I can see the IDs in the debug log but get an error when creating the Asset.  What am I overlooking?

There is no other code created yet.
 
@IsTest(SeeAllData=True)

public class AssetUpdateTest {
    
    public static testmethod void testAssetLink()    {
        Account acc = createAccount(); 
        Contact con = createContact(acc); 
        Case cas = createCase(acc,con); 
        Asset ast = createAsset(acc,con,cas); 

        System.debug('**************************   Case ID: ' + cas.id); 
        System.debug('**************************   Case.Asset: ' + cas.AssetId);
        
    }
    
    public static Account createAccount(){
        Account theAccount = new Account(
            recordtypeid='01270000000Q7rQ', 
            name='Test Account', 
            Status__c='Client',
            Line_of_Business__c='CRS',
            phone='8005551212', 
            currencyisocode='USD'); 
        
        insert theAccount;
        return theAccount; 
    }    
    
    public static Contact createContact(Account theAccount){
        Contact theContact = new Contact(
            recordtypeid='01270000000Q7ra',
            email='tim.bouscal@audatex.com', 
            firstname='George', 
            lastname='Washington',
            accountid=theAccount.id);
        insert theContact;        
        return theContact; 
    }
    
    public static Case createCase(Account acc, Contact con){
        Case theCase = new Case(
            recordtypeid='01270000000Dy9u', 
            AccountId = acc.Id, 
            ContactId = con.Id,             
            
            Requestor__c=con.Id, 
            Reason='New Account Setup', 
            Reason_Detail__c='New - ADXE Shop 02',
            Status='New', 
            Origin='Sales Request', 
            Subject='AssetUpdateTest Sample BisOps Case', 
            Description='This is a sample case for testig the AssetUpdate class'
        ); 
        insert theCase; 
        return theCase;
    }    
    
    public static Asset createAsset(Account acc, Contact con, Case cas){
        System.debug('***** ***** ***** Account ID: ' + acc.id + '     Contact Id: ' + con.id + '     Case ID: '+ cas.Id); // all 3 values show in debug log
        Asset theAsset = new Asset(
            Name='Test Asset', 
            Account = acc, 
            Contact = con, 
            Case_Number__c = cas.CaseNumber, 
            Type__c='New', 
            Status='Purchased', 
            Description='This is a test asset for testing the AssetUpdate class'
        );
        insert theAsset; 
        return theAsset; 
    }
}

Error: 
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Every asset needs an account, a contact, or both.: [AccountId, ContactId]

Class.AssetUpdateTest.createAsset: line 69, column 1
Class.AssetUpdateTest.testAssetLink: line 9, column 1

 
Hello all,
I currently have the following logic in a workflow rule to determine when to send out an email alert:

AND ( 
RecordTypeId <> "012C0000000CCTo", 
ISCHANGED ( Requested_Dev_Date__c ), 

OR 
(ISPICKVAL (StageName , "6.5 Process with Signature" ), 
(ISPICKVAL (StageName , "6.3 Process without Signature" )) 
)))

I now have a need to test for more than one record type ID, while the rest of the logic would stay the same. How do I best accomplish this code? Is the right approach a CASE statement, or IF? How would this be structured?
 
Hi,

How do you "read" (in plane English) this piece of code?
List<OpportunityShare> oppShareList = [select Id, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId IN :opportunityIdList and RowCause = 'Team'];
My interpretation is...

Create a variable of the type List<OpportunityShare> which is called oppShareList and assign the following records to such list: all records (display the fields Id, OpportunityAccessLevel, etc...) FROM the table OpportunityShare WHERE ...????

I do not understand the code after the WHERE

Could someone explain?

Thank you very much.


 
Hi All,

I have a request from our business, to create a field on a custom object called Vehicle, A field that show the total values of the opportunities associated with the specific vehicle. Our in-house developer managed to do that, but with a schedule rule that runs only once/day, and the request is to show the total amount every time an amount in a opportunity is updated.

The developer created 2 different classes, one to make a sum of all values from all opportunities:
/* @date 29.09.2017 */
/* @description for update a summary field on vehicle level, which sums up the opportunity amount of the related opportunities*/
global class Opportunity_Amount_Update implements Database.Batchable<sObject>  {

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT ID FROM Vehicle__c ' );
    }
    
    global decimal STTO = 0;

    global void execute(Database.BatchableContext bc, List<Vehicle__c> scope){
        // process each batch of records
        Set<Vehicle__c> Veh = new Set<Vehicle__c>();
        List<Vehicle__c> Veh1 = new List<Vehicle__c>();
        List<Opportunity> OPP = [Select Id, GH_Vehicle__c, Amount from Opportunity WHERE GH_Vehicle__c <>'']; 
          for (Vehicle__c VEx : scope) {    
            for (Opportunity Opps1 : OPP ) {
                 if(Opps1.GH_Vehicle__c == VEx.id) {
                     STTO = STTO + Opps1.Amount;
                 }
            }
            VEx.Opportunity_amount__c = STTO;
            Veh.add(VEx);
            STTO = 0;
         }
        Veh1.addall(Veh);
        update Veh1;
    }    

    global void finish(Database.BatchableContext bc){
    }    
}

And another one as a scheduler:
global class Opportunity_Amount_Update_scheduler implements Schedulable {
    global void execute(SchedulableContext ctx) {
        Opportunity_Amount_Update OA = new Opportunity_Amount_Update();
        DataBase.executeBatch(OA);
    }
}

Ans as I mentionated abowe, we need the first class (Opportunity_Amount_Update) to run every time the value of an opportunity changes.
Can you please help me with this, if it can be made like that?

Thank You
Calin B
I'm VERY new to Apex (literally all coding) and am trying to figure out how to update the Priority to High on an activity after it has become overdue by 10 days.

The Priority field update is the only thing that I need to happen and I cannot figure out what I'm missing.  My alerts are both on line 3; unexpected token ':' and unexpected syntax: 'mismatched input':' expecting Semicolon.
User-added image

Being pointed in the right direction would be greatly appreciated!

Hi

I am using this app from the app exchange (https://appexchange.salesforce.com/listingDetail?listingId=a0N300000016cbDEAQ) to ensure that a contact role is added to an opportunity when a certain stage is selected on the opportunity. This works perfectly when updating an existing opportunity but I dont want it to apply when creating new opportunities.

I thought I could just add NOT(IsNew()) to the custom field, but it gives an error of IsNew can't be used in this type of formula.

Any ideas of how I can exclude this trigger from firing when creating a new opportunity would be appreciated?

Custom Field

IF( 
DATEVALUE( CreatedDate ) >= DATE(2017,09,28), 
CASE( 
StageName, 
"Stage to be Required 1",1, 
"Define",1, 
"Meeting / Proposal",1, 
"Negotiation",1, 
"Verbal Agreement/Contract",1, 
"Closed Won",1, 
0 
), 
0	
)
 


 

Apex Class

//This is provided as a sample to require a contact on opportunities it is provided without warranty and support. 

trigger opportunity_contact_required on Opportunity (before insert, before update) {

    //map to keep track of the contact_required = 1
    Map<String, Opportunity> oppy_contact = new Map<String, Opportunity>();

    //Trigger.new is an array of opportunities 
    //and adds any that have Contact_Required = 1 to the oppy_contact Map
    for (Integer i = 0; i < Trigger.new.size(); i++) {
        System.debug('*****Required? ' + Trigger.new[i].contact_required__c);
        if  (Trigger.new[i].contact_required__c == 1) {
            oppy_contact.put(Trigger.new[i].id,Trigger.new[i]);
        }
    }

    //map to keep track of the opportunity contact roles
    map<Id, OpportunityContactRole> oppycontactroles = new map<Id, OpportunityContactRole>();

    //select OpportunityContactRoles for the opportunities with contact role required 

    List<OpportunityContactRole> roles = [select OpportunityId, IsPrimary from OpportunityContactRole
        where (OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId
        in :oppy_contact.keySet())];


    for (OpportunityContactRole ocr : roles) {
        //puts the contact roles in the map with the Opportunity ID as the key
        oppycontactroles.put(ocr.OpportunityId,ocr);
    }

    // Loop through the opportunities and check if they exists in the contact roles map or contact role isn't required    
    for (Opportunity oppy : system.trigger.new) {
        //system.debug('List oppy Id - '+oppy.id);
        if  (oppy.contact_required__c ==1 && !oppycontactroles.containsKey(oppy.id))
        {
            oppy.addError('No Primary Contact has been added to the opportunity. Please go to the Contact Roles and select a primary contact.');       
        }
    } //for    
 }

Apex Test Class
 
public class test_opportunity_contact_required {


// test to ensure an opportunity can be added

public static testMethod void testoppyrequired0()
    {
        //create oppty 
        List<Opportunity> oppy = new List<Opportunity>();
                                    
        //add 10 opportunites without a contact, and with the condition contact required = 0
        
        for (Integer i = 0; i < 10; i++) {
            oppy.add(new Opportunity(Name='nick_test'+i,StageName='Perception Analysis',CloseDate=System.Today()));
        }
        insert oppy;
        
        map<Id, Opportunity> oppy_map = new map<Id, Opportunity>();
        
        for (Integer i = 0;i<10;++i){
            oppy_map.put(oppy[i].Id,oppy[i]);
        } //for
        
        System.assert([SELECT count() FROM Opportunity WHERE Id IN :oppy_map.keySet()] == 10);   
    } //testoppyrequired = 0
    
    
    //test to go from a not required value to a required value

public static testMethod void testoppyrequired1()
    {   
            //create oppty 
            List<Opportunity> oppy2 = new List<Opportunity>();
                                        
            //add 10 opportunites without a contact, and with the condition contact required = 0       
            for (Integer i = 0; i < 10; i++) {
                oppy2.add(new Opportunity(Name='nick_test'+i,StageName='Qualification',CloseDate=System.Today()));
            }
            
            insert oppy2;
            
            for (Integer i = 0; i < 10; i++) {
                
          	  oppy2[i].StageName='Negotiation/Review';
            
            }

			Test.startTest();

			try {
			
			    update oppy2;
			    
			    Opportunity sampleTest = [Select Id, Contact_Required__c From Opportunity where Id = :oppy2[0].id];
			    
			    System.debug('*****SAMPLE' + sampleTest);
			    
			    System.assert(false, 'This update should have failed.');
			
			} catch(System.DmlException e) {
			
			    System.assert(e.getMessage().contains('No Primary Contact Exists.'));
			
			}

    		Test.stopTest();
       
 
    } //testoppyrequired = 1



public static testMethod void testoppyrequired1woprimary()
    {   
            //create oppty 
            List<Opportunity> oppy = new List<Opportunity>();
                                        
            //add 10 opportunites 
                    
            for (Integer i = 0; i < 10; i++) {
                oppy.add(new Opportunity(Name='nick_test'+i,StageName='Qualification',CloseDate=System.Today()));
            }
            
            insert oppy;
            
            //add 10 contacts
            
            List<Contact> c = new List<Contact>();
                                        
    
            for (Integer i = 0; i < 10; i++) {
                c.add(new Contact(LastName='nick_test'+i));
            }

            insert c;

            for (Integer i = 0; i < 10; i++) {
                
            oppy[i].StageName='Negotiation/Review';
            
            }

            //add 10 opporunity contact roles associated to the opportunities and contacts above
            
            List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
            
            for (Integer i = 0; i < 10; i++) {
                ocr.add(new OpportunityContactRole(Role='Business User',OpportunityId=oppy[i].id,ContactId=c[i].id));
            }
            
            insert ocr;
            
boolean caughtException = false;


Test.startTest();

try {

    update oppy;

} catch(System.DmlException e) {

    System.assert(e.getMessage().contains('No Primary Contact Exists.'));

    caughtException = true;

}

    Test.stopTest();

    System.assert(caughtException);         
 
    } //testoppyrequired = 1


public static testMethod void testoppyrequired1primary()
    {   
            //create oppty 
            List<Opportunity> oppy = new List<Opportunity>();
                                        
            //add 10 opportunites 
                    
            for (Integer i = 0; i < 10; i++) {
                oppy.add(new Opportunity(Name='nick_test'+i,StageName='Qualification',CloseDate=System.Today()));
            }
            
            insert oppy;
            
            map<Id, Opportunity> oppy_map = new map<Id, Opportunity>();
            
            for (Integer i = 0;i<10;++i){
                oppy_map.put(oppy[i].Id,oppy[i]);
            } //for
            
            //add 10 contacts
            
            List<Contact> c = new List<Contact>();
                                        
    
            for (Integer i = 0; i < 10; i++) {
                c.add(new Contact(LastName='nick_test'+i));
            }

            insert c;

            //add 10 opporunity contact roles associated to the opportunities and contacts above
            
            List<OpportunityContactRole> ocr = new List<OpportunityContactRole>();
            
            for (Integer i = 0; i < 10; i++) {
                ocr.add(new OpportunityContactRole(Role='Business User',OpportunityId=oppy[i].id,ContactId=c[i].id,IsPrimary=True));
            }
            
            insert ocr;
            
            for (Integer i = 0; i < 10; i++) {
                
            oppy[i].StageName='Negotiation/Review';
            
            }

			try {
			
			    update oppy;
			    
			        System.assert([SELECT count() FROM Opportunity
			            WHERE Id IN :oppy_map.keySet()] == 10);
			
			} catch(System.DmlException e) {
			
			    System.assert(false);
			
			}   
 
    } //testoppyrequired = 1 and primary contact = true

} //test class





 
Hello Devs, I have the following Trigger and Class that was working fine until this morning when I received the following error of Too Many future calls: 51. 

Any idea how to alleviate gettign this error?  Here is my trigger and class code....thank you all for any help you can provide....

Trigger:
 
trigger DeleteExtraBookingsTrigger on Opportunity (after insert) {

    For(Opportunity opps : Trigger.new){
        If(opps.Auto_Bookings__c == True){
            
            
        DeleteExtraBookingsClass.deleteRecords(Trigger.newMap.keySet());    
            
        }
    }
    
    
}

Class code:
 
public class DeleteExtraBookingsClass {

    @future
    public static void deleteRecords(Set<ID> oppIdsToDelete){
        List<Opportunity> opp = [SELECT ID, Armor_Product_Category__c From Opportunity WHERE ID IN : oppIdsToDelete AND Auto_Bookings__c = True
                                AND (Armor_Product_Category__c = null or Armor_Product_Category__c = 'Armor | null')];
        
        If(opp.size()>0){
        delete opp;
        database.emptyRecycleBin(opp);
        }
    }
    
}

Hello awesome devs! 

Need some help here as I am at a loss why the following Trigger is not setting values on all records but it setting a value on some of the records when doing a mass insert r or update.  When you go to a single record and perform an update the trigger always fires correctly.  

What is trying to be achieved:  

When a record on Object A is created or updated and it includes a SKU in a field called SKU__c .
Then trigger is called on Object A to find a Product from our standard Product2 object that have the same value in the ProductCode field as the SKU__c fiel don Object A.  
When found, a field (Product_Line__c) on Object A should be populated with the value form the found Product2 record and its Product_Line__c field. 

Again this works when updating records one by one, but anythign in mass, will only update a few records.  (Latest example: out of 1097 records in a mass update, only roughly 40 records got updated, the rest have nothign populated in the Product_Line__c field on Object A.

Can anyone look over my code, and help me out? :)

Thank you so much all,

Shawn

Trigger Code:
 
trigger PopulateProductLineOnCharge on Zuora__SubscriptionProductCharge__c (before insert, before update) {

    
    List<Zuora__SubscriptionProductCharge__c> spcToUpdate = new List<Zuora__SubscriptionProductCharge__c>();
    String pLineText = '';
    String SkuText = '';
    Product2 P;
    
    
    For(Zuora__SubscriptionProductCharge__c s : Trigger.new){
        If(s.Product_Line__c == null && s.SKU__c != null){
            SkuText = s.SKU__c;
        }
    }
    
    If(SkuText != null){
    P = [SELECT Id, Product_Line__c, ProductCode FROM Product2 WHERE ProductCode = : SkuText LIMIT 1];
    
    For(Zuora__SubscriptionProductCharge__c s2 : Trigger.New){
        If(SkuText.contains(s2.SKU__c)){
            s2.Product_Line__c = p.Product_Line__c;
            spcToUpdate.add(s2);
        }
        }
    }
 
}

 
Hello awesome devs! 

I have the followign trigger which works as intended, however when I do a mass upload or mass edit on more than 10 Lead records, I always get the "Apex CPU Time Limit Exceeded" error.  Can anyone tell me how to resolve this error in my code as if my users do a mass update of more than 10 lead records to assume ownership it throws this error and any other time an insert or update of more than 10 Lead records at a time. 

Thanks so much for any help you can provide,

Shawn

Trigger code:
 
trigger LeadCountOfTasks on Task (after delete, after insert, after undelete, after update) {
    Task [] tlist;
        if(Trigger.isDelete)
            tlist= Trigger.old;
        else
            tlist = trigger.new;
    set<id> lid = new set< id> ();
    
    If(!tlist.isEmpty()){
    for(Task ts : tlist)
    {   if(ts.WhoId!=null && ts.whatId == null)
    {
        If(string.valueOf(ts.WhoId).startsWith('00Q'))
        {
        lid.add(ts.Whoid);
    }
    }
    }
    If(lid.size()>0){
    Map <id,Task > tmap = new Map <id, Task>([select id, Whoid from Task where Whoid in:lid]);
    Map <id, Lead> lmap = new Map <id, Lead>([select id,Count_Activity__c from lead where id in:lid ]);
    
        If(lmap.size()>0){
       List<Lead> llist = [SELECT Id, Count_Activity__c FROM Lead WHERE ID IN:lmap.values()]; 
    for(lead l : lmap.values())
    {
        set<id> tids = new set <id>();
        for(Task tt : tmap.values())
        {
           if(tt.WhoId== l.Id)
            tids.add(tt.id);
        }
        if(l.Count_Activity__c!=tids.size())
        l.Count_Activity__c=tids.size();
        
              tlist = [select id, Whoid from task where whoid in:lid ];
        for(lead le :llist)
        {
            for(Task te:tlist)
            {
                if(tlist.size()>0)
                le.Count_Activity__c = tlist.size();
            }
        }
        
        
    }
    If(lmap.size()>0){
    update lmap.values();
    }
    }
    }
    }
}

 
Hello awesome devs!

I am attempting to create a VF page with 4 fields for user inputting.  2 of these fields are Date fields which when filled in like MM/DD/YYY when I press the search button to call my custom controller the date in the field populated has its format changed to Tue Dec 26 00:00:00 GMT 2017 and doesnt seem to be being applied in the search itself as all records are returned and not ones just for the date entered. 

Can someone help me with gettign the format to stay as I think this is the cause of the date field not being used in the search criteria. 

Please see my VF Page and controller code below. 

Thank you very much for any help you can provide,

Shawn

VF Page Code - 
 
<apex:page controller="SubSearchController">
    
    <apex:form>
    	<apex:pageBlock id="pb">
        	<apex:pageBlockButtons>
                <apex:commandButton action="{!searchRecords}" value="Search" rerender="pb"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="2">
                <apex:outputLabel value="Account Id" />
                <apex:inputText value="{!AccId}"/>
                <apex:outputLabel value="Status" />
                <apex:inputText value="{!SubStatus}"/>
                <apex:outputLabel value="Service Activation date" />
                <apex:inputText value="{!SAD}"/>
                <apex:outputLabel value="Term End Date" />
                <apex:inputText value="{!TermEnd}"/>
            </apex:pageBlockSection>
            <apex:pageBlockTable var="record" value="{!records}" id="pbTable">
                <apex:column value="{!record.Name}" />
                <apex:column value="{!record.Zuora__Status__c}" />
                <apex:column value="{!record.Zuora__ServiceActivationDate__c}" />
                <apex:column value="{!record.Zuora__TermEndDate__c}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
    
</apex:page>

Controller Code -

public class SubSearchController {

    public String AccId {get;set;}
    public String SubStatus {get;set;}
    public Date SAD {get;set;}
    public Date sadDate = Date.valueOf(SAD);
    public Date TermEnd {get;set;}
    public Date TermDate = Date.valueOf(TermEnd);
    
    public List<Zuora__Subscription__c> records {get; private set;}
    
    public SubSearchController(){
        records = new List<Zuora__Subscription__c>();   
    }
    
    public PageReference searchRecords() {
        
        records = [SELECT Zuora__Account__c, Zuora__Status__c, Zuora__ServiceActivationDate__c, Zuora__TermEndDate__c, OpportunityId__c, Total_Booking_Amount__c, Id, Name
                  FROM Zuora__Subscription__c WHERE Zuora__Account__c = : AccId AND Zuora__Status__c = : SubStatus AND (Zuora__ServiceActivationDate__c = : sadDate OR Zuora__TermEndDate__c = :TermDate)];
        return null;
        
    }
    
}

 
Hello awesome developers...I am not sure why I am gettign SOQL 101 Errors on the following trigger.  

Can anyone give some advice on what to try to ensure we are not gettign this error. 

What I am tring to do is if an account goes to an active state after an update, it should go and grab all contacts that meet some criteria and update a field on all of the contact records. 

Any help would be greatly appreciated...

Thanks in advance,

Shawn

Trigger code - 
 
trigger SetAccountActiveOnContactRecord on Account (after insert, after update) {

    
    List<Contact> consToUpdate = new List<Contact>();
    
    For(Account a : Trigger.new){
        If(a.Status__c == 'Active'){
            List<Contact> consToAdd = [SELECT ID, Account_Active__c, AMP_Notification_Types__c, Contact_Types__c FROM Contact WHERE AccountId = : a.Id AND Account_Active__c != True AND 
                                       (AMP_Notification_Types__c INCLUDES('Technical','Billing','Account') OR Contact_Types__c INCLUDES('Technical')) LIMIT 100];
            
            If(consToAdd.size()>0){
            For(Contact c : consToAdd){
                
                c.Account_Active__c = True;
                consToUpdate.add(c);
            
            }
            }
        }
    }
    
    if(consToUpdate.size()>0){
        update consToUpdate;
    }
    
    
}

 
Hello Awesome Devs!!!

I have the following Scheduled Class, and test class, and I am only able to get the code coverage on this class to 70 percent.  Looks like the issue is in my IF , ELSE IF statements, as the Null check always tests out, but if I am stating that the field is not null/blank then the code aftere that doe snot get covered.  

Can anyone help me figure out what is going on here and help to get this above the acceptable coverage limit?

Appreciate any help you can provide,

Shawn

Class - 
 
global class CreateUpgradeDowngradeOpportunities Implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        CreateOpportunities();
    }
      
    public void CreateOpportunities()
    {
        //Variable & List Declarations
        
        Date Today = Date.Today();
        Date d1 = Today.addDays(-1);
		List<Opportunity> lstOpp = new List<Opportunity>();
		Opportunity objOpp;
		Id idRecTypeDowngrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Downgrade').getRecordTypeId();
		Id idRecTypeUpgrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Upgrade').getRecordTypeId();
        User FH = [Select ID FROM User WHERE FirstName = 'Firehost' LIMIT 1];
		Map<Id, Account> mapAcc = new Map<Id, Account>();
		Id idAcc;
		String strStatus;
		Decimal amt;
		Set<Id> setIdAcc = new Set<Id>();
		List<AggregateResult> lstAR = new List<AggregateResult>();
		
		// collect sum by account
		for(AggregateResult objAR : [SELECT Zuora__Account__c , Zuora__Status__c, SUM(Zuora__MRR__C) 
									FROM Zuora__Subscription__c 
									WHERE Zuora__Status__c IN ('Cancelled', 'Active')
										AND Zuora__Account__c != NULL
										AND (Zuora__TermStartDate__c = YESTERDAY OR Zuora__TermEndDate__c = YESTERDAY)
                                     // Add additional Criteria here..
									GROUP BY ROLLUP(Zuora__Account__c, Zuora__Status__c)])
		{
			lstAR.add(objAR);
			setIdAcc.add((Id)objAR.get('Zuora__Account__c'));
		} // End of Aggregate For Loop
		
		// collect account infos
		if(!setIdAcc.isEmpty())
		{
			mapAcc = new Map<Id, Account>([SELECT Id, Name, OwnerId, Service_Lead__c FROM Account WHERE Id IN: setIdAcc]);   
		}
		
		// create opps
		for(AggregateResult objAR : lstAR)
		{
			idAcc = (Id)objAR.get('Zuora__Account__c');
			strStatus = (String)objAR.get('Zuora__Status__c');
			amt = (Decimal)objAR.get('expr0');
            
			if(strStatus == 'Cancelled' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeDowngrade;
				objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Downgrade';
				objOpp.Amount = amt * -1;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Cancelled';    
				lstOpp.add(objOpp);    
			}
            else if(strStatus == 'Cancelled' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeDowngrade;
				objOpp.OwnerId = FH.Id;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Downgrade';
				objOpp.Amount = amt * -1;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Cancelled';    
				lstOpp.add(objOpp);    
			}
			else if(strStatus == 'Active' && !String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeUpgrade;
				objOpp.OwnerId = mapAcc.get(idAcc).Service_Lead__c;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Existing Business';
				objOpp.Amount = amt;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Closed Won';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
				lstOpp.add(objOpp);
			}
            else if(strStatus == 'Active' && String.isBlank(mapAcc.get(idAcc).Service_Lead__c))
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeUpgrade;
				objOpp.OwnerId = FH.Id;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Existing Business';
				objOpp.Amount = amt;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Closed Won';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
				lstOpp.add(objOpp);
			}
		} // END of FOR Loop

		if(!lstOpp.isEmpty())
		{
			insert lstOpp;
		}
    } // End of CreateOpportunities Method 
} // End of Class

Test Class -
 
@isTest(SeeAllData = True)
public class CreateUpgradeDowngradeOpportunitiesTest {

    List<Zuora__Subscription__c> subs = new List<Zuora__Subscription__c>();
    
    
    private static testMethod void tm1(){
        
    	Date Today = Date.Today();
    	Date d1 = Today.addDays(-1);
        User u = [SELECT ID FROM USER WHERE FirstName = 'FireHost' LIMIT 1];
        
        Account a = New Account();
        a.Name = 'Test Account';
        a.Status__c = 'Active';
        insert a;
        
        Account a2 = New Account();
        a2.Name = 'Test Account 2';
        a.Status__c = 'Active';
        a.Service_Lead__c = u.Id;
        insert a2;
        
        Zuora__Subscription__c s = new Zuora__Subscription__c();
        s.Zuora__Account__c = a.Id;
        s.Zuora__Status__c = 'Active';
        s.Zuora__MRR__c = 100;
        s.Zuora__TermStartDate__c = d1;
        insert s;
        
        Zuora__Subscription__c s2 = new Zuora__Subscription__c();
        s2.Zuora__Account__c = a.Id;
        s2.Zuora__Status__c = 'Cancelled';
        s2.Zuora__MRR__c = 100;
        s2.Zuora__TermStartDate__c = d1;
        insert s2;
        
        Zuora__Subscription__c s3 = new Zuora__Subscription__c();
        s3.Zuora__Account__c = a2.Id;
        s3.Zuora__Status__c = 'Active';
        s3.Zuora__MRR__c = 100;
        s3.Zuora__TermStartDate__c = d1;
        insert s3;
        
        Zuora__Subscription__c s4 = new Zuora__Subscription__c();
        s4.Zuora__Account__c = a2.Id;
        s4.Zuora__Status__c = 'Cancelled';
        s4.Zuora__MRR__c = 100;
        s4.Zuora__TermStartDate__c = d1;
        insert s4;


        String CRON_EXP = '0 0 0 15 3 ? *';
        

		String jobId = System.schedule('ScheduleApexClassTest',  CRON_EXP, new CreateUpgradeDowngradeOpportunities());
		CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
		System.assertEquals(CRON_EXP, ct.CronExpression);
		System.assertEquals(0, ct.TimesTriggered);

    }
    
}

Hello awesome devs...I have a good one here today! 

The company has had a Consulting group create a VF page and controller to do the following function.  It seems that thier Test class was removed from our environment somehow as this is in our production org, however no test class provides any code coverage any longer.  I need to make a small edit to the VF page, and want to ensure that the controller has proper coverage after I make the small tweak, but again I can not find any test class that provides coverage.  Thsi was done a few years back so the change sets that included this info has expired and we no longer have visibility into it.  So I need to create a new test class, but am unsure how to for this piece of particular code. 

Can anyone help to help me create a test class for the folllowing code?

On Object A - the new button is pressed, which navigates you to the VF page which allows you to either

A: select an existing account with a specific record type or:
B: if not found the next section of the VF page will allow you to create a new Account record to use for the custom object upon saving the VF page. 

Here is the controller code for this VF page
 
public class new_testVfpage {
    
    Public Purchase_request__c pr{get;set;}
    Public string accountname{get;set;}
    Public string phonenumber{get;set;}
    Public string Billingstreet{get;set;}
    Public string Billingcity{get;set;}
    public string contactname{get;set;}
    public string contactemail{get;set;}
    Public String billingzipcode{get;set;}
    public Account account {get;set;}
    Public string testfield{get;set;}
    public boolean isExistError{get;set;}
    public boolean isNullError{get;set;}

    public new_testVfpage(ApexPages.StandardController sc) {
        pr= (Purchase_request__c )sc.getRecord();
        account=new account();
        pr.Renewal__c='Existing Vendor';
        Id rtid= Schema.SObjectType.Purchase_request__c.getRecordTypeInfosByName().get('PR Existing Vendor, No V-Qs /w Submit').getRecordTypeId();
        pr.recordtypeid =rtid;
        isExistError=false;
        
    }
    
    Public pagereference newsave(){
        integer needDesc = 0;
        integer descMax = 0;
        testfield=pr.Vendor_Name__c;

        //Identifiy if Insert or Update Vendor Type of Record Type
        Id vendorId = Schema.SobjectType.Account.getRecordTypeInfosByName().get('Vendor').getRecordTypeId();
        List<Account> accList = [SELECT Id FROM Account where Id = :pr.Vendor_Name__c AND RecordType.Id =: vendorId];

        if(accList.IsEmpty()){//insert
            Id prrtid= Schema.SObjectType.Purchase_request__c.getRecordTypeInfosByName().get('PR All Questions /w Submit Button').getRecordTypeId();
            pr.RecordTypeId = prrtid; //'01270000000UQfyAAG'; //PR All Questions /w Submit Button
        }else{//Update
            Id prrtid = Schema.SObjectType.Purchase_request__c.getRecordTypeInfosByName().get('PR Existing Vendor, No V-Qs /w Submit').getRecordTypeId();
            pr.RecordTypeId = prrtid; //'01270000000UQg1AAG'; //PR Existing Vendor, No V-Qs /w Submit
        }
        
       //CheckVendor Name is Empty
       if(testfield == null || testfield ==''){   
          //When Account Name has value    
          if(accountname!= '' && accountname!= null){
              account.name=accountname;
              isExistError=false;
              //New Vendor will check the following fields
              if((account.Will_vendor_store_NPPI_or_PCI_data__c != 'Yes' && account.Will_vendor_store_NPPI_or_PCI_data__c != 'No')){
                  ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Will vendor store NPPI or PCI data? is required'));
                  isExistError=true;
              }
              
              if((account.Will_vendor_store_PHI_data__c != 'Yes' && account.Will_vendor_store_PHI_data__c != 'No')){
                  ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Will vendor store PHI data?'));
                  isExistError=true;
              }
              
              if((account.Will_vendor_store_Armor_corporate_data__c != 'Yes' && account.Will_vendor_store_Armor_corporate_data__c != 'No')){
                  ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Will vendor store Armor corporate data? is required'));
                  isExistError=true;
              }
              
              if((account.Will_vendor_access_Armor_or_Cust_data__c != 'Yes' && account.Will_vendor_access_Armor_or_Cust_data__c != 'No')){
                  ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Will vendor access Armor or Customer Data? is required'));
                  isExistError=true; 
              }
              
              if((account.Are_vendor_services_Critical_to_Armor__c!= 'Yes' && account.Are_vendor_services_Critical_to_Armor__c!= 'No')){
                  ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Are vendor services critical to Armor? is required'));
                  isExistError=true;
              }
              //removes error if all the condition of required fields for new vendor is Yes
              if((account.Will_vendor_store_NPPI_or_PCI_data__c != '' && account.Will_vendor_store_NPPI_or_PCI_data__c != null && account.Will_vendor_store_NPPI_or_PCI_data__c != '--None--')
              && (account.Will_vendor_store_PHI_data__c != '' && account.Will_vendor_store_PHI_data__c != null && account.Will_vendor_store_PHI_data__c != '--None--')
              && (account.Will_vendor_store_Armor_corporate_data__c != '' && account.Will_vendor_store_Armor_corporate_data__c != null && account.Will_vendor_store_Armor_corporate_data__c != '--None--')
              && (account.Will_vendor_access_Armor_or_Cust_data__c != '' && account.Will_vendor_access_Armor_or_Cust_data__c != null && account.Will_vendor_access_Armor_or_Cust_data__c != '--None--')
              && (account.Are_vendor_services_Critical_to_Armor__c != '' && account.Are_vendor_services_Critical_to_Armor__c != null && account.Are_vendor_services_Critical_to_Armor__c != '--None--')){
                  isExistError=false;
              }
              
                //Error if NPPI/PCI desc is null when account.Will_vendor_store_PHI_data__c value is yes
                if(account.Will_vendor_store_NPPI_or_PCI_data__c == 'Yes' ){
                    if(account.NPPI_PCI_If_Yes_enter_description__c != null){
                       isExistError=false;
                       isNullError=false;
                    }else{
                        ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'NPPI/PCI is set to Yes please enter description'));
                        isExistError=true;
                        isNullError=true;
                    }
            
                }else{
                    if(account.Will_vendor_store_NPPI_or_PCI_data__c == 'No'){
                        isExistError=false;
                        isNullError=false;
                    }else{
                        isExistError=true;
                    }
                }
            
                //Error if PHI desc is null when account.Will_vendor_store_PHI_data__c value is yes
                //if(account.Will_vendor_store_PHI_data__c == 'Yes' ){
                if(account.Will_vendor_store_PHI_data__c == 'Yes' ){
                    if(account.PHI_If_Yes_enter_description__c != null){
                       if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'PHI is set to Yes please enter description'));
                        isExistError=true;
                        isNullError=true; 
                    }
                
                }else{
                    if(account.Will_vendor_store_PHI_data__c == 'No'){
                        if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        isExistError=true;
                    }
                }
            
                //Error if Corp Data desc is null when Corp Data value is yes
                if(account.Will_vendor_store_Armor_corporate_data__c == 'Yes' ){
                    if(account.Corp_Data_If_Yes_enter_description__c != null){
                       if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Corp Data is set to Yes please enter description'));
                        isExistError=true;
                        isNullError=true; 
                    }
                
                }else{
                    if(account.Will_vendor_store_Armor_corporate_data__c == 'No'){
                        if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        isExistError=true;
                    }
                }
            
                //Error if Access Data desc is null when Access Data value is yes
                if(account.Will_vendor_access_Armor_or_Cust_data__c == 'Yes' ){
                    if(account.Cust_Data_If_Yes_enter_description__c != null){
                       if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Access Data is set to Yes please enter description'));
                        isExistError=true;
                        isNullError=true; 
                    }
                
                }else{
                    if(account.Will_vendor_access_Armor_or_Cust_data__c == 'No'){
                        if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        isExistError=true; 
                    }
                }
                
                //Error if Critical desc is null when account.Are_vendor_services_Critical_to_Armor__c value is yes
                if(account.Are_vendor_services_Critical_to_Armor__c == 'Yes' ){
                    if(account.Critical_If_Yes_enter_description__c != null){
                       if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Critical is set to Yes please enter description'));
                        isExistError=true;
                        isNullError=true;    
                    }
                
                }else{
                    if(account.Are_vendor_services_Critical_to_Armor__c == 'No'){
                        if(isNullError==false){
                           isExistError=false;
                           isNullError=false;
                       }
                    }else{
                        isExistError=true;   
                    }
                }
                
                //removes error if all required fields are not null
                if((account.Will_vendor_store_NPPI_or_PCI_data__c == 'Yes')
                  && (account.Will_vendor_store_PHI_data__c == 'Yes' )
                  && (account.Will_vendor_store_Armor_corporate_data__c == 'Yes')
                  && (account.Will_vendor_access_Armor_or_Cust_data__c == 'Yes')
                  && (account.Are_vendor_services_Critical_to_Armor__c == 'Yes')){
                    //Description null check                      
                    if((account.NPPI_PCI_If_Yes_enter_description__c != null && account.NPPI_PCI_If_Yes_enter_description__c != '')
                     &&(account.PHI_If_Yes_enter_description__c != null && account.PHI_If_Yes_enter_description__c != '')
                     &&(account.Corp_Data_If_Yes_enter_description__c != null && account.Corp_Data_If_Yes_enter_description__c != '')
                     &&(account.Cust_Data_If_Yes_enter_description__c != null && account.Cust_Data_If_Yes_enter_description__c != '')
                     &&(account.Critical_If_Yes_enter_description__c != null && account.Critical_If_Yes_enter_description__c != '')
                    ){
                        isExistError=false;
                    }else{
                        isExistError=true;
                    }
                 }
          }else{
              ApexPages.addMessage(new apexpages.message(ApexPages.Severity.ERROR, 'Account Name is required'));
              isExistError=true;
          }
          
          
                
        Id accrtid= Schema.SObjectType.Account.getRecordTypeInfosByName().get('Vendor').getRecordTypeId();
            account.recordtypeid=accrtid;
       
        contact c=new contact(); 
        if(contactname!= '' && contactname !=null){
           c.lastName=contactname;
        }
        if(isExistError==true){
            return null;
        }else{    
         upsert account;
         Upsert Pr; 
        }
         
        if(contactname != '' && contactname !=null){
        c.accountid=account.id;
        c.LeadSource='PR VF Page - Manually';
        insert c;
        }
         
        pr.Vendor_Name__c=account.id;
        pr.Renewal__c='New Vendor';
        upsert Pr; 
        }
        if(accountname!= '' && accountname!= null){
            upsert Pr;
            return new PageReference('/'+pr.Id+'/e?retURL=%2F'+pr.Id); 
        }else{
            if(testfield == null || testfield ==''){
                return null; 
            }else{
                upsert Pr;
                return new PageReference('/'+pr.Id+'/e?retURL=%2F'+pr.Id); 
            } 
        }   
             
    }
    
}

 
Awesome developers!

I have the following trigger that is operating as intended, however every now and then I receive an Null pointer exection error on line 21 of the following code.  I can not trace this back to anything and the code looks to be looking for nulls but again I am not a very seasoned developer with code so I am hopign someone can help share why this error is generated every now and then.  

Appreciate the help!
trigger AcctPaymentRollup on Zuora__Payment__c (after insert, after update, before delete, after unDelete) {
    List<Id> AccIds=new List<Id>();
    
If(Trigger.isInsert || Trigger.isUpdate || Trigger.isUnDelete) {
    for(Zuora__Payment__c mst:Trigger.New){
    if(mst.Zuora__Account__c !=null && mst.Zuora__AppliedInvoiceAmount__c != null && mst.Zuora__GatewayStatus__c == 'Submitted' && mst.Zuora__PaymentMethod__c != 'Check'){
     AccIds.add(mst.Zuora__Account__c);
    }
        else if (mst.Zuora__Account__c != null && mst.Zuora__AppliedInvoiceAmount__c != null && (mst.Zuora__PaymentMethod__c == 'Check' || string.ValueOf(mst.Zuora__PaymentMethod__c).startsWith('ACH'))){
            AccIds.add(mst.Zuora__Account__c);
        }
    }
   

   Map<Id,Account> AccMap = new Map<Id,Account>([select id,Current_Invoice_Amount_Paid__c from Account where id in:AccIds]);
   
   for(Zuora__Payment__c mst:Trigger.New)
   {
        if(AccMap != NULL && !AccMap.IsEmpty())
        {
            AccMap.get(mst.Zuora__Account__c).Current_Invoice_Amount_Paid__c = mst.Zuora__AppliedInvoiceAmount__c;
        
        }
   }

   if(AccMap != NULL && !AccMap.IsEmpty())
   {
        update AccMap.values();
   }}
   
   If(Trigger.isDelete) {
    for(Zuora__Payment__c mst:Trigger.Old){
    if(mst.Zuora__Account__c !=null && mst.Zuora__GatewayStatus__c == 'Submitted' && mst.Zuora__PaymentMethod__c != 'Check'){
     AccIds.add(mst.Zuora__Account__c);
    }
    else if (mst.Zuora__Account__c != null && (mst.Zuora__PaymentMethod__c == 'Check' || string.ValueOf(mst.Zuora__PaymentMethod__c).startsWith('ACH'))){
     AccIds.add(mst.Zuora__Account__c);   
        }
    }
   

   Map<Id,Account> AccMap = new Map<Id,Account>([select id,Current_Invoice_Amount_Paid__c from Account where id in:AccIds]);
   
   for(Zuora__Payment__c mst:Trigger.Old)
   {
        if(AccMap != NULL && !AccMap.IsEmpty())
        {
            AccMap.get(mst.Zuora__Account__c).Current_Invoice_Amount_Paid__c = AccMap.get(mst.Zuora__Account__c).Current_Invoice_Amount_Paid__c - mst.Zuora__AppliedInvoiceAmount__c;
        }
   }

   if(AccMap != NULL && !AccMap.IsEmpty())
   {
        update AccMap.values();
   }}

}

 
Devs,

I am wondering if there is a way to create an Apex class that will upon creating a new sandbox or refreshing an existing sandbox, that will scour the Email template object and find any email addresses in the Additional email Address fields specificaly for workflow email alerts and then edit them to make then un-usable just as the email addresses for users is edited to include somethign like @example.com.com or somethign of our choosing to ensure that a lot of manual tasks of running through each email alert to either edit manaully or remove completely for testing. 

I have not been able to find any help on this and wasnt sure if anyone has been able to do this somehow,

Thanks for your time,


Shawn
Hello great Devs out there!

I have the following Schedulable apex class that I need a test class for.  I am attaching the test class I have attempted but I am getting errors.  Can anyone tell me if this is the correct approach for a test class for the following code as I have written test classes before but not for scheduled code so what am I missing?  

Thanks for helping this newbie at code out!

Shawn

Scheduled Class Code - 
 
global class CreateUpgradeDowngradeOpportunities Implements Schedulable
{
    global void execute(SchedulableContext sc)
    {
        CreateOpportunities();
    }
      
    public void CreateOpportunities()
    {
        //Variable & List Declarations
        
        Date Today = Date.Today();
        Date d1 = Today.addDays(-1);
		List<Opportunity> lstOpp = new List<Opportunity>();
		Opportunity objOpp;
		Id idRecTypeDowngrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Downgrade').getRecordTypeId();
		Id idRecTypeUpgrade = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Upgrade').getRecordTypeId();
		Map<Id, Account> mapAcc = new Map<Id, Account>();
		Id idAcc;
		String strStatus;
		Decimal amt;
		Set<Id> setIdAcc = new Set<Id>();
		List<AggregateResult> lstAR = new List<AggregateResult>();
		
		// collect sum by account
		for(AggregateResult objAR : [SELECT Zuora__Account__c , Zuora__Status__c, SUM(Zuora__MRR__C) 
									FROM Zuora__Subscription__c 
									WHERE Zuora__Status__c IN ('Cancelled', 'Active')
										AND Zuora__Account__c != NULL
										AND (Zuora__TermStartDate__c = YESTERDAY OR Zuora__TermEndDate__c = YESTERDAY)
									GROUP BY ROLLUP(Zuora__Account__c, Zuora__Status__c)])
		{
			lstAR.add(objAR);
			setIdAcc.add((Id)objAR.get('Zuora__Account__c'));
		} // End of Aggregate For Loop
		
		// collect account infos
		if(!setIdAcc.isEmpty())
		{
			mapAcc = new Map<Id, Account>([SELECT Id, Name, OwnerId FROM Account WHERE Id IN: setIdAcc]);
		}
		
		// create opps
		for(AggregateResult objAR : lstAR)
		{
			idAcc = (Id)objAR.get('Zuora__Account__c');
			strStatus = (String)objAR.get('Zuora__Status__c');
			amt = (Decimal)objAR.get('expr0');
			if(strStatus == 'Cancelled')
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeDowngrade;
				objOpp.OwnerId = mapAcc.get(idAcc).OwnerId;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Downgrade';
				objOpp.Amount = amt * -1;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Cancelled';    
				lstOpp.add(objOpp);    
			}
			else if(strStatus == 'Active')
			{
				objOpp = new Opportunity();
				objOpp.RecordTypeId = idRecTypeUpgrade;
				objOpp.OwnerId = mapAcc.get(idAcc).OwnerId;
				objOpp.Name = mapAcc.get(idAcc).Name + ' - AMP';
				objOpp.AccountId = mapAcc.get(idAcc).Id;
				objOpp.Opportunity_Source__c = 'Portal';
				objOpp.Type = 'Existing Business';
				objOpp.Amount = amt;
				objOpp.CloseDate = d1;
				objOpp.StageName = 'Closed Won';
                objOpp.Closed_Comments__c = 'AMP Portal Self Service Upgrade';
				lstOpp.add(objOpp);
			} 
		} // END of FOR Loop

		if(!lstOpp.isEmpty())
		{
			insert lstOpp;
		}
    } // End of CreateOpportunities Method 
} // End of Class

My Attempt at the test class for this scheduled class. as you can see I create an Accoutn record and date variables and then use them in the Subscription record as needed, and then run my scheduled class.  Thought this would have done the trick....but nope...
 
@isTest
public class CreateUpgradeDowngradeOpportunitiesTest {

    List<Zuora__Subscription__c> subs = new List<Zuora__Subscription__c>();
    
    
    private static testMethod void tm1(){
        
    	Date Today = Date.Today();
    	Date d1 = Today.addDays(-1);
        
        Account a = New Account();
        a.Name = 'Test Account';
        a.Status__c = 'Active';
        insert a;
        
        Zuora__Subscription__c s = new Zuora__Subscription__c();
        s.Zuora__Account__c = a.Id;
        s.Zuora__Status__c = 'Active';
        s.Zuora__MRR__c = 100;
        s.Zuora__TermStartDate__c = d1;
        insert s;
        
        CreateUpgradeDowngradeOpportunities sc= new CreateUpgradeDowngradeOpportunities();
		sc.execute(null);
        
    }
    
    
    
    
}



Hello Awesome Developers.....

I have the following trigger that should be updating an Apttus Quote Record based on Line Items that are added.  

Ultimately what I am trying to achieve is when a new Apttus config file is created (gets created when a cart is finalized) and is marked finalized for its status, look for the line Items associated with that Apttus config record, and if any of those items has a particualr product code through the product selected to be used and its quantity is greater that 3 then add those records to a list and then for that list update the master Quote record to have a checkbox checked true which will then require an approval to be done.  

Looks like through my debug statements I can see that the records and lists are being treated fine up until line 45 as the master quote record does not get updated.  

Any help on this would be greatly appreciated, and if you need any mor einformation, please ask,

Thanks again,

Shawn

Trigger Code:
 
trigger ColocationCrossConnectApproval on Apttus_Config2__ProductConfiguration__c (before insert, before update) {

    List<Apttus_Config2__LineItem__c> colocationList = new List<Apttus_Config2__LineItem__c>();
    	system.debug('colocationList Size Initial -'+colocationList.size());
    List<Apttus_Config2__LineItem__c> crossConnectList = new List<Apttus_Config2__LineItem__c>();
    	system.debug('crossConnectList Size Initial -'+crossConnectList.size());
    List<Apttus_Config2__ProductConfiguration__c> configRecords = new List<Apttus_Config2__ProductConfiguration__c>();
    	system.debug('configRecords Size Initial -'+configRecords.size());
    
    For(Apttus_Config2__ProductConfiguration__c config : Trigger.new){
        
        If(config.Apttus_Config2__Status__c == 'Finalized'){
                configRecords.add(config);
            	system.debug('configRecords Size After -'+configRecords.size());
        } // End of Status = Finalized If Statement
     } // End of Trigger.New For Loop
    
    If(configRecords.size()>0){
  
    	For(Apttus_Config2__ProductConfiguration__c configToWork : configRecords){
        
            List<Apttus_Config2__LineItem__c> colocationItems = [SELECT ID, Name, Apttus_Config2__OptionId__c,Apttus_Config2__OptionId__r.ProductCode,
                                                                 Apttus_Config2__ConfigurationId__c,Apttus_Config2__Quantity__c,
                                                                 Apttus_Config2__ConfigurationId__r.Apttus_QPConfig__Proposald__r.ColocationApprovalRequired__c,
                                                                 Apttus_Config2__ConfigurationId__r.Apttus_QPConfig__Proposald__r.CrossConnectApprovalRequired__c 
                                                                 FROM Apttus_Config2__LineItem__c 
                                                                 WHERE Apttus_Config2__ConfigurationId__c IN : configRecords];
            system.debug('colocationItems Size -' + colocationItems.size());
            
            For(Apttus_Config2__LineItem__c coLoItems : colocationItems){
                
                If(coLoItems.Apttus_Config2__OptionId__r.ProductCode == 'SAN-001' && coLoItems.Apttus_Config2__Quantity__c > 3){
                    colocationList.add(coLoItems);
                    	system.debug('colocationList Size After -'+colocationList.size());
                } // End Of Colocation If Statement To Add CoLocation Line Items to colocationList
                
                else If(coLoItems.Apttus_Config2__OptionId__r.ProductCode == 'SAN-002' && coLoItems.Apttus_Config2__Quantity__c > 3) {
                    crossConnectList.add(coLoItems);
                    	system.debug('crossConnectList Size After -'+crossConnectList.size());
                } // End of Else If Statement to add Cross Connect Lines to crossConnectList   
            } // End of Line For Loop   
    	} // End of configToWork For Loop
    } // End Of Bulkify If Statement
    
    If(colocationList.size()>0){
        For(Apttus_Config2__LineItem__c finalcoLoList : colocationList){
            finalcoLoList.Apttus_Config2__ConfigurationId__r.Apttus_QPConfig__Proposald__r.ColocationApprovalRequired__c = True;
            Database.update(finalcoLoList);
        } // End of finalcoLoList For Loop
    } // End of colocationList size If Statement
    
    If(crossConnectList.size()>0){
        For(Apttus_Config2__LineItem__c finalcrossList : crossConnectList){
            finalcrossList.Apttus_Config2__ConfigurationId__r.Apttus_QPConfig__Proposald__r.CrossConnectApprovalRequired__c = True;
            Database.update(finalcrossList);
        } // End of finalcrossList For Loop
    } // End of crossconnectList size If Statement    
} // End Of Trigger

 
Hello Awesome Developers! 

I am hoping one of you heroes out there can help me with a requirmeent I have.  Let me be up front, I have not been developing in apex for long and have not had any other developign experience with code in any other language or platform, so in other words a newbie. :)

So here is the deal, I have a need to have opportnities created every night based upon another object having records created the previous day. This object is a Zuora application object called Subscriptions and a record would be created whenever a customer of ours would use our self servic eportal (outside of Salesforce) to perform an upgrade or downgrade of thier services.  This action by the customer will create a Subscription record in Salesforce and when those get created I need every night to create an Upgrade or downgrade Opportunity from those subscription records created. Also we need to batch the same customer so if they do 3 upgrades, we take the amount from all three subscription records and sum them so that we only create one opportunity per customer for upgrades and an opportunity for downgrades and then have the Amoutn field on th enewly created opp be the total sum of the Upgrade subscription records and if there are downgrades, the same would need to happen to sum all of those downgrade record amounts into one opp and the amount would be that SUM.  

Please see my attempt at this code below, where I am setting the class as a scheduled class, and when I run this in the Dev console no opps are bneing created even though I have subscription records I manually created for this test.  That is issue number one, gettign this to create opps, but I havent gotten as far to test if the Aggregate function being used will do the magic of SUMing thw amounts and only creating one opportunity per account for all upgrades and one opp for all downgrades for that account. 

I hope this makes sense, I am just tryign to once a night, grab all subscriptions created for that day (Actually this will run at 2AM so createddate would be the day before) and then rn though those Subscription records and create one opp per account and have the amoutn be the sum for both types (Upgrades and downgrades) 

Thank you very much for your help! 

Shawn
 
global class CreateUpgradeDowngradeOpportunities Implements Schedulable
{
     global void execute(SchedulableContext sc)
      {
            CreateOpportunities();
      }
      
      public void CreateOpportunities()
      {
         Date d1 = system.today()-1;
         List<Zuora__Subscription__c> SubsCreated = [SELECT Id, Name, Zuora__Account__c, Zuora__MRR__c, Zuora__Status__c FROM Zuora__Subscription__c WHERE CreatedDate =: d1];
          
          For(Zuora__Subscription__c z : SubsCreated){
              If(z.Zuora__Status__c == 'Cancelled'){
                  AggregateResult[] groupedResultsDown = [SELECT Zuora__Account__c , SUM(Zuora__MRR__C) FROM Zuora__Subscription__c WHERE ID IN: SubsCreated GROUP BY Zuora__Account__c];
                 //Create Downgrade Opp 
                 
                  List<Opportunity> downgradeOpps = new List<Opportunity>();
                 
                  For(AggregateResult ard : groupedResultsDown){
                   
                      Opportunity od = new Opportunity();
                      	od.RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Downgrade').getRecordTypeId();
                      	od.OwnerId = z.Zuora__Account__r.OwnerId;
                      	od.Name = z.Zuora__Account__r.Name + ' - AMP';
                      	od.AccountId = z.Zuora__Account__r.Id;
                      	//od.Armor_Product_Category__c
                      	//od.Armor_Product__c	
                      	//od.Armor_Anywhere_Location__c
                      	od.Opportunity_Source__c = 'Portal';
                      	od.Type = 'Downgrade';
                      	od.Amount = z.Zuora__MRR__c * -1;
                      	od.CurrencyIsoCode = z.CurrencyIsoCode;
                      	od.CloseDate = d1;
                      	od.StageName = 'Cancelled';
                      
                      downgradeOpps.add(od);
                      //End of Creating Downgrade Opp
                  } // End of GroupedResultDown For Loop
                  
                  insert downgradeOpps;
                  
              }
              Else If(z.Zuora__Status__c == 'Active'){
                  AggregateResult[] groupedResultsUp = [SELECT Zuora__Account__c , SUM(Zuora__MRR__C) FROM Zuora__Subscription__c WHERE ID IN: SubsCreated GROUP BY Zuora__Account__c];
                 //Create Upgrade Opp 
                 
                 List<Opportunity> upgradeOpps = new List<Opportunity>();
                  For(AggregateResult aru : groupedResultsUp){
                    
                        
                      Opportunity ou = new Opportunity();
                     	ou.RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AMP Upgrade').getRecordTypeId();
                      	ou.OwnerId = z.Zuora__Account__r.OwnerId;
                      	ou.Name = z.Zuora__Account__r.Name + ' - AMP';
                      	ou.AccountId = z.Zuora__Account__r.Id;
                      	//ou.Armor_Product_Category__c
                      	//ou.Armor_Product__c	
                      	//ou.Armor_Anywhere_Location__c
                      	ou.Opportunity_Source__c = 'Portal';
                      	ou.Type = 'Existing Business';
                      	ou.Amount = z.Zuora__MRR__c;
                      	ou.CurrencyIsoCode = z.CurrencyIsoCode;
                      	ou.CloseDate = d1;
                      	ou.StageName = 'Closed Won';
                      
                      upgradeOpps.add(ou);
                      //End of Creating Upgrade Opp

                  } // End of GroupedResultUp For Loop
                 
                 insert upgradeOpps;
              }
              
          } // End of SubsCreated For Loop
         
          
      } //End of CreateOpportunities Method
} // End Of Class

 
I have created a VF Page to replicate a form that we use, with an extension to when the command button is pressed on the VF page will attach the form to the record the button to pull up the VF page was caled from. 

I am now trying to test my test class and I am getting the following error message upon testing.  "Methods defined as TestMethod do not support getContent call"

Can anyone help re-write or give suggestions on how to get this test class to test out the controller extension? 

Appreciate any help!

Extension Code:
public class ArmorIncMDNAExtension {

    private final Contract__c contract;
    
    private ApexPages.StandardController standardController;
    
    public ArmorIncMDNAExtension(ApexPages.StandardController standardController) {
        this.Contract = (Contract__c)standardController.getRecord();
    }
    
    public pagereference GeneratePDF(){
pagereference Pg = Page.ArmorIncMDNA;
Blob pdf1 = pg.getcontentAsPdf();
Attachment d = new Attachment();
d.ParentId = contract.Id;
d.Body = Pdf1;
d.Name = contract.Account__r.Name + ' Armor Defense Inc. Mutual NDA.pdf';
d.ContentType = 'application/pdf';
insert d;
return null;
}
    
}

Test class Code:
@isTest
public class ArmorContractExtTest {

    
    
    static testMethod void tm1 () {

		Date myDate = Date.newInstance(2017, 8, 17);
        
        Contract__c c = new Contract__c();
        	c.Account__c = '001S000000rwY8H';
        c.Auto_Renew__c = 'No';
        c.Contract_Term_In_Months__c = 12;
        c.Effective_Date__c = myDate;
        c.Renewal_Period_Term_In_Months__c = 12;
        
        insert c;
         
        ArmorIncMDNAExtension ae = new ArmorIncMDNAExtension(new ApexPages.StandardController(c));
        ae.GeneratePDF();

    }
    
    
}

Hello all! 

I have a trigger which operates just fine for all scenarios (Insert, Update, Delet and undelete) but when i am attempting to create a test class for the trigger to test my first scenario I am getting a null pointer exception with the folllowing error: 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AcctSubMrrRollup: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.AcctSubMrrRollup: line 18, column 1: []

Please see my Trigger and test class below, can anyone advise what i may e doing incorrect as in theory my trigger should be doing things correctly and I am not sure why my Map is Null even after fulfillign the If statement criteria on not being null?

Please help...

Thanks for your time,

​Shawn

Trigger Code: 
trigger AcctSubMrrRollup on Zuora__SubscriptionProductCharge__c(after insert, after update, before delete, after unDelete) {
    List<Id> AccIds=new List<Id>();
    
If(Trigger.isInsert || Trigger.isUpdate || Trigger.isUnDelete) {
    for(Zuora__SubscriptionProductCharge__c mst:Trigger.New){
    if(mst.Zuora__Account__c !=null){
     AccIds.add(mst.Zuora__Account__c);
    }
    }
   

   Map<Id,Account> AccMap = new Map<Id,Account>([select id,Subscription_MRR__c from Account where id in:AccIds]);
   
   for(Zuora__SubscriptionProductCharge__c mst:Trigger.New)
   {
        if(!AccMap.IsEmpty())
        {
            AccMap.get(mst.Zuora__Account__c).Subscription_MRR__c = AccMap.get(mst.Zuora__Account__c).Subscription_MRR__c + mst.Zuora__MonthlyRecurringRevenue__c;
        }
   }

   if(!AccMap.IsEmpty())
   {
        update AccMap.values();
   }}
   
   If(Trigger.isDelete) {
    for(Zuora__SubscriptionProductCharge__c mst:Trigger.Old){
    if(mst.Zuora__Account__c !=null){
     AccIds.add(mst.Zuora__Account__c);
    }
    }
   

   Map<Id,Account> AccMap = new Map<Id,Account>([select id,Subscription_MRR__c from Account where id in:AccIds]);
   
   for(Zuora__SubscriptionProductCharge__c mst:Trigger.Old)
   {
        if(!AccMap.IsEmpty())
        {
            AccMap.get(mst.Zuora__Account__c).Subscription_MRR__c = AccMap.get(mst.Zuora__Account__c).Subscription_MRR__c - mst.Zuora__MonthlyRecurringRevenue__c;
        }
   }

   if(!AccMap.IsEmpty())
   {
        update AccMap.values();
   }}

}

Test Class Code:
@isTest
public class AcctSubMrrRollupTest {

    public static testMethod void tm1 (){
        
     Account a = new Account();
        a.Name = 'Test Account Rollup';
        
        insert a;
        
        System.debug('The Id for the newly created Account is ' + a.Id);
        
     Zuora__SubscriptionProductCharge__c z1 = new Zuora__SubscriptionProductCharge__c();
        z1.Name = 'Testing 1';
        z1.Zuora__Zuora_Id__c = '12345';
        z1.Zuora__MonthlyRecurringRevenue__c = 100;
        z1.Zuora__Account__c = a.Id;
        
        insert z1;
        
        System.debug('The ID for the newly created Sub Record is ' + z1.Id);
        
        System.assertEquals(100, a.Subscription_MRR__c);
        
    }
    
}

 
Hello all Awesome Developers!

I have a visualforce page using an extension that populates a lookup field and does a custom save to redirect to another Visualforce page. 

My stuggle is that I am newer to APEX coding and I do not know how to attempt a test class to make my extension class pass code coverage. 

Can anyone help please? 

Visualforce Page:
<apex:page standardController="Salesforce_Support_Survey__c" sidebar="false" showHeader="false" extensions="SalesforceSupportSurveyController" docType="html-5.0">
   
    <style>
    html, body, p { 
        font-family: "ProximaNovaSoft-Regular", Calibri, 
            "Gill Sans", "Gill Sans MT", Candara, Segoe, 
            "Segoe UI", Arial, sans-serif; 
        font-size: 110%;
    }
    input { font-size: 95%; }
	</style>
    
    <apex:form >
        <apex:pageBlock title="Thank you for taking our short survey!" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Submit Survey"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Survey Questions:" columns="2">
                <apex:outputField value="{!Salesforce_Support_Survey__c.X1_Timliness__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X1_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X2_Satisfaction__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X2_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X3_Submission_process__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X3_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X4_Enhancement_Ideas__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X4_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X5_Additional_Comments__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X5_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.Issue__c}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Extension Class that Test class is needed for:

public class SalesforceSupportSurveyController
{
   Salesforce_Support_Survey__c Issue {get;set;}

    //constructor
    public SalesforceSupportSurveyController(ApexPages.StandardController stdController){
        Issue = (Salesforce_Support_Survey__c)stdController.getRecord();
        Issue.Issue__c = ApexPages.currentPage().getParameters().get('lookupVal');
    }

    public PageReference save(){
        insert Issue;
        
        PageReference reRend = new PageReference('/apex/ThankYou');
        reRend.setRedirect(true);
        return reRend;
    }
}

Thank you all for your help in getting me past this, I really appreciate it,

Shawn
Hello awesome developers!

I am stuck here, and I will be up front I am prety new to the apex extension for VF pages.  

I am attempting to as a record is closed, send an email from a workflow with an url to a VF page for an user to fill out a brief survey.  I am attempting to place a parameter in the URL of the closing records ID to then pre populate the lookup field on the VF page with the ID of the closing record that is sending the survey needed email. 

I have the following VF page built and extension, however when the page is loaded, the lookup field on the VF page is not being populated.  Any ideas on what I did incorrectly and or ideas on how to make this work?  

I appreciate any input,

PS...once this is working, since I am new to the extension building, any insights on building a test class for the extension?

Shawn

VF Page:
 
<apex:page standardController="Salesforce_Support_Survey__c" sidebar="false" showHeader="false" extensions="SalesforceSupportSurveyController" docType="html-5.0">
   
    <style>
    html, body, p { 
        font-family: "ProximaNovaSoft-Regular", Calibri, 
            "Gill Sans", "Gill Sans MT", Candara, Segoe, 
            "Segoe UI", Arial, sans-serif; 
        font-size: 110%;
    }
    input { font-size: 95%; }
	</style>
    
    <apex:form >
        <apex:pageBlock title="Thank you for taking our short survey!" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Submit Survey"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Survey Questions:" columns="2">
                <apex:outputField value="{!Salesforce_Support_Survey__c.X1_Timliness__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X1_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X2_Satisfaction__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X2_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X3_Submission_process__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X3_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X4_Enhancement_Ideas__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X4_Answer__c}"/>
                <apex:outputField value="{!Salesforce_Support_Survey__c.X5_Additional_Comments__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.X5_Answer__c}"/>
                <apex:inputField value="{!Salesforce_Support_Survey__c.Issue__c}"/>
                 <script>
          			document.getElementById('{!$Component.dynFieldName}_lkid').value = '{!IssueId}';
          			document.getElementById('{!$Component.dynFieldName}').value = '{!IssueName}';
      			</script>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Extension:
 
public class SalesforceSupportSurveyController
{
    public string IssueId
    {    get;set;    }

    public string IssueName
    {    get;set;    }
    
    public SalesforceSupportSurveyController(ApexPages.StandardController ctlr)
    {
        IssueId = System.currentPageReference().getParameters().get('lookupVal');
        IssueName = [select Name from SFDC_Issue__c where Id =: IssueId].Name;
    }
}

 
Hello awesome developers.  I have the followign Visualforce Page and Extension Class that lists all Parent Account Contacts on any Child accounts for that Parent on the Child Acount Page Layout.  I can not figure out a Test lass for this one, I am used to doing test classes for actual triggers and I am assuming this is different as I have not done many VF pages in my life and could really use the guidence and help on this one to learn from.  Thank you in advance if you can help!

VF Page - 
 
<apex:page standardcontroller="Account" extensions="myController2" tabStyle="Account">
<apex:pageBlock >
<apex:pageblocksection title="Contacts" columns="1">
<apex:pageblocktable value="{!accounts}" var="cons1">
<apex:column headervalue="Name">
<apex:outputLink value="/{!cons1.id}">{!cons1.Name}</apex:outputLink>
</apex:column>
<apex:column value="{!cons1.Phone}"/>
<apex:column value="{!cons1.Email}"/>
</apex:pageblocktable>
</apex:pageblocksection>
</apex:pageBlock>
</apex:page>



Extension Class -  
 
public class myController2{

    public mycontroller2(ApexPages.StandardController controller) {

    }

    public list<contact> cons;
    public List<Contact> getAccounts() {
    Id recid=apexpages.currentpage().getparameters().get('id');  
    Account lesson=[select id,ParentId from Account where Id=:recid limit 1];
 
        cons=[select id,Phone,Email,Name from contact where Accountid=:lesson.ParentId];
        if(cons.size()>0){return cons;}    
        else{
        return null;
        }
     
      
    }

}

 
Hello, 

I am attempting some apex outside of the normal areas for me as I am new and stil learning. 

I am trying to when a child account is created for an existing account, clone the Contacts and then list them under the child account as well.  I know this isnt best practice, however it is what I am tasked with and the following is the code I currently have, although I am getting an error on line 29 and the error is - Illegal Assignment From Set to Id   Can anyone help me to get thsi working so that I can show in Sandbox and help to show the duplication and why this would be a bad idea?

Thanks,
 
trigger CopyAccountContactsToChild on Account (before insert) {

    Set<Account> AcctsToUpdate = new Set<Account>();
    List<Id> ParentAccounts = new List<Id>();
    List<Contact> ConsToSwap = new List<Contact>();
    
    
    For(Account A : Trigger.New){
        
        If(A.Parent_Account_Custom__c != null){
           
            AcctsToUpdate.add(A);   
        }   
    }
    
    For(Account A2 : AcctsToUpdate){
        ParentAccounts.add(A2.Parent_Account_Custom__c);
    }
    
    For(Id pAtoLookAt : ParentAccounts){
        List<Contact> consToGet = new List<Contact>([SELECT ID, AccountId FROM Contact WHERE AccountId =: pAtoLookAt]);
        
        For(Contact c3 : consToGet){
        ConsToSwap.add(c3);
        }
    }
    
    For(Contact AFinal : ConsToSwap){
        AFinal.AccountId = AcctsToUpdate;
    }   

}

 
I have a process that based on checkboxes on the Account object when the Account is created, it will create a child account for the Parent account being created.  This will usually be done during the lead conversion process where the Account gets created and based on the checkboxes selected on the lead the approprate Child Accounts will be created.  Now here is my question.....When the lead conversion is successful and the opportunity is created for the parent account, I would like a trigger to based on the two check boxes on the Parent account (Anywhere or Complete) to create an Opportunity using the same field data from the opp created by the lead conversion for each child account created with a small tweak to the name field and re-pointing the Account ID on the new child opps to point to thier correct Child account again base don the proper checkbox selected and the trigger process.   Can this happen?   If so, can you give me a head start as I woudl like to get this automated and I know we can do this, but I have no idea. 

Please be my saving hero!!!!

Thanks in advance,

Shawn
Hello Developers,

I have created a trigger that based on criteria on an Account record, will create child account records.  I then have some Process Builder processes checking a checkbox on the Parent account record when the children are created to hopefully run the trigger only once per child record.  The first child account record gets created and the process does what it needs to do just fine, but in my below trigger code, the second scenario of the "Complete" child record (The second if statement in the code) if both Anywhere and Complete checkboxes are selected when the parent Accoutn gets created,then I get two Child accounts for Complete.  This started after introducing the processes to only fire each scenario of the trigger once as the checkboxes on the parent record could be selected at different times.  I have spent many hours looign over this and can not figure out why two "Complete" child accounts are getting created only when both scenarios of my trigger have thier criteria met.   Can you please help me awesome Devs!!!!

Here is my trigger code...
 
trigger CreateChildAccount on Account (after insert, after update){

    String TriggerRan = 'False';
    String TriggerRanComplete = 'False';
    
    Id AcctRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Prospect').getRecordTypeId();
    List<Account> ChildAnywhere = new List<Account>();
    List<Account> ChildComplete = new List<Account>();
        
    For(Account a : Trigger.new){
        
        If(a.Armor_Anywhere__c == true && a.ChildTriggerRan__c != True && TriggerRan == 'False'){
          ChildAnywhere.add(new Account(name = a.Name + '_Anywhere',ParentId = a.Id,
          Parent_Account_Custom__c = a.Id,Additional_Partner_Application_Comments__c = a.Additional_Partner_Application_Comments__c,
          Application_Type__c = a.Application_Type__c,Cloud_Environment__c = a.Cloud_Environment__c,
          IS_Company_Category__c = a.IS_Company_Category__c,Channel__c = a.Channel__c,
          IS_Company_Facebook_Fans__c = a.IS_Company_Facebook_Fans__c,IS_Company_Facebook_Profile_URL__c = a.IS_Company_Facebook_Profile_URL__c,
          IS_Company_Summary__c = a.IS_Company_Summary__c,IS_Company_Twitter_Followers__c = a.IS_Company_Twitter_Followers__c,
          IS_Company_Twitter_Profile_URL__c = a.IS_Company_Twitter_Profile_URL__c,Original_Comments__c = a.Original_Comments__c,
          Primary_Customer_Size__c = a.Primary_Customer_Size__c,DBA_if_Applicable__c = a.DBA_if_applicable__c,
          IS_Estimated_Annual_Revenue__c = a.IS_Estimated_Annual_Revenue__c,IS_Estimated_Employees__c = a.IS_Estimated_Employees__c,
          IS_Estimated_Online_Ad_Budget__c = a.IS_Estimated_Online_Ad_Budget__c,IS_Estimated_PPC_Budget__c = a.IS_Estimated_PPC_Budget__c,
          IS_Founded_Year__c = a.IS_Founded_Year__c,How_Did_you_Hear_About_Armor__c = a.How_did_you_hear_about_Armor__c,
          IS_InboundScore__c = a.IS_InboundScore__c,Industry_Firehost__c = a.Industry_FireHost__c,
          Created_By_Conversion__c = a.Created_By_Conversion__c,Lead_Record_Type__c = a.Lead_Record_Type__c,
          Lead_Source__c = a.Lead_Source__c,IS_Company_LinkedIn_URL__c = a.IS_Company_LinkedIn_URL__c,
          IS_Location__c = a.IS_Location__c,My_Company_Size_Is__c = a.My_Company_Size_Is__c,
          NAICS_Code__c = a.NAICS_Code__c,Partner_Categories__c = a.Partner_Categories__c,
          Partner_Submitted__c = a.Partner_Submitted__c,Primary_Customer_Industries__c = a.Primary_Customer_Industries__c,
          Original_Interests__c = a.original_interests__c,Referral_Id__c = a.Referral_ID__c,
          ReferralId__c = a.ReferralId__c,Referrer_Code__c = a.Referrer_Code__c,
          Referring_Partner__c = a.Referring_Partner__c,Relationship_Entity__c = a.Relationship_Entity__c,
          X5_Largest_Customers__c = a.X5_Largest_Customers__c,Company_Size__c = a.Company_Size__c,
          Company_Success_Story__c = a.Company_Success_Story__c,Customer_Count__c = a.Customer_Count__c,
          Customers_Placed_at_a_Hosting_Company__c = a.Customers_Placed_at_a_Hosting_Company__c,Level_of_Engagement__c = a.Level_of_Engagement__c,
          Past_Partnerships__c = a.Past_Partnerships__c,Primary_Services__c = a.Primary_Services__c,
          Target_Market__c = a.Target_Market__c,Target_Market_Size__c = a.Target_Market_Size__c,
          Solution_Competencies__c = a.Solution_Competencies__c,Source_Territory__c = a.Source_Territory__c,
          Submitting_Partner_User__c = a.Submitting_Partner_User__c,mkto_custom_UTM_Campaign__c = a.mkto_custom_UTM_Campaign__c,
          mkto_custom_UTM_Medium__c = a.mkto_custom_UTM_Medium__c,mkto_custom_UTM_Source__c = a.mkto_custom_UTM_Source__c,
          IS_Website_Traffic_Rank__c = a.IS_Website_Traffic_Rank__c,RecordTypeId = AcctRecordTypeId,ChildTriggerRan__c = True));
          TriggerRan = 'True';
        }
        
        If(a.Armor_Complete__c == true && a.ChildTriggerRanComplete__c != True && TriggerRanComplete == 'False'){
          ChildComplete.add(new Account(name = a.Name + '_Complete',ParentId = a.Id,
          Parent_Account_Custom__c = a.Id,Additional_Partner_Application_Comments__c = a.Additional_Partner_Application_Comments__c,
          Application_Type__c = a.Application_Type__c,Cloud_Environment__c = a.Cloud_Environment__c,
          IS_Company_Category__c = a.IS_Company_Category__c,Channel__c = a.Channel__c,
          IS_Company_Facebook_Fans__c = a.IS_Company_Facebook_Fans__c,IS_Company_Facebook_Profile_URL__c = a.IS_Company_Facebook_Profile_URL__c,
          IS_Company_Summary__c = a.IS_Company_Summary__c,IS_Company_Twitter_Followers__c = a.IS_Company_Twitter_Followers__c,
          IS_Company_Twitter_Profile_URL__c = a.IS_Company_Twitter_Profile_URL__c,Original_Comments__c = a.Original_Comments__c,
          Primary_Customer_Size__c = a.Primary_Customer_Size__c,DBA_if_Applicable__c = a.DBA_if_applicable__c,
          IS_Estimated_Annual_Revenue__c = a.IS_Estimated_Annual_Revenue__c,IS_Estimated_Employees__c = a.IS_Estimated_Employees__c,
          IS_Estimated_Online_Ad_Budget__c = a.IS_Estimated_Online_Ad_Budget__c,IS_Estimated_PPC_Budget__c = a.IS_Estimated_PPC_Budget__c,
          IS_Founded_Year__c = a.IS_Founded_Year__c,How_Did_you_Hear_About_Armor__c = a.How_did_you_hear_about_Armor__c,
          IS_InboundScore__c = a.IS_InboundScore__c,Industry_Firehost__c = a.Industry_FireHost__c,
          Created_By_Conversion__c = a.Created_By_Conversion__c,Lead_Record_Type__c = a.Lead_Record_Type__c,
          Lead_Source__c = a.Lead_Source__c,IS_Company_LinkedIn_URL__c = a.IS_Company_LinkedIn_URL__c,
          IS_Location__c = a.IS_Location__c,My_Company_Size_Is__c = a.My_Company_Size_Is__c,
          NAICS_Code__c = a.NAICS_Code__c,Partner_Categories__c = a.Partner_Categories__c,
          Partner_Submitted__c = a.Partner_Submitted__c,Primary_Customer_Industries__c = a.Primary_Customer_Industries__c,
          Original_Interests__c = a.original_interests__c,Referral_Id__c = a.Referral_ID__c,
          ReferralId__c = a.ReferralId__c,Referrer_Code__c = a.Referrer_Code__c,
          Referring_Partner__c = a.Referring_Partner__c,Relationship_Entity__c = a.Relationship_Entity__c,
          X5_Largest_Customers__c = a.X5_Largest_Customers__c,Company_Size__c = a.Company_Size__c,
          Company_Success_Story__c = a.Company_Success_Story__c,Customer_Count__c = a.Customer_Count__c,
          Customers_Placed_at_a_Hosting_Company__c = a.Customers_Placed_at_a_Hosting_Company__c,Level_of_Engagement__c = a.Level_of_Engagement__c,
          Past_Partnerships__c = a.Past_Partnerships__c,Primary_Services__c = a.Primary_Services__c,
          Target_Market__c = a.Target_Market__c,Target_Market_Size__c = a.Target_Market_Size__c,
          Solution_Competencies__c = a.Solution_Competencies__c,Source_Territory__c = a.Source_Territory__c,
          Submitting_Partner_User__c = a.Submitting_Partner_User__c,mkto_custom_UTM_Campaign__c = a.mkto_custom_UTM_Campaign__c,
          mkto_custom_UTM_Medium__c = a.mkto_custom_UTM_Medium__c,mkto_custom_UTM_Source__c = a.mkto_custom_UTM_Source__c,
          IS_Website_Traffic_Rank__c = a.IS_Website_Traffic_Rank__c,RecordTypeId = AcctRecordTypeId,ChildTriggerRanComplete__c = True));
          TriggerRanComplete = 'True';
        }
        
    }
	
    If(ChildAnywhere.size()>0){
    insert ChildAnywhere;
    }
    
    If(ChildComplete.Size()>0){
    insert ChildComplete;  
    }
    
}

Here is a snapshot of each Process to supposedly stop the trigger form firing again on subsequent updates to the parent account record...

For Anywhere Scenario...
Criteria - 

User-added image
Record Update Action - 

User-added image

Complete Criteria - 

User-added image

Complete Record Update Action - 

User-added image

Both process pretty much have the same criteria and actions...

Criteria...On Account object when record created / For Anywhere process the criteria is lookign for ChildTriggerRan checkbox firld to be true AND Parent ID Lookup field not being NULL / For Complete it is looking for ChildTriggerRunComplete checkbox to be true AND Parent Id Lookup field not NULL

Then Record Update Action is  / For Anywhere - Update the Parent Record ID populated only if the ChildTriggerRan field is currently false  and update that field to True / For Complete it will update the Parent Record ID populated only if the ChildTriggerRanComplete field is currently false and update that field to True. 





Thnak you for your time, I hope some one can help me as I am stumped on this one!!!

Shawn
Hello awesome devs! 

Need some help here as I am at a loss why the following Trigger is not setting values on all records but it setting a value on some of the records when doing a mass insert r or update.  When you go to a single record and perform an update the trigger always fires correctly.  

What is trying to be achieved:  

When a record on Object A is created or updated and it includes a SKU in a field called SKU__c .
Then trigger is called on Object A to find a Product from our standard Product2 object that have the same value in the ProductCode field as the SKU__c fiel don Object A.  
When found, a field (Product_Line__c) on Object A should be populated with the value form the found Product2 record and its Product_Line__c field. 

Again this works when updating records one by one, but anythign in mass, will only update a few records.  (Latest example: out of 1097 records in a mass update, only roughly 40 records got updated, the rest have nothign populated in the Product_Line__c field on Object A.

Can anyone look over my code, and help me out? :)

Thank you so much all,

Shawn

Trigger Code:
 
trigger PopulateProductLineOnCharge on Zuora__SubscriptionProductCharge__c (before insert, before update) {

    
    List<Zuora__SubscriptionProductCharge__c> spcToUpdate = new List<Zuora__SubscriptionProductCharge__c>();
    String pLineText = '';
    String SkuText = '';
    Product2 P;
    
    
    For(Zuora__SubscriptionProductCharge__c s : Trigger.new){
        If(s.Product_Line__c == null && s.SKU__c != null){
            SkuText = s.SKU__c;
        }
    }
    
    If(SkuText != null){
    P = [SELECT Id, Product_Line__c, ProductCode FROM Product2 WHERE ProductCode = : SkuText LIMIT 1];
    
    For(Zuora__SubscriptionProductCharge__c s2 : Trigger.New){
        If(SkuText.contains(s2.SKU__c)){
            s2.Product_Line__c = p.Product_Line__c;
            spcToUpdate.add(s2);
        }
        }
    }
 
}

 
Hello awesome devs!

I am attempting to create a VF page with 4 fields for user inputting.  2 of these fields are Date fields which when filled in like MM/DD/YYY when I press the search button to call my custom controller the date in the field populated has its format changed to Tue Dec 26 00:00:00 GMT 2017 and doesnt seem to be being applied in the search itself as all records are returned and not ones just for the date entered. 

Can someone help me with gettign the format to stay as I think this is the cause of the date field not being used in the search criteria. 

Please see my VF Page and controller code below. 

Thank you very much for any help you can provide,

Shawn

VF Page Code - 
 
<apex:page controller="SubSearchController">
    
    <apex:form>
    	<apex:pageBlock id="pb">
        	<apex:pageBlockButtons>
                <apex:commandButton action="{!searchRecords}" value="Search" rerender="pb"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="2">
                <apex:outputLabel value="Account Id" />
                <apex:inputText value="{!AccId}"/>
                <apex:outputLabel value="Status" />
                <apex:inputText value="{!SubStatus}"/>
                <apex:outputLabel value="Service Activation date" />
                <apex:inputText value="{!SAD}"/>
                <apex:outputLabel value="Term End Date" />
                <apex:inputText value="{!TermEnd}"/>
            </apex:pageBlockSection>
            <apex:pageBlockTable var="record" value="{!records}" id="pbTable">
                <apex:column value="{!record.Name}" />
                <apex:column value="{!record.Zuora__Status__c}" />
                <apex:column value="{!record.Zuora__ServiceActivationDate__c}" />
                <apex:column value="{!record.Zuora__TermEndDate__c}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
    
</apex:page>

Controller Code -

public class SubSearchController {

    public String AccId {get;set;}
    public String SubStatus {get;set;}
    public Date SAD {get;set;}
    public Date sadDate = Date.valueOf(SAD);
    public Date TermEnd {get;set;}
    public Date TermDate = Date.valueOf(TermEnd);
    
    public List<Zuora__Subscription__c> records {get; private set;}
    
    public SubSearchController(){
        records = new List<Zuora__Subscription__c>();   
    }
    
    public PageReference searchRecords() {
        
        records = [SELECT Zuora__Account__c, Zuora__Status__c, Zuora__ServiceActivationDate__c, Zuora__TermEndDate__c, OpportunityId__c, Total_Booking_Amount__c, Id, Name
                  FROM Zuora__Subscription__c WHERE Zuora__Account__c = : AccId AND Zuora__Status__c = : SubStatus AND (Zuora__ServiceActivationDate__c = : sadDate OR Zuora__TermEndDate__c = :TermDate)];
        return null;
        
    }
    
}

 
1) Make two DateTime fields on contact object.

LastTaskCreatedTime

LastEmailSentTime


2) Whenever a task is created on Contact LastTaskCreatedTime field should be updated.


3) Whenever you send an email LastEmailSentTime field should be updated.

4) Make trigger as bulk / Test class


Ans me on-Amuraghav14@gmail.com
What workflow rule do I run to populate a currency field with the value from another currency field on the same object (opp page)? 

Tried using TEXT () and VALUE () but kept getting errors.
As the Administrator, I am able to view the page, but when a user to whom I've granted permission attempts to access the same page, the user receives the following error:
 
An internal server error has occurred
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience. 

Thank you again for your patience and assistance. And thanks for using salesforce.com! 

Error ID: 1322486646-119233 (-2068884021)
Hello!

I need to have cases created every month and at certain times of the month (ex: day 1, day 15), to notify a department that they need to retrieve/review billing invoices.  I thought I could do this using the Process Builder, but I do not have an option to start a process from a date.  Is there another way.  I have not been able to find any answers/solutions.

Thank you!

BB  :)
I have a lookup relationship between Object A and Object B . “A” is the parent to “B”.

When a record from “A” gets deleted, the related field value in record “B” is removed. What I want do is remove the field value of a different lookup field value on “B” once the field value between “A” and “B” is deleted.

When a field value is removed on the child, due to the parent record being deleted does this count as an update to the record? If so, I believe it should be possible to update this through visual workflow, process builder or workflow rules, but have not been able to get this to work.

I have also tried using a formula field checkbox. When checkbox = TRUE on record B, run the workflow rule, visual flow, or process builder, but have been unsuccessful.

Is this possible through visual workflows, process builder, or workflow rules?
 
There is a custom object Designation which have 3 fields :
Employee_Designation (text) ,
Account_Name(look up to account),
Contact_Name(look up to contact)
I want to do  a duplicate check so that value in all the 3 field should be different.
Eg : Suppose there is an existing record in Designation
  Employee_Designation=Test Lead and Account_Name=Universal containers and Conatct_Name=Daniel Philz
i dont want any new or updated record to have same values in all 3 fields
If i go for duplicate management rule ,then the matching rule wont allow 2 look up fields.
How it can be done?
 
Hi All,

I'm a new admin and do not have any developer experience, so any help would be greatly appreciated!

I've added new tasks to an existing apex class button and it works perfectly in my sandbox instance but when I validate the change in production before deployment I received the following error code:

System.AssertException: Assertion Failed 
Stack Trace: Class.TestCreateOnboardingTasks.verifyTasksCreated: line 51, column 1

This is line 45-59 in my apex class:

Task t = new Task();
        t.WhatId = accountID;
        t.WhoId = champion.Id;
        t.Subject = 'Onboarding: Day 7';
        t.ActivityDate = a.Subscription_Start_Date__c.addDays(7);
        t.OwnerId = a.OwnerId;
        insert t;
        
        t = new Task();
        t.WhatId = accountID;
        t.WhoId = champion.Id;
        t.Subject = 'Onboarding: Day 15';
        t.ActivityDate = a.Subscription_Start_Date__c.addDays(15);
        t.OwnerId = a.OwnerId;
        insert t;

Any ideas on what to do for it to pass the validation test?
Hello friends
stucked in this question
1.Set the case target resolution date for accounts that have basic support level to 30 days from today.
plz help me in completing this workflow with steps.i dont know codding.
 
I am trying to update some accounts in the anonymous window and get the Too many DML rows error message. What am I doing wrong? 
 
​List<Account> acc = new List<Account>();

for(Account a:[SELECT Id, Industry from Account WHERE Industry='Architect']){
    
    a.Industry='Architecture';
    acc.add(a);
}

update acc;

Yogesh
Thisis the error I am getting when trying to convert a lead. No reason, just this error. I have checked required fields and mappings and everything seems to check out. I have checked that record type is not Master for the profile. There are no validations or process builders or workflows or flows causing the problem. These are all web-to-lead with the same lead source and what we call lead source detail.

This should be simple. I am trying to convert a lead to an existing account, not creating an oppty. So, basically I am creating a new contact on the Account.
User-added image

Was not sure where to categorize this, let me know if you have a better place for it.

shannon
 
Hi I am trying to figure out to how trigger works for updating checkbox on Case object when checkboxfield of other custom object is set to true ,Lets say I have a custom field Required__c on Destination object and I have a Criteria__c  field on Case object, whenever required__c is true I want to update the criteria__c on case object to true , can anyone please guide me on this 

Thanks in advance
  • November 03, 2017
  • Like
  • 0
Hi everyone,

First time poster, long time reader :)

I would like to have a date/time field updated in a lead record whenever an email is sent to the lead; Sometimes we send emails from within the platform, but sometimes from our gmail account directly (we use Salesforce Inbox for automatic activity capture).

Is this possible? How would one go about creating such a trigger?