• mjohnson-TIC
  • NEWBIE
  • 497 Points
  • Member since 2011
  • Software Developer
  • TIC Gums

  • Chatter
    Feed
  • 14
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 110
    Replies
Hi, I've got a lead trigger bulkification issue.  The following piece of code throws a too many soql queries error when more than 200 leads are inserted:
 
if(Trigger.isInsert || Trigger.isUpdate){  
        
            if(HelperClass.firstRun2){
                
            HelperClass.firstRun2=false;          
        
            for(Lead l1: trigger.new){               
                if((UserInfo.getUserId() == Label.MarketoIntegrationUser || UserInfo.getUserId() == Label.WebsiteIntegrationUser) &&
                   (l1.RecordTypeId == leadRecordTypeId) && (l1.Country == 'United States' || 
                   l1.Country == 'United States of America' ||
                   l1.Country == 'USA' ||
                   l1.Country == 'U.S.' ||
                   l1.Country == 'U.S.A'
                   ) ){     
               
                    Set<String> postalCodes = new Set<String>();

                    for( Lead l : trigger.new ) {
                            if(l.PostalCode != null && l.PostalCode.length() >=5)
                                try{                          
                                    String zipStringx = l.PostalCode.substring(0,5);
                                    postalCodes.add( zipStringx );  
                                   // postalCodes.add( l.PostalCode );     
                                } catch(DMLException e){
                                     ApexPages.addMessages(e);
                                     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
                                     String[] toAddresses = new String[] {'sfdc-admins@pingidentity.com'};
                                     mail.setToAddresses(toAddresses);
                                     mail.setReplyTo('sfdc-admins@pingidentity.com');
                                     mail.setSenderDisplayName('Apex error message');
                                     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
                                     mail.setPlainTextBody(e.getMessage());
                                     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                                
                                }        
                                                                                         
                    }

                    Map<String, Zip_State_Table__c > validZips = new Map<String, Zip_State_Table__c >();

                    for( Zip_State_Table__c obj : [SELECT  Id, 
                                        Name,
                                        ZipCode__c,
                                        Territory__c                                            
                                        FROM Zip_State_Table__c 
                                            WHERE ZipCode__c IN :postalCodes] ) {
                        validZips.put( obj.ZipCode__c, obj );
                    }

                    for( Lead l : trigger.new ) {
                        if( l.PostalCode != null && l.PostalCode.length() >=5 ) { 
                            if( validZips.containsKey(l.PostalCode.substring(0,5)) ) { 
                                l.State = validZips.get(l.PostalCode.substring(0,5)).Name;
                                l.RegionTerritoryHidden__c = validZips.get(l.PostalCode.substring(0,5)).Territory__c;
                            } else {}

                        } 
                    }
                }
                }
            }
        }

I know the error in the above code is with this part of the code:  
 
for( Zip_State_Table__c obj : [SELECT  Id, 
                                        Name,
                                        ZipCode__c,
                                        Territory__c                                            
                                        FROM Zip_State_Table__c 
                                            WHERE ZipCode__c IN :postalCodes] ) {
                        validZips.put( obj.ZipCode__c, obj );
                    }


I'm unable to re-write that code to avoid the error.  Does anyone see how I can re-write that code with the soql query for loop to avoid the too many soql queries error?  Thanks 
 
Hi!  I outsourced a request that was over my head, but there's an issue we didn't consider that our partner wants to charge a lot to fix.  I'd like to do it myself, but they're recommending against it.  Can someone help me understand if their reason makes sense?  
 
We use Cases as Product RMAs.  Each RMA Case has at least one custom object Return Line Item (RLI) related to it.  The RLI contains the product information (part number, quantity sold, qty returning, qty received, etc).  Our problem was that large customers would only return part of the product they requested an RMA for.  Because RMA cases had to be processed in full, credit would be delayed and inventory would be incorrect.  We asked our vendor to create a process that would create a second case for anything that had been returned and update the original case to show only what was pending return.

So for example:
Original Case
Line 1 has qty 3 expected and nothing has been received
Line 2 has qty 2 expected and 1 has been received
Line 3 has qty 4 expected and 4 have been received
 
Press Button.
 
Line 1 for qty 3 stays on the original case
Line 2 for qty 1 stays on the original case
 
Line 2 for qty 1 moves to the cloned case
Line 3 for qty 4 moves to the cloned case
  
