• cambart14
  • NEWBIE
  • 80 Points
  • Member since 2012

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 18
    Replies

Hi Experts,

I am trying to get the below trigger to work for multiple attachments (users may attached 2 or 3 files to the Special_Product_Request__c object).  If there is more than one attachment, this trigger will fail (even with small files).  Your assistance is much appreciated!

trigger EmailAttachments on Special_Product_Request__c (after insert, after update) {

for(Special_Product_Request__c spr : trigger.new){
    if (spr.Engineering_Group__c == 'ASI' && spr.SPR_Stage__c == '2 - Marketing Review' && (spr.SPR_Stage__c != Trigger.oldMap.get(spr.Id).SPR_Stage__c)) {
       Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
       spr = [SELECT id, Opportunity.Name, Product_Managerlookup__c.Email, Opportunity.Owner.Name, Opportunity.Account.Name FROM Special_Product_Request__c WHERE Id = :spr.Id];                    

        // create email content
        String Name = spr.Opportunity.Name; 
        String OwnerName = spr.Opportunity.Owner.Name;
        String Account = spr.Opportunity.Account.Name;
        String subject = 'Special Product Request Attachments - '+Name;
        email.setSubject(subject);
        
        List<Messaging.EmailFileAttachment> attachmentList = new List<Messaging.EmailFileAttachment>();

        String line1 = 'Please see attached for special product request files related to opportunity: '+Name+'.  \r\n';
        String line2 = 'Opportunity Owner: '+OwnerName+'.  \r\n';
        String line3 = 'Account Name: '+Account+'.  \r\n';
        String body = line1 + line2 + line3; 
        email.setPlainTextBody(body);

		String ProductManager = spr.Product_Managerlookup__c.Email;
        email.setToAddresses(new String[]{ProductManager});

            // fetch attachments for Special_Product_Request__c
            Attachment att = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : spr.id];

   // List of attachments handler
   Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

   {
     // Create the email attachment
     efa.setFileName(att.Name);
     efa.setBody(att.body);
     efa.setContentType(att.ContentType);
     efa.setInline(false);
	 attachmentList.add(efa);
    
   }

    // Attach files to email instance
    email.setFileAttachments(attachmentList);
    Messaging.sendEmail(new Messaging.singleEmailMessage[] {email});
    }

 }  
}

Thanks,
cambart14
 
I have a custom Visualforce page that is used to create an interactive report for our sales teams.  Once a sales rep clicks on custom tab, it brings them to the Visualforce page, which in turn calls the Apex class.  The Apex class queries the rep's opportunities and puts them into a list.  The Visualforce page uses that list and some CSS and Javascript to render an interactive report for the rep.

My question is how would I get code coverage for the Apex class as it is not triggered by a record and does not have a DML statement?  It simply calls a list of records in a list and displays it to the user.
I am trying to figure out how to translate a list of Close Dates in the respective Fiscal Quarters.  We have custom fiscal years enabled in the org.

The code below is completely functional, except line 13.  How do convert the Close Dates to Fiscal Quarters.

Thanks!
 
public string getData()
  {    List<PivotData> PivotDataList=new List<PivotData>();
   List<OpportunityLineItem> OppList=[Select Opportunity.Account.Name,Opportunity.StageName,Opportunity.CloseDate,
   Opportunity.Amount,Opportunity.RecordTypeID,CurrencyISOCode,Expected_Total_Price__c,Opportunity.IsClosed, Quantity,
   Opportunity.Name,PriceBookEntry.Product2.Name,Opportunity.Probability,PriceBookEntry.Product2.Description from OpportunityLineItem 
   WHERE Opportunity.OwnerID =: UserInfo.getUserId() AND Opportunity.IsClosed = FALSE ];
       for(OpportunityLineItem o :OppList)
       {
           PivotData p=new PivotData();
           p.AccountName=o.Opportunity.Account.Name;
           p.StageName=o.Opportunity.StageName;
           p.Year=string.valueof(o.Opportunity.CloseDate.Year());
           p.Quarter=string.valueof(o.Opportunity.CloseDate.FiscalQuarter());
           p.CurrencyCode=o.Opportunity.CurrencyISOCode;
           p.ExpectedTotalPrice=o.Expected_Total_Price__c;
           p.OpportunityName=o.Opportunity.Name;
           p.ItemNumber=o.PriceBookEntry.Product2.Name;
           p.Probability=o.Opportunity.Probability;
           p.ItemDescription=o.PriceBookEntry.Product2.Description;
           p.Quantity=o.Quantity;
           
           PivotDataList.add(p);
           
       }
       getPivot='visibility: visible';
       exportPdf=false;
       return JSON.serialize(PivotDataList);
  }

 
We have a product specification form (Product_Brief__c) that once saves needs to insert a Project.  Once that Project is inserted, I need to take the Project ID and update the Product Brief with that ID.

The code below works properly to create a Project.  When I try and use that Project ID to update the Product Brief (last two lines of code) it gives me this error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY.

Any help here would be much appreciated!
trigger ProjectCreation on Product_Brief__c (after insert, after update) {

    Product_Brief__c pb = [SELECT ID, Opportunity__r.ID, Opportunity__r.Owner.ID, Select_Product__c, Related_Project__c FROM Product_Brief__c WHERE ID =: trigger.new];
    
    Project__c p = new Project__c();
    p.RecordTypeID = '012W00000008nXT';
    p.Related_Opportunity__c = pb.Opportunity__r.ID;
    p.Sales_Rep__c = pb.Opportunity__r.Owner.ID;
    p.Project_Description__c = pb.Select_Product__c;
    p.Project_Category__c = 'Bags and Tubing Sets';
	p.Status__c = 'Active';
    p.Start_Date_and_Time__c = System.Now();
    
    insert p;
    
    pb.Related_Project__c = p.ID;
    
    update pb;
}
Below is our code to find the account ID for inserted child records that have a unique identify (R12 Customer Number).  This works great if the R12 Customer Number is a unique match, but we are now consolidating accounts in SFDC and this may contain a string of customer numbers on the account level (example, R12 Customer Number = 'GEN12412;GEN12342;GEN12542' rather than R12 Customer Number = 'GEN12412').

I am trying to figure out how a child record being inserted with the R12 Customer Number = 'GEN12412' can find the right account ID if on the account the R12 Customer Number = 'GEN12412;GEN12342;GEN12542'.  The child record needs to trigger a contains search, but I am not certian how that would look in an Apex Trigger.

 
trigger UpdateCPInvoiceHeaderId on Customer_Order_Header__c (before insert) {
    //get the R12 Customer Numbers and store it in a set.
    set<String> acct = new set<String>();
    set<String> acct2 = new set<String>();
    for(Customer_Order_Header__c i: trigger.new){
        if(i.R12_Customer_Number__c != null){
        acct.add(i.R12_Customer_Number__c);
        }
        }
    
    //query the account records and get the associated IDs 
    map<string, Account> acctMap = new map<string, Account>();
    for(Account a:[SELECT Id, R12_Customer_Number__c FROM Account WHERE R12_Customer_Number__c IN: acct]){
        acctMap.put(a.R12_Customer_Number__c,a);
        }
    
    //update the account value based on the R12 Customer Number in the record    
    for(Customer_Order_Header__c i:trigger.new){
        if(i.R12_Customer_Number__c !=null && acctMap.containsKey(i.R12_Customer_Number__c)){
            i.Account__c=acctMap.get(i.R12_Customer_Number__c).Id;
        }
        
    }
    
}

 
Hello!  We have a custom object (Invoice__c)  that is the child in a master-detail relationship with Accounts.  Accounts have a unique number system housed in the SGN_Number__c field that is also on the invoice information that we get from our ERP system.  When we insert invoices into Salesforce.com we do not want to manually map each invoice to the correct account (using the SGN Number) in Excel, but would rather have an Apex trigger automatically find the right accound and populate the account ID into the Invoice__c lookup field (Account__c). 

I have written the below trigger, but cannot seem to get it to work.

trigger updateInvoiceAccount on Oracle_Sales_History__c (before insert) {

    //get the SGNs and store it in a set.
    set<String> accountSGN = new set<String>();
    for(Invoice__c i: trigger.new){
            accountSGN.add(i.SGN_Number__c);
    }

    //query the account records and get the associated ids.
    map<string, Account> accountMap = new map<string, Account>([SELECT Id from Account where Id IN: accountSGN]);

    //update the account value based on the SGN in the record.
    for(Invoice__c i: trigger.new){
            i.Account__c = accountMap.get(i.SGN_Number__c).Id;    
    }

}

Thanks,
cambart14

We want to be able to send a simple email notificaiton when ever a member is added to an Opportunity Team, that gives a link.  Below is the working trigger we have in the sandbox, but I need help writing a APEX Test Class that will cover atleast 75% of the code before I can deploy it.  The trigger works perfectly, but any help on how to write a test class would be appreciated.

 