Our issue is that from the example above Line 3 still exists on the original case and the qty expected is now 0.  It’s causing confusion in our process and I want to delete that RLI from the original case.  I created the following code to do so, but when I asked the opinion of the person who created the original process he said “There is the issue of doing DML in a trigger, and doing a query in a for loop is never a good idea, especially with how many transactions your trigger structure currently processes.”  What does he mean?  Is it really a concern since only one case would be updated at a time?
 
trigger DeleteZeroQtyReturn on Return_Line_Item__c (after update) {

List<Id> lstId = new List<Id>();
 
for(Return_Line_Item__c RLI: Trigger.old){
        List<Return_Line_Item__c> existRLIList = [Select Id from Return_Line_Item__c where QTY_Returned__c = 0 and Split_with_Button__c=true];
        delete existRLIList;
    }

}

 
Hi Everyone,

This is probably a pretty easy answer, but I'm just drawig a blank.  The code snippet below is designed to clone an Opportunity.  The RecClone class is set up to pull in all createable fields for the clone, since the clone function that Apex offers only pulls those fields that you specifically name.  The clone works fine, but I want to overwrite some of the clone fields with other values.  How do I pull the values from Line 3 and replace them with the values from lines 4 - 10?
 
String soql = RecClone.getCreatableFieldsSOQL('Opportunity','Id =: OppId');
                    Opportunity opp = (Opportunity)Database.query(soql);
                    Opportunity opp2 = opp.clone(false, true);
                        opp2.CloseDate = opp.Renewal_Date_Next__c;
                        opp2.OwnerId = amh.Assigned_Account_Manager__c;
                        opp2.Term__c = 12;
                        opp2.Renewal__c = 'Yes';
                        opp2.Effective_Date__c = opp.Renewal_Date_Next__c;
                        opp2.Renewed_Opportunity__c = opp.Id;
                        Opp2.StageName = 'Call Scheduled';

                insert opp2;

 
I need a formula that calculates how many days are in the current month.

I've been using this: DAY(DATE(YEAR(TODAY()),MONTH(TODAY())+1,1)-1)
till now but it's starting to give me an error: #Error!

HELP!
I am trying to pull attachments from a parent object onto the approval email alert (as links) when the child object is submitted for approval.  I am able to pull all the fields from the parent object onto the VF template; but for some reason attachments will not work and i receive the following error message:  Error: Aggregate Relationship is used in an unsupported complex expression containing 'OBJECTA__r.attachments'. 

Beginning of template:
<messaging:emailTemplate subject="CDR Approval Request - {!RelatedTo.PARENT__r.Account__r.Name}" recipientType="User" relatedToType="CHILD__c">
<messaging:htmlEmailBody >

Section pertaining to attachments:
<apex:repeat value="{!relatedTo.PARENT__r.Attachments}" var="a"> 
 <p><a href="https://CS15.salesforce.com/{!URLFOR($Action.Attachment.Download, a.name)}">{!a.Name}</a> ({!a.BodyLength} B)</p>
</apex:repeat>

I believe referencing 'PARENT__r' is the problem, but I do not know how else to reference that the attachments need to pull from the parent object (not child as it will have none)?

Do I need to create a controller to pull the parent object attachments and then reference that controller in the email template??

Please help!
 