trigger EmailTeamMember on OpportunityTeamMember (after insert) {

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    for (OpportunityTeamMember o : trigger.new) { 
    String[] showID = new String[] {o.UserID};
    List<User> u = [SELECT Id, Name, Email, BID_Billing_Burden__c FROM User WHERE Id in :showID];
    String[] toAddresses = new String[] {u[0].email};
    String[] oppID = new String[] {o.OpportunityID};
    
    if (o.User_Office__c=='LOG')
    {
    mail.setToAddresses(toAddresses);
    mail.setReplyTo ('noreply@salesforce.com');
    mail.setSenderDisplayname('Salesforce Support');
    mail.setSubject('Added to an Opportunity Team ');
    mail.setUseSignature(false);
    mail.setPlainTextBody('You have been added to an Opportunity Team ');
    mail.setHtmlBody('You have been added to an Opportunity Team:<b><p><p/> '+ 
     'To view that opportunity <a href=https://na3.salesforce.com/'+o.OpportunityID+'>click here.</a>');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
    }
}

 Thanks again!

We have the below APEX trigger written in our sandbox, but need to deploy it into production.  The issue is we don't have any code coverage, and I am new to APEX programming.

 

Any help on creating a text class to cover 75% of this code would be much appreciated.

 

	trigger ownerCopy on Account (before Insert, before Update) {

    // handle arbitrary number of opps
    for(Account x : Trigger.New){

        // check that owner is a user (not a queue)
        if( ((String)x.OwnerId).substring(0,3) == '005' ){
            x.Owner_Copy__c = x.OwnerId;
        }
        else{
            // in case of Queue we clear out our copy field
            x.Owner_Copy__c = null;
        }
    }

}

 Thanks again for your time and input!

With the Winter '13 release of Salesforce, they have added native trigger support for Opportunity Teams (previously Selling Teams).  We would like to have our users notified when they are added to a Opportunity Team.  I have written the code below.

 

trigger EmailTeamMember2 on OpportunityTeamMember (after insert) {

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    for (OpportunityTeamMember o : trigger.new) { 
    String[] toAddresses = new String[] {o.User.email};

    mail.setToAddresses(toAddresses);
    mail.setReplyTo ('support@acme.com');
    mail.setSenderDisplayname('Salesforce Support');
    mail.setSubject('Added to an Opportunity Team : ');
    mail.setUseSignature(false);
    mail.setPlainTextBody('You have been added to the Opportunity Team of: ' + o.Opportunity);
    mail.setHtmlBody('You have been added to the Opportunity Team of:<b> '+ o.Opportunity+');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

 It saves without any errors, but when I try to add a team member this error appears:

 

Apex trigger EmailTeamMember2 caused an unexpected exception, contact your administrator: EmailTeamMember2: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : null: []: Trigger.EmailTeamMember2: line 16, column 1  

 

Thanks for your help in advance!!! :)

With the Winter '13 release of Salesforce, they have added native trigger support for Opportunity Teams (previously Selling Teams).  We would like to have our users notified when they are added to a Opportunity Team.  I have written the code below.

 

trigger EmailTeamMember2 on OpportunityTeamMember (after insert) {

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    for (OpportunityTeamMember o : trigger.new) { 
    String[] toAddresses = new String[] {o.User.email};

    mail.setToAddresses(toAddresses);
    mail.setReplyTo ('support@acme.com');
    mail.setSenderDisplayname('Salesforce Support');
    mail.setSubject('Added to an Opportunity Team : ');
    mail.setUseSignature(false);
    mail.setPlainTextBody('You have been added to the Opportunity Team of: ' + o.Opportunity);
    mail.setHtmlBody('You have been added to the Opportunity Team of:<b> '+ o.Opportunity+');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

 It saves without any errors, but when I try to add a team member this error appears:

 

Apex trigger EmailTeamMember2 caused an unexpected exception, contact your administrator: EmailTeamMember2: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : null: []: Trigger.EmailTeamMember2: line 16, column 1  

 

Thanks for your help in advance!!! :)

I have created a custom object (Product_Brief__c) , that is related to a specific opportunity.  With the Product_Brief__c there are stages (Stage_c) that can be selected from a drop down list. My Opportunity has a custom checkbox field (Submit_to_New_Products__c).

 

I need when the stage = "Needs Corrections/ Clarifications" that my custom checkbox field (Submit_to_New_Products__c) to be unchecked.

 

The code I have written is below, but it is not updating the related Opportunity.

 

trigger uncheckSubmitPB on Product_Brief__c (after insert, after update) {

    Set<ID> oppIds = new Set<ID>();   
    for(Product_Brief__c PB : Trigger.new)
    
    if(PB.Stage__c=='Needs Corrections/ Clarification')
    {
    oppIds.add(PB.Opportunity__r.id);
    }
    List<Opportunity> UpdateOpp = [SELECT ID, Submit_to_New_Products__c  FROM Opportunity WHERE Opportunity.id IN : oppIds];
    for(Opportunity ol: UpdateOpp)
    {ol.Submit_to_New_Products__c=false;}
    update UpdateOpp;

    
}

 

 Thanks for your help!

On some of our Opportunites we can have multiple 'active' projects that we would like change the status to 'complete' when its opportunity is marked as 'Won' or 'Lost'.  I have looked at doing this through the Workflow, but it does not seem robust enought to accomplish this.  Would I be able to accomplish this through a trigger?  If not, any other suggestions are welcome.  Thanks for your help!

I have a custom Visualforce page that is used to create an interactive report for our sales teams.  Once a sales rep clicks on custom tab, it brings them to the Visualforce page, which in turn calls the Apex class.  The Apex class queries the rep's opportunities and puts them into a list.  The Visualforce page uses that list and some CSS and Javascript to render an interactive report for the rep.

My question is how would I get code coverage for the Apex class as it is not triggered by a record and does not have a DML statement?  It simply calls a list of records in a list and displays it to the user.
I am trying to figure out how to translate a list of Close Dates in the respective Fiscal Quarters.  We have custom fiscal years enabled in the org.

The code below is completely functional, except line 13.  How do convert the Close Dates to Fiscal Quarters.

Thanks!
 
public string getData()
  {    List<PivotData> PivotDataList=new List<PivotData>();
   List<OpportunityLineItem> OppList=[Select Opportunity.Account.Name,Opportunity.StageName,Opportunity.CloseDate,
   Opportunity.Amount,Opportunity.RecordTypeID,CurrencyISOCode,Expected_Total_Price__c,Opportunity.IsClosed, Quantity,
   Opportunity.Name,PriceBookEntry.Product2.Name,Opportunity.Probability,PriceBookEntry.Product2.Description from OpportunityLineItem 
   WHERE Opportunity.OwnerID =: UserInfo.getUserId() AND Opportunity.IsClosed = FALSE ];
       for(OpportunityLineItem o :OppList)
       {
           PivotData p=new PivotData();
           p.AccountName=o.Opportunity.Account.Name;
           p.StageName=o.Opportunity.StageName;
           p.Year=string.valueof(o.Opportunity.CloseDate.Year());
           p.Quarter=string.valueof(o.Opportunity.CloseDate.FiscalQuarter());
           p.CurrencyCode=o.Opportunity.CurrencyISOCode;
           p.ExpectedTotalPrice=o.Expected_Total_Price__c;
           p.OpportunityName=o.Opportunity.Name;
           p.ItemNumber=o.PriceBookEntry.Product2.Name;
           p.Probability=o.Opportunity.Probability;
           p.ItemDescription=o.PriceBookEntry.Product2.Description;
           p.Quantity=o.Quantity;
           
           PivotDataList.add(p);
           
       }
       getPivot='visibility: visible';
       exportPdf=false;
       return JSON.serialize(PivotDataList);
  }

 
We have a product specification form (Product_Brief__c) that once saves needs to insert a Project.  Once that Project is inserted, I need to take the Project ID and update the Product Brief with that ID.

The code below works properly to create a Project.  When I try and use that Project ID to update the Product Brief (last two lines of code) it gives me this error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY.

Any help here would be much appreciated!
trigger ProjectCreation on Product_Brief__c (after insert, after update) {

    Product_Brief__c pb = [SELECT ID, Opportunity__r.ID, Opportunity__r.Owner.ID, Select_Product__c, Related_Project__c FROM Product_Brief__c WHERE ID =: trigger.new];
    
    Project__c p = new Project__c();
    p.RecordTypeID = '012W00000008nXT';
    p.Related_Opportunity__c = pb.Opportunity__r.ID;
    p.Sales_Rep__c = pb.Opportunity__r.Owner.ID;
    p.Project_Description__c = pb.Select_Product__c;
    p.Project_Category__c = 'Bags and Tubing Sets';
	p.Status__c = 'Active';
    p.Start_Date_and_Time__c = System.Now();
    
    insert p;
    
    pb.Related_Project__c = p.ID;
    
    update pb;
}
Below is our code to find the account ID for inserted child records that have a unique identify (R12 Customer Number).  This works great if the R12 Customer Number is a unique match, but we are now consolidating accounts in SFDC and this may contain a string of customer numbers on the account level (example, R12 Customer Number = 'GEN12412;GEN12342;GEN12542' rather than R12 Customer Number = 'GEN12412').

I am trying to figure out how a child record being inserted with the R12 Customer Number = 'GEN12412' can find the right account ID if on the account the R12 Customer Number = 'GEN12412;GEN12342;GEN12542'.  The child record needs to trigger a contains search, but I am not certian how that would look in an Apex Trigger.

 
trigger UpdateCPInvoiceHeaderId on Customer_Order_Header__c (before insert) {
    //get the R12 Customer Numbers and store it in a set.
    set<String> acct = new set<String>();
    set<String> acct2 = new set<String>();
    for(Customer_Order_Header__c i: trigger.new){
        if(i.R12_Customer_Number__c != null){
        acct.add(i.R12_Customer_Number__c);
        }
        }
    
    //query the account records and get the associated IDs 
    map<string, Account> acctMap = new map<string, Account>();
    for(Account a:[SELECT Id, R12_Customer_Number__c FROM Account WHERE R12_Customer_Number__c IN: acct]){
        acctMap.put(a.R12_Customer_Number__c,a);
        }
    
    //update the account value based on the R12 Customer Number in the record    
    for(Customer_Order_Header__c i:trigger.new){
        if(i.R12_Customer_Number__c !=null && acctMap.containsKey(i.R12_Customer_Number__c)){
            i.Account__c=acctMap.get(i.R12_Customer_Number__c).Id;
        }
        
    }
    
}

 
Hello!  We have a custom object (Invoice__c)  that is the child in a master-detail relationship with Accounts.  Accounts have a unique number system housed in the SGN_Number__c field that is also on the invoice information that we get from our ERP system.  When we insert invoices into Salesforce.com we do not want to manually map each invoice to the correct account (using the SGN Number) in Excel, but would rather have an Apex trigger automatically find the right accound and populate the account ID into the Invoice__c lookup field (Account__c). 

I have written the below trigger, but cannot seem to get it to work.

trigger updateInvoiceAccount on Oracle_Sales_History__c (before insert) {

    //get the SGNs and store it in a set.
    set<String> accountSGN = new set<String>();
    for(Invoice__c i: trigger.new){
            accountSGN.add(i.SGN_Number__c);
    }

    //query the account records and get the associated ids.
    map<string, Account> accountMap = new map<string, Account>([SELECT Id from Account where Id IN: accountSGN]);

    //update the account value based on the SGN in the record.
    for(Invoice__c i: trigger.new){
            i.Account__c = accountMap.get(i.SGN_Number__c).Id;    
    }

}

Thanks,
cambart14

We have the below APEX trigger written in our sandbox, but need to deploy it into production.  The issue is we don't have any code coverage, and I am new to APEX programming.

 

Any help on creating a text class to cover 75% of this code would be much appreciated.

 

	trigger ownerCopy on Account (before Insert, before Update) {

    // handle arbitrary number of opps
    for(Account x : Trigger.New){

        // check that owner is a user (not a queue)
        if( ((String)x.OwnerId).substring(0,3) == '005' ){
            x.Owner_Copy__c = x.OwnerId;
        }
        else{
            // in case of Queue we clear out our copy field
            x.Owner_Copy__c = null;
        }
    }

}

 Thanks again for your time and input!

With the Winter '13 release of Salesforce, they have added native trigger support for Opportunity Teams (previously Selling Teams).  We would like to have our users notified when they are added to a Opportunity Team.  I have written the code below.

 

trigger EmailTeamMember2 on OpportunityTeamMember (after insert) {

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    for (OpportunityTeamMember o : trigger.new) { 
    String[] toAddresses = new String[] {o.User.email};

    mail.setToAddresses(toAddresses);
    mail.setReplyTo ('support@acme.com');
    mail.setSenderDisplayname('Salesforce Support');
    mail.setSubject('Added to an Opportunity Team : ');
    mail.setUseSignature(false);
    mail.setPlainTextBody('You have been added to the Opportunity Team of: ' + o.Opportunity);
    mail.setHtmlBody('You have been added to the Opportunity Team of:<b> '+ o.Opportunity+');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

 It saves without any errors, but when I try to add a team member this error appears:

 

Apex trigger EmailTeamMember2 caused an unexpected exception, contact your administrator: EmailTeamMember2: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : null: []: Trigger.EmailTeamMember2: line 16, column 1  

 

Thanks for your help in advance!!! :)

On some of our Opportunites we can have multiple 'active' projects that we would like change the status to 'complete' when its opportunity is marked as 'Won' or 'Lost'.  I have looked at doing this through the Workflow, but it does not seem robust enought to accomplish this.  Would I be able to accomplish this through a trigger?  If not, any other suggestions are welcome.  Thanks for your help!