To start...I'm not developer...so this is probably a silly question but...we've recently gone through a migration to a new SFDC org and I have a bit of code originally written 8 years ago and the test class that was written for it simply won't work.  But I don't know enough about writing test code to have the foggiest idea why! :(

It's a crucial part of our current billing process...so any help would be greatly appreciated!
/*
Description:
 Automatically email customer their invoice once it’s been approved.
 
Functional Logic (API names in brackets[]):
 Whenever a case is updated and the Send Invoice [Send_Invoice__c] flag is true
 send an email to the case contact [ContactId] including the case attachment as 
 an email attachment if and only if there is one and only one attachment of a size less than 5 MB attached to the case.
 
Updates:
12/14/09 - Send a user friendly error email to the case owner if invoice fails to get sent
02/14/08 - Reset send_invoice__c flag if email fails

*/
@isTest
private class InvoiceMailerTest {

  // ensure no errors occur when sending a invoice correctly and that
  // send invoice flag remains checked
    static testMethod void testInvoiceMailer() {
    
    // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // add one attachment to simulate adding an invoice
    Attachment testAttachment = getTestAttachment(testCase);
    insert testAttachment;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is still checked as any errors will uncheck it
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == true, 
      'The invoice mailer appears to be failing when a case has a valid contact and attachment.');
    
    }
    
    // ensure no exceptions are thrown if case has no contact id
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorNoContactId() {
      // create test case and zero out contact id field
      Case testCase = getTestCase();
      testCase.contactId = null;
      insert testCase;
      
      // add one attachment to simulate adding an invoice
    Attachment testAttachment = getTestAttachment(testCase);
    insert testAttachment;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as no contact id should generate an
    // error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case had no associated contact.');  
    }
    
    // ensure no exceptions are thrown if case has no attachments
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorNoAttachment() {
      // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // don't add any attachments
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as a case with no attachments
    // should generate an error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case had no associated attachment');
    }
    
    // ensure no exceptions are thrown if case has more than one attachment
    // and that the send invoice flag is reset
    static testMethod void testInvoiceMailerErrorTooManyAttachments() {
      // create test case
    Case testCase = getTestCase();
    insert testCase;
    
    // add multiple attachments
    Attachment testAttachment1 = getTestAttachment(testCase);
    insert testAttachment1;
    Attachment testAttachment2 = getTestAttachment(testCase);
    insert testAttachment2;
    
    // mimic invoice approval process by checking send invoice
    System.Test.startTest();
    testCase.Send_Invoice__c = true;
    update testCase;
    System.Test.stopTest();
    
    // assert that send invoice is not checked as a case with more than one attachment
    // should generate an error email and uncheck the send invoice flag
    testCase = [select send_invoice__c from Case where id = :testCase.id];
    system.assert(testCase.send_invoice__c == false, 
      'The invoice mailer appears to have succeeded even though the test case has more than one associated attachment');
    }
    
    // create a generic case related to a contact with a non-null email
    private static Case getTestCase() {
      Contact testContact = new Contact(lastName = 'Test', email = 'test@mailinator.com');
      insert testContact;
      
      Case testCase = new Case(contactId = testContact.id);
      return testCase;
    }
    
    // create a generic attachment related to a given case
    private static Attachment getTestAttachment(Case parentCase) {
      Blob attachmentContent = Blob.valueOf('Hello World!');
      Attachment testAttachment = 
        new Attachment(parentId = parentCase.id,
                 name = 'Invoice.pdf',
                 body = attachmentContent);
      return testAttachment;
    }
}


 
Hello,

Can someboby please help me with the steps and approach, how to confugre the Monthly and weekly calendars in the same field? something like toggle where user should be able to select which calender he wants to use.

Please suggetions!!.
Hi all,

I'm very new to Apex, but am convinced this scenario is possible. Problem is I can't find any examples anywhere, which surprises me.

I have a text field on Account called 'Originating_Lead__c' containing the 18 char ID of a Lead.

On the Lead is a lookup to Account.

I want to insert the ID of the Account record into the Account lookup field on the Lead record that corresponds to the ID held in the Originating_Lead__c field on Account.

I'm know I can't do this declaratively as it's "going down the tree", but I'm surprised this issue hasn't crept up before on here - have trawled right through and haven't found anything. Does anybody know of any examples of similar triggers for similar problems? 

Have browsed and used this community extensively but never posted a question - never needed to!

Thanks in advance.
Michael
Hi,
   I deployed my code on production and I can see that from he logs that my apex class is getting called from my visualforce page, but not a single debug statement is getting printed. It works fine in sandbox enviornment but on production its not printing anything. I have run this code on production before and it used to work fine. but suddenly it stopped working.

Anyone faced same issue before ?

Thanks,
Abhishek 
Hello,
I'm just an admin, not a dev (yet). I would like to create a roll up field at the opportunity taht will be the summ of the product meeting a certain criteria. When I create a rollup summary field at the opportunity level, I can filter the criterias, but not the one I am interested in: Product Name.
How can I filter the product name in this field?
Many thanks!

I would like to send the 'name' field in the Lead Object to an external API. However only the 'FirstName' and 'LastName' are available.

Can I edit the WSDL file that is created with the outbound message and change 'FirstName' to 'name' then save it?

Hi All -

We are looking to implement SAML SSO for our Salesforce instance. From what I've gleaned, it's best practice to set up a custom domain when doing this (we are currently using the generic domain). We are also somewhat concerned about our API integrations once we go live and enforce SAML logins - how does this affect those logins and integrations?

If anyone can comment on some of these, I would be most appreciative.