• Kevin Chiles 930
  • NEWBIE
  • 85 Points
  • Member since 2014
  • Sr. Salesforce System Admin
  • Megapath

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 20
    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
 
Hello!
I am trying to convert a button from Java script to a lighting component but am having no luck.  I am hoping for some pointers that could help me get this going.  I was hoping this would be much easier that is has turned out to be 
 
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}

var ___spinner_id = '___spinner';
 
function showSimpleSpinner() {
   
  if (document.getElementById(___spinner_id)==null) {
    var _spinnerHtml = '<div id="' + ___spinner_id + '" style="width:100%; height:100%; z-index:1001; width:100%; height:100%; top: 0px; left:0px; position:fixed;">' +
                         '<div style="background-color:#333; opacity:0.4; width:100%; height:100%; "></div>' +
                         '<div style="display:block; position: fixed;background-image:url(/img/loading32.gif); top: 50%; left:50%; margin-left:-16px; margin-top: -16px;width: 32px; height:32px;"/>' +
                       '</div>';
    var _tmp = document.createElement('div');
    _tmp.innerHTML = _spinnerHtml;
    document.body.appendChild(_tmp.firstChild);
  }
   
  document.getElementById(___spinner_id).style.display = 'block';
}
 
function hideSimpleSpinner() {
  document.getElementById(___spinner_id).style.display = 'none';
}

showSimpleSpinner();

try{
if ( {!Opportunity.IsClosed} ) {
alert('Can not change Purchase Path if Opportunity is closed');
hideSimpleSpinner();
} else {
sforce.apex.execute("trac_OpportunityHelper","rebuildPurchasePath",{oppId:'{! Opportunity.Id }'});
window.location.href = window.location.href;
}
}catch(e){
alert(e);
hideSimpleSpinner();
}

 
Hello!

I have an Email trigger that seems to be firing twice.  I cannot for the life of me figure out why.  Basically the trigger is picking up a template and a the attachments associated to a custom objects record and emailing it to a team.  This for some reason is firing 2 emails instead of one.  Its driving me mad!
 
trigger Send_TechDocs_Cloud on Sales_Handoff_Activity__c (after update) {



for(Sales_Handoff_Activity__c SHA : trigger.new){
    if (SHA.TAD_Status__c == 'TAD Complete' && SHA.Cloud__c==True && Trigger.oldMap.get(Sha.Id).TAD_Status__c != Trigger.newMap.get( Sha.Id ).TAD_Status__c ) {
   // && SHA.TAD_Status__c!=Trigger.oldMap.get(sha.id).TAD_Status__c
   
    //Retrieve Email template
     EmailTemplate et=[Select id from EmailTemplate where name=:'Cloud Tad Complete'];
     
     
    //Create email list
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

       //Create attachment list
       List<Messaging.EmailFileAttachment> efalist = new List<Messaging.EmailFileAttachment>();
       
       contact c =[select id, email from Contact where Email=:'kevin.chiles@megapath.com' limit 1];
       //Create message
       
       Messaging.SingleEmailMessage singlemail = new Messaging.SingleEmailMessage();
        //add template
       singleMail.setTemplateId(et.Id);              
        //set target object for merge fields
        singleMail.setTargetObjectId(c.Id);
        singlemail.setwhatId(SHA.Id);       
        //set to save as activity or not
        singleMail.setSaveAsActivity(false);
         
         
        //add address's that you are sending the email to
        String []ToAddress= new string[] {'ash@megapath.com' }; 

        //set addresses
        singlemail.setToAddresses(toAddress);
        
        
            //add mail
                emails.add(singleMail);
        
        {
Help me Obi Wan, you're my only hope

Chiles
    
Hello!

I am trying to update a Campaign Member from a lead when a lead interaction occures.  The code works, but the code is not covered by the class for some odd reason.  Can anyone let me know what may be the issue?  I am only seeing 55 percent coverage with the items after the if statements not being covered: IE Lines 16-17  and 23-25
 
trigger UpdateLeadForTrial on CampaignMember (after insert,after update) {

for (CampaignMember cm: Trigger.New){


//Collect associated lead
List<Lead> led =[select Id, In_trial__c from Lead where Id =:cm.LeadId];

For( Lead l: Led){

//Logic for when to fire
if (l.In_Trial__c ==False && CM.Status=='Package Sent'){


//Updating value for In Trial field on Lead
l.In_Trial__c=True;
Update led;
}

//Running criteria for lead that is expired uncheck the In Trial field
if (l.In_Trial__c ==True && CM.Status=='Trial Complete'){

l.In_Trial__c=False;

Update led;
}}


}}

Test Class
@isTest(seeAllData=true)

private class testClass_UpdateLastModifiedDate
{
    public static testmethod void method1()
            {
        
        Lead l= new Lead(RecordTypeid=[select id,name,SobjectType from RecordType where Name ='SMB' and SobjectType='Lead'].id, Company='Test',LastName='test',
        leadsource='web',In_Trial__c=false,email='test@test.com',Install_Phone__c='999-999-9999',Status='0-Lead',OwnerId=[select id,LastName from User where Lastname='Sync' limit 1].id);
        insert l;
        
        task t2 =new Task(OwnerId=l.OwnerId,WhoId=l.Id,Subject='Call',Description='test',Status='In Progress');
        insert t2;
        
        Account Ac = new Account(MegaPath_Department__c='Channel',OwnerId=[select id,LastName from User where LastName='Sync' limit 1].id,
        Name='testAccountName11',Type='Customer');
        insert Ac;
        
        Contact c= new Contact(AccountId=ac.id, LastName='Chiles',LeadSource='Chat');
        Insert c;
        
        Opportunity Opp =New Opportunity(OwnerId=Ac.OwnerId,Name='test',AccountId=Ac.Id,StageName='Prospecting',CloseDate=system.today(),ContactForRole__c=c.Id,Number_of_Sites__c='5',
        LeadSource='360 Communications - T1',NextStep='test',Install_Street__c='test',Install_State__c='CA',Install_City__c='test',Install_Zip__c='94582',
        Install_Phone__c='3157775695');
        Insert Opp;
        
        Task t3 = new Task(  OwnerId=opp.OwnerId,WhoId=c.Id,Description='test', WhatId=opp.ID, Subject='Call',Status='In Progress');
        insert t3;        
        
        Task t1 = new Task(  OwnerId=ac.OwnerId,WhoId=c.Id,Description='test', WhatId=Ac.ID, Subject='Call',Status='In Progress');
        insert t1;
        //Task t2 = [Select Status,ID from Task where ID =:t1.ID];
       // insert t2;
        
        t1.Status='Completed';
        Update t1;
        
          Campaign cp=new Campaign(Name='MP1 Free Trial',IsActive=TRUE,Free_Trial_Campaign__c=TRUE);
        Insert cp;
        
         CampaignMember cm= New CampaignMember(CampaignId=Cp.Id,LeadId=l.Id,Status='Request');
        Insert cm;
       {
       
        
        CM.Status='Package Sent';
        Update CM;
        
        //l.In_Trial__c=True;
        //Update L;
        
        CM.Status='Trial Complete';
        Update CM;
        
        
        }
        l.Status='X - Lost/Nurture';
        l.Lead_Disposition__c='Lost To Competitor';
        update l;
        }
    }

 
Hello!

Below is complete code with test class for sending an Email from a custom object with all of the related attachments upon a variable on the object being set:
 
trigger Send_TechDocs on Sales_Handoff_Activity__c (before update) {



for(Sales_Handoff_Activity__c SHA : trigger.new){
    if (SHA.Tech_Doc_Status__c == 'Completed') {
    
    //Retrieve Email template
     EmailTemplate et=[Select id from EmailTemplate where name=:'Tech Doc Complete Full'];
     
     
    //Create email list
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

       //Create attachment list
       List<Messaging.EmailFileAttachment> efalist = new List<Messaging.EmailFileAttachment>();
       
       contact c =[select id, email from Contact where Email=:'Salesops@megapath.com' limit 1];
       //Create message
       
       Messaging.SingleEmailMessage singlemail = new Messaging.SingleEmailMessage();
        //add template
       singleMail.setTemplateId(et.Id);              
        //set target object for merge fields
        singleMail.setTargetObjectId(c.Id);
        singlemail.setwhatId(SHA.Id);       
        //set to save as activity or not
        singleMail.setSaveAsActivity(false);
         
         
        //add address's that you are sending the email to
        String []ToAddress= new string[] {'SSS1@Megapath.com','megapath.highcap@megapath.com' }; 

        //set addresses
        singlemail.setToAddresses(toAddress);
        
        
            //add mail
                emails.add(singleMail);
        
        {
           
                      

            // fetch attachments for Object
                     
            List<Attachment> allatt = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id];                     
         
         // Attachment att = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id limit 1];

           for(Attachment att : allatt) {
            // List of attachments handler
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

   {
      // try{

        

//Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(att.Name);

efa.setBody(att.Body);

efa.setContentType(att.ContentType);

efaList.add( efa );

  
    
   }

    // Attach files to email instance
   // singlemail.setFileAttachments(attachmentList);
   
  {
    singlemail.setFileAttachments(efaList);
   }
   }
    //send the message
     Messaging.sendEmail(emails);
          }

 }  
}
}

Test Class:
 
@isTest
private class EngineerNotesCreateTest
{
    static testMethod void EngineerNotesCreate()
    {
    
    Account acc=New Account(Name='test');
    insert acc;
    
     Contact ct=New Contact(FirstName='sarah',LastName='jenny',email='Salesops@megapath.com',AccountId=acc.id);
        insert ct;
      
     Opportunity opp= New Opportunity (Name='Test',Closedate=date.today(),NextStep='test',StageName='1 – Solution Design',Sales_Engineer__c='Joel Thomas',
     LeadSource='Call - Service Transfer',Type='Change Voice Services',Channel__c='SMB',    
        Install_Street__c='Test',
        Install_Zip__c='94582',
        Install_State__c='CA', 
        Install_City__c='Test',
        Install_Phone__c='3157775695',
        Install_Country__c='USA');
        Insert opp;
     
Booking_Checklist__c  bc= New Booking_Checklist__c(   
Active_Date__c=date.Today(),
Adjusted_Revenue__c=100,
Adjusted_Revenue_Reason__c='Product Line Adjustment',
Affiliate_Name_Matches__c='Yes',
Approval_Status__c='Approved',
Booked_Deal_More_Than_75_Locations__c='Yes',
Booking_Checklist_Record_Owner__c='Joy Cortez',
Checklist_Notes__c='test',
Child_or_Parent_Account_Correct__c='Yes',
Contracted_items_match_products__c='Yes',
Contracted_pricing_match_product_Pricing__c='Yes',
Contract_Signed_by_Valid_Date_Shown__c='Yes',
Correct_Shipping_Address__c='Yes',
Disposition__c='Construction Cost',
Does_Circuit_Speed_Qualify_W_Carrier__c='Yes',
Enrolled_Date__c=system.Today(),
Existing_Cust_Is_the_org_RMR_Reflected__c='Yes',
Existing_Customer__c='No',
Flowed_with_Layer_2_circuit__c='Yes',
Have_residential_services_been_ordered__c='No',
Incorrect_Missing_LCON_Information__c='No',
Is_the_contract_legible__c='Yes',
Is_this_an_out_of_contract_Move_order__c='No',
Is_this_an_R14_to_R17_voice_migration__c='No',
Is_this_a_Sylantro_or_Duet_migration__c='No',
LAN_set_up_missing__c='Yes',
Location_sold_as_new_within_6_months__c='No',
Missing_IP_Blocks__c='No',
Missing_Supp_Address_Information__c='No',
New_customer_booked_by_CAS_Dept__c='No',
NRR_Included_in_Quote__c='No',
Opportunity__c=opp.id,
Order_booked_previously_at_same_location__c='No',
Order_Stage__c='Enrolled',
Partner_splits_Partner_being_tagged__c='No',
Pre_Install_Cancelled_Date__c=system.today(),
Quote_Linked_to_Opportunity_b2b_ID__c='Yes',
Quote_Ordered_Status__c='Data Ready for Review',
Reason_Code__c='Awaiting FOC',
Agent_Matches_Named_Acct_Ent_SMB_HO_Mang__c='Yes',
SCR_Approval_completed_prior_to_booking__c='Yes',
Signed_Contract_Attached_To_Opp__c='Yes',
Signed_contract_has_additional_Writting__c='Yes',
Signed_contract_uploaded_into_MPQT__c='Yes',

Voice_Cloud_MPLS_Orders_SHA_Completed__c='Yes');

insert bc;

     
     
     
        
        Sales_Handoff_Activity__c Sha= new Sales_Handoff_Activity__c(
        Number_of_Seats_Trunks__c='5',
        Primary_Contact_Time_Zone__c='West',
        Opportunity_Name_2__c=opp.id,
        Customer_Contact_Name__c='Kevin Chiles',
        Customer_Contact_Email__c='kchiles2@gmail.com',
        Customer_Contact_Phone__c='0000000000',
        Quote_ID__c='255555.2',
        Expedite_Hand_Off_Date__c= date.today(),
        
        VPM_Notes__c='test notes',
        Assigned_VPM__c='Alex Stewart'
        
        );
        insert Sha;
        Attachment attach=new Attachment();  
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.body=bodyBlob;
        attach.parentId=sha.id;
        insert attach;
        
        sha.tech_doc_status__c='Completed';
        
        update Sha;
    }
}

This works like a dream, enjoy!
Hello!

I am having an error where I do not have enough coverage on my trigger to deploy.  My code covers the whole trigger except the crucial record type update.  Any help is greatly appreciated!

Trigger:
trigger PartnerContractRecordtype on Case (before update) {

for (Case c : Trigger.New) {
 
Partner_Contract__c pc =[Select Id ,RecordTypeId from Partner_Contract__c where id=:c.Partner_Contract__c limit 1];

RecordType rt = [select id from Recordtype where SobjectType='Partner_Contract__c' and Name =:'Approval'];

if (c.Status =='Partner - Pending Paperwork' && c.Partner_Contract__c!=Null){



pc.RecordtypeId=rt.id;

update pc;
}
}
}

Class:

@isTest(SeeAllData = true)
public class PartnerContractTrigger
{
    public static testMethod void PartnerContractTrigger()
    {
    
    Account a = New Account(Name='test',recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Account' and isActive=true and Name='Affiliate'].id);
        
        insert a;
        
        Contact ct=New Contact(FirstName='sarah',LastName='jenny',email='test@test.com',AccountId=a.id);
    insert ct;
        
        Account mpdefault = New Account(Name='Megapath - Default',recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Account' and isActive=true and Name='Affiliate'].id);
        
        Contact ct2=New Contact(FirstName='sarah',LastName='jenny',email='test@test.com',AccountId=mpdefault.id);
        insert ct2;
        
        Insert mpdefault;
        
        Partner_Contract__c pc = New Partner_Contract__c(Name='0',Parent_Partner__c=mpdefault.id,Status__c='Active',
        PartnerProgram__c='Referral',Partner__c=a.Id,recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Partner_Contract__c' and isActive=true and Name='Non Approval'].id
        );
        Insert pc; 
        
        Availiable_Contract__c ac = New Availiable_Contract__c(Name='0',Contract_Rank__c=1,Partner__c=a.Id,Partner_Contract__c=pc.Id 
        );
                   
        Insert ac;       
        
        RecordType recordtypeId2=[Select Name, Id From RecordType
        Where sObjectType='Partner_Contract__c' and isActive=true and Name='Approval'];
        
        Case C= new Case(AccountId=a.id,ContactId=ct.Id,Sales_Rep__c=UserInfo.getUserId(),Case_Request_Type__c='Partner Onboarding',
        recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Case' and isActive=true and Name='Channel Support'].id,Partner_Contract__c=pc.id,Company_Name__c=a.Name,
        Clarity_Account_ID__c='N/A',Site_Contact__c='Test', Site_Contact_Phone__c='3157775695',Primary_Affiliate__c='Megapath - Default',
        Primary_Affiliate_ID_2__c='1980',Subject='Onboarding Request for New Partner',Description='Onboarding Request for New Partner');
        
        insert c;
                     
        c.Status='Pending Partner Paperwork';
        update c;
        
        
          
        Pc.Name='1234';
        pc.Status__c='Active';
        Pc.Partner_Contract_Status__c='Partner Activated';
       // pc.recordtypeId=[Select Name, Id From RecordType
       // Where sObjectType='Partner_Contract__c' and isActive=true and Name='Approval'].id;
        update pc;  




    }
}
 
Hello!

I have a trigger that is updating a record type to a child object.  I have a test class built but it is only covering 66 percent of the trigger, can anyone help me to get this coverage up?  Trigger and class below
trigger PartnerContractRecordtype on Case (before update) {

for (Case c : Trigger.New) {
 
Partner_Contract__c pc =[Select Id ,RecordTypeId from Partner_Contract__c where id=:c.Partner_Contract__c limit 1];
//this line is not covered in the class 
RecordType rt = [select id from Recordtype where SobjectType='Partner_Contract__c' and Name =:'Approval'];

if (c.Status =='Partner - Pending Paperwork' && c.Partner_Contract__c!=Null){



pc.RecordtypeId=rt.id;

update pc;
}
}
}
 
@isTest(SeeAllData = true)
public class PartnerContractTrigger
{
    public static testMethod void PartnerContractTrigger()
    {
    
    Account a = New Account(Name='test',recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Account' and isActive=true and Name='Affiliate'].id);
        
        insert a;
        
        Contact ct=New Contact(FirstName='sarah',LastName='jenny',email='test@test.com',AccountId=a.id);
    insert ct;
        
        Account mpdefault = New Account(Name='Megapath - Default',recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Account' and isActive=true and Name='Affiliate'].id);
        
        Contact ct2=New Contact(FirstName='sarah',LastName='jenny',email='test@test.com',AccountId=mpdefault.id);
        insert ct2;
        
        Insert mpdefault;
        
        Partner_Contract__c pc = New Partner_Contract__c(Name='0',Parent_Partner__c=mpdefault.id,Status__c='Active',
        PartnerProgram__c='Referral',Partner__c=a.Id,recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Partner_Contract__c' and isActive=true and Name='Non Approval'].id
        );
        Insert pc; 
        
        Availiable_Contract__c ac = New Availiable_Contract__c(Name='0',Contract_Rank__c=1,Partner__c=a.Id,Partner_Contract__c=pc.Id 
        );
                   
        Insert ac;       
        
        RecordType recordtypeId2=[Select Name, Id From RecordType
        Where sObjectType='Partner_Contract__c' and isActive=true and Name='Approval'];
        
        Case C= new Case(AccountId=a.id,ContactId=ct.Id,Sales_Rep__c=UserInfo.getUserId(),Case_Request_Type__c='Partner Onboarding',
        recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Case' and isActive=true and Name='Channel Support'].id,Partner_Contract__c=pc.id,Company_Name__c=a.Name,
        Clarity_Account_ID__c='N/A',Site_Contact__c='Test', Site_Contact_Phone__c='3157775695',Primary_Affiliate__c='Megapath - Default',
        Primary_Affiliate_ID_2__c='1980',Subject='Onboarding Request for New Partner',Description='Onboarding Request for New Partner');
        
        insert c;
                     
        c.Status='Pending Partner Paperwork';
        update c;
        
        
          
        Pc.Name='1234';
        pc.Status__c='Active';
        Pc.Partner_Contract_Status__c='Partner Activated';
       // pc.recordtypeId=[Select Name, Id From RecordType
       // Where sObjectType='Partner_Contract__c' and isActive=true and Name='Approval'].id;
        update pc;  




    }
}

 
Hello!

I am trying to create opportunity renewals from Assets.  If an asset is tied to the same opportunity as an expiring asset, we need to add that as a line item on the opportunity page.  Right now, I can only create an opp with 1 product, but I may have 4 assets that need to be added to that opp as products due to their previous relationship.  Please see my code below to let me know what I am doing wrong:
 
trigger createOpp2 on Asset (after update) {


for(Asset A : Trigger.New){



//Opportunity opp=[select Id from Opportunity where id =: A.Opportunity__c Limit 1];


list<Asset> assets=[select Id,Product2id,Opportunity__c From Asset where Opportunity__c =:a.Opportunity__c];
 

 List<PriceBookEntry> ProductList =  [SELECT  Id, Product2Id,UnitPrice FROM PriceBookEntry WHERE Product2Id =:a.Product2id];
 
    

List<OpportunityLineItem> listOI = new List<OpportunityLineItem> ();
  

 if (Trigger.isUpdate && A.Create_Renewal_Opp__c==TRUE ) 
                        {  
                        Opportunity o = New Opportunity(
                            AccountId =A.AccountId,
                            Name='New Subscrition Renewal',                    
                            Type = 'Subscription Renewal',
                            CloseDate=System.Today()+60,
                            RecordTypeId=[select Id from RecordType where Name = 'Renewal' and SobjectType = 'Opportunity'].Id,
                            StageName='Renewal');
                                     
                            insert o;
                            
                            
                            for(PricebookEntry Product: ProductList){
                               Opportunitylineitem NewItem = new opportunitylineItem();
                                   NewItem.opportunityId=o.id;
                                       NewItem.quantity=a.quantity;
                                              NewItem.UnitPrice=(Product.UnitPrice*0.5+Product.UnitPrice);
                                               NewItem.PricebookEntryId=Product.Id;
                                               
                                                   listOI.add(NewItem);   
                   
       }
                                                  insert listOI;
                                                               
    
     }}}

 
Looking for some assistance with this article I posted a few weeks back.  I have not been able to crack this and was hoping this re-post would help to get some traction.  Thank you all so much~!

https://developer.salesforce.com/forums/ForumsMain?id=906F0000000BQnrIAG

​Kevin Chiles
Hello developers of the Salesforce World!

I need some help (probably more than I realize).  I am trying to create a trigger that will carry over products to a custom object when an opportunity is closed won.  I have this part working.  However, those products need to be updated (renewed) with a similar purchase (same account, new opp, but same products).  This part I cannot get to work.  I keep getting List has more than 1 row for assignment as an error and I do not know how to resolve it.  Any assistance would be amazing!  Thanks!
 
trigger OpportunityWon2 on Opportunity (after update, after insert) {
  for (Opportunity o : Trigger.New) {
        if (o.isWon != (Trigger.oldMap != null ? Trigger.oldMap.get(o.Id).isWon : false) && o.isWon)
        {
      
      boolean okee = false;
      if (Trigger.isUpdate) {    
        // Check if there already is a SPA, if true then skip
        Integer renewcnt = [SELECT count() FROM Renewal_Summary__c WHERE Account__c = :o.AccountId];
        if (renewcnt == 0)
          okee = true;

            List<OpportunityLineItem> prods = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c=:'Maintenance Contracts' ];
            List<OpportunityLineItem> prods2 = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c!='Maintenance Contracts' ];
            
            for(OpportunityLineItem prod : prods )
            {
            
            Id pId = [SELECT id, Product2Id FROM PriceBookEntry WHERE id = :prod.PricebookEntryId][0].Product2Id;
            Product2 p = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pId];
            
            if (Trigger.isInsert || (Trigger.isUpdate && okee)) {  
           
            Renewal_Summary__c rs = new Renewal_Summary__c(Account__c = o.AccountId); 
           
            rs.Reseller__c = o.Reseller__r.Id;
            rs.Type__c = 'Maintenance Contracts';
            rs.Status__c = 'Active';
            rs.Product__c=pId;           
            insert rs;
            
            for(OpportunityLineItem addprod : prods2 )
            {
            
            Id pId2 = [SELECT id, Product2Id,UnitPrice FROM PriceBookEntry WHERE id = :addprod.PricebookEntryId][0].Product2Id;
            Product2 p2 = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pId2];
            
           
            
           Renewal_Line_Item__c RLI = new Renewal_Line_Item__c(Renewal_Summary__c=rs.Id);
           RLI.Opportunity__c=o.Id;
           RLI.Price__c=addprod.UnitPrice;
           RLI.Quantity__c=addprod.Quantity;
           RLI.Renewal_Date__c=o.CloseDate+365;
           RLI.Purchase_Date__c=o.CloseDate;
           RLI.Product__c=pID2;
           RLI.Total_Price__c=addprod.TotalPrice;
           
           insert RLI;
           }
           }
        
        Else{
        
        List<OpportunityLineItem> prodsold = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c=:'Maintenance Contracts' ];
            List<OpportunityLineItem> prods2old = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c!='Maintenance Contracts' ];
            
            for(OpportunityLineItem prod2old : prodsold )
            {
            
           // Id pId = [SELECT id, Product2Id FROM PriceBookEntry WHERE id = :prodold.PricebookEntryId][0].Product2Id;
            //Product2 p = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pId];
            
            Id pIdold = [SELECT id, Product2Id,UnitPrice FROM PriceBookEntry WHERE id = :prod2old.PricebookEntryId][0].Product2Id;
            Product2 p2old = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pIdold];
        
            if (Trigger.isInsert || (Trigger.isUpdate)) { 
        
            
        
           Renewal_Summary__c rsold= [select Id,Name,Product__c,Account__c from Renewal_Summary__c where Account__c=:o.AccountId];
           Renewal_Line_Item__c RLIold =[select Id,Product__c,Opportunity__c,Price__c,Quantity__c, Renewal_Summary__c, Renewal_Date__c,Purchase_Date__c,Total_Price__c from Renewal_Line_Item__c where Renewal_Summary__c =:rsold.Id];
           
           
           
           RLIold.Opportunity__c=o.Id;
           RLIold.Price__c=prod2old.UnitPrice;
           RLIold.Quantity__c=prod2old.Quantity;
           RLIold.Renewal_Date__c=o.CloseDate+365;
           RLIold.Purchase_Date__c=o.CloseDate;
           RLIold.Product__c=pIDold;
           RLIold.Total_Price__c=prod2old.TotalPrice;
           
           update RLIold;
    }
}}}}}}}

 
Hello!

I am trying to raise my code coverage for a trigger that picks up a converted lead, and creates a few records and eventually will send out an email to a client.  however, I cannot get my code over 57% and wanted to turn to the Community for assistance!  Any help you can provide would be awesome!  Please see the trigger below:
 
trigger createcontract on Lead (after update) {


//trigger InsertContract on Opportunity (after insert, after update) {

  List<Sertifi2_0__TestContract__c> Childs = new List<Sertifi2_0__TestContract__c>();
  
  PageReference pdf = Page.ExcelPDF;

  
  for(lead o : trigger.new)
  
    {
    
  // if(trigger.isupdate){
   
    if(o.LeadSource=='[Liberty Reseller]'&& o.isconverted==True){
    
       Sertifi2_0__TestContract__c Child = new Sertifi2_0__TestContract__c ();
       Child.Sertifi2_0__Opportunity__c = o.ConvertedOpportunityId;
       child.Sertifi2_0__Account__c=o.ConvertedAccountId;
       child.Sertifi2_0__Settings__c='Settings';
       Child.Name = 'New Contract'; 
       child.Sertifi2_0__Contact__c=o.Convertedcontactid;
       Childs.add(Child);     
          

    insert Childs;


    Sertifi2_0__EDocument__c signDoc = new Sertifi2_0__EDocument__c(
    Sertifi2_0__TestContract__c = child.id,
    Sertifi2_0__Name__c = 'FurstPerson Agreement for '+ child.Sertifi2_0__Contact__r.Name+'.pdf',
    //Sertifi2_0__Sertifi_ID__c = 'qwerty',
    Sertifi2_0__Number_Signed__c = 0,
    Sertifi2_0__Document_Type__c = 'Signing Document');
    
insert signDoc;

if (!Test.isRUnningTest()) {
            Document thedoc = [select body from document where Name = 'Sertifi Contract1'];
            //String pdfBody = EncodingUtil.urlEncode(thedoc.body.toString(), 'UTF-8');


Contact tempContact = [select id,name,email from Contact where Id =: o.Convertedcontactid][0];
Sertifi2_0__ContractContactJunction__c signer = new Sertifi2_0__ContractContactJunction__c(
    Sertifi2_0__Contact__c = tempContact.id,
    Sertifi2_0__TestContract__c = child.id,
    Sertifi2_0__Signer_Order__c = 1,
    
    Sertifi2_0__Level_Name__c = '1st Signer',
                Sertifi2_0__Email__c = tempcontact.email);
insert signer;

Attachment attach = new Attachment();
           //AttachedContentDocument attach = new AttachedContentDocument();
           //attach.ContentDocumentId = '015J0000000gLXk';
            attach.Body = thedoc.body;
            attach.name = 'Furst Agreement for ' + child.Sertifi2_0__Contact__r.Name+'.pdf';
            attach.ParentId = signDoc.Id;
            //attach.
            insert attach;
            
            Sertify_Methods.callSertifi(child.Id);

}
}
}
}

And the test class:
@isTest (SeeAllData=true)
public class Contractreatetestclass{
    static Document document;
    
    static {

    document = new Document();
    document.Body = Blob.valueOf('Some Text');
    document.ContentType = 'application/pdf';
    document.DeveloperName = 'my_document';
    document.IsPublic = true;
    document.Name = 'Sertifi Contract1';
    document.FolderId = [select id from folder where name = 'Public Documents'].id;
    insert document;

  }
  
  static testMethod void ContractreatetestclassMethod(){
  
  Test.startTest();
  
    Lead l = new Lead(FirstName='test',LastName='test',
    Company='test',
    LeadSource='[Liberty Reseller]');
    Insert L;
    
    Database.LeadConvert lc = new database.LeadConvert();
    lc.setLeadId(l.id);
    lc.setDoNotCreateOpportunity(false);
    lc.setConvertedStatus('Qualified');

    Database.LeadConvertResult lcr = Database.convertLead(lc);
    System.assert(lcr.isSuccess());

    Sertifi2_0__TestContract__c Contract = new Sertifi2_0__TestContract__c ();
       Contract.Sertifi2_0__Opportunity__c = l.ConvertedOpportunityId;
       Contract.Sertifi2_0__Account__c=l.ConvertedAccountId;
       Contract.Sertifi2_0__Settings__c='Settings';
       Contract.Name = 'New Contract'; 
       Contract.Sertifi2_0__Contact__c=l.Convertedcontactid;
       insert contract;


    Contact tempContact = new Contact(FirstName='test',LastName='Test',AccountId=l.convertedAccountId);
    
    insert tempContact;
    
    Sertifi2_0__EDocument__c signDoc = new Sertifi2_0__EDocument__c(
    Sertifi2_0__TestContract__c = contract.id,
    Sertifi2_0__Name__c = 'FurstPerson Agreement for '+ contract.Sertifi2_0__Contact__r.Name+'.pdf',
    //Sertifi2_0__Sertifi_ID__c = 'qwerty',
    Sertifi2_0__Number_Signed__c = 0,
    Sertifi2_0__Document_Type__c = 'Signing Document');
    
    insert signDoc;


    Sertifi2_0__ContractContactJunction__c signer = new Sertifi2_0__ContractContactJunction__c(
    Sertifi2_0__Contact__c = tempContact.id,
    Sertifi2_0__TestContract__c = Contract.id,
    Sertifi2_0__Signer_Order__c = 1,
    
    Sertifi2_0__Level_Name__c = '1st Signer',
                Sertifi2_0__Email__c = tempcontact.email);
    insert signer;
    
    Attachment attach = new Attachment();
           //AttachedContentDocument attach = new AttachedContentDocument();
           //attach.ContentDocumentId = '015J0000000gLXk';
            attach.Body = document.body;
            attach.name = 'Furst Agreement for ' + Contract.Sertifi2_0__Contact__r.Name+'.pdf';
            attach.ParentId = signDoc.Id;
            //attach.
            insert attach;
            

    Test.stopTest(); 


    
   }}

Where am I failing to build out the necessary components to be successful with this code?  Thank you for any support and have a great day!

Kevin Chiles
 
Hello!

I have a trigger that is creating a contact role on the Opportunity when a lookup field is populated but I cannot get my code coverage above 66%!
What can I do to get better coverage?!
Trigger:
trigger addContactRole on Opportunity (after Insert, after update) {

List<OpportunityContactRole> newContactRoleList=new List<OpportunityContactRole>();
List<OpportunityContactRole> oldContactRoleList=new List<OpportunityContactRole>();
Set<Id> OppId=new Set<Id>();
Set<Id> ContactId=new Set<Id>();

for(Opportunity oppObj: Trigger.new)
{
//Insert condition
if(Trigger.isInsert)
{
if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
{
//Creating new contact role
newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c,OpportunityId=oppObj.Id, Role='Decision Maker', IsPrimary = true));

}
}
else
{

if(oppObj.Investor__c==null && Trigger.oldMap.get(oppObj.Id).Investor__c!=null)
{
//Getting the contact and oppty Id from old values and adding this in set
Opportunity OldoppObj=Trigger.oldMap.get(oppObj.Id);
OppId.add(OldoppObj.id);
ContactId.add(OldoppObj.Investor__c);

}
else if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
{
//Creating new contact role
newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c, OpportunityId=oppObj.Id, Role='Decision Maker', IsPrimary = true));
}
}
}


try
{
//inserting new Contacts
if(newContactRoleList.size()>0) insert newContactRoleList;

//Selecting old contact roles
if (OppId.size()>0) oldContactRoleList=[Select Id from OpportunityContactRole where ContactId in : ContactId and OpportunityId in : OppId];

//Deleting old contact roles
if (oldContactRoleList.size()>0) delete oldContactRoleList;
}
catch(Exception e)
{
System.debug(e);
trigger.new[0].addError('Technical error occurred. Please contact to your system administrator or try after some time.');

}




}

Test Class:
 
@isTest(SeeAllData=true)

public class YourTriggerTestClass{
    static testMethod void yourTestMethod(){
    
        //fill all the required field and make sure your data passes the validation rules.
        //insert account
        account acc = new account(
        Name='test account');
        
        insert acc;
        
        //insert contact
        contact ct2 = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct2;
        
        contact ct = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct;
        
        //insert propert
        Property__c p = new Property__c(
        Name='test');
        
        insert p;
        
        //insert campaign
        Campaign camp = new Campaign(
        Name='test camp',
        IsActive=True,
        Property__c=p.Id);
        
        insert camp;
        
        
        //Insert Opportunity
        opportunity opp = new opportunity(
        Name = 'Test oppty',
        
        CampaignId=camp.id,
        StageName='Prospecting',
        CloseDate=system.today(),
        AccountId=acc.id
        );
        
        insert opp;
        
        opp.Investor__r=ct2;
        
        update opp;
        
        
        
        }
        }

 

Hello!  I cracked this last week and wanted to share my working code with everyone.  This is for a scenario when you have multiple "contacts" or contact data on the lead object that will need to become multiple contacts.  For this one, we had 3 sections on the page where we were capturing data for brokers, Owners, ect.  This code takes each of those sections and creates a new contact for each section.  feel free to comment with any suggestions to enhance or if you have any addition questions about how it is setup.  Thanks!

Trigger
trigger UpdateContactObject_Trigger on Lead (before update) 
{/*
     * Create variables to store the lead values,
     * new and old.  This will be used below to
     * determine if the leads are being converted,
     * not converted yet, or has already been
     * converted.
     */
    List<Lead> newLeads = trigger.new;
    Map<Id, Lead> mOldLeads = trigger.oldMap;
    Lead oldLead;
    
    /*
     * Create sets of Ids to store the records
     * associated with the converted leads
     */
    Set<Id> convertedAccountIds = new Set<Id>();
    Set<Id> convertedContactIds = new Set<Id>();
    Set<Id> convertedOpportunityIds = new Set<Id>();

    /*
     * Loop through the leads submitted through this
     * trigger.  Populate the appropriate sets of Ids
     * for each lead with populated values.
     */
    for (Lead l : newLeads) {
        
        if (l.convertedAccountId != null) {
            convertedAccountIds.add(l.convertedAccountId);
        }
        
        if (l.convertedContactId != null) {
            convertedContactIds.add(l.convertedContactId);
        }
        }
        
        Account accounts =
        [SELECT Id, Name
         FROM Account
         WHERE Id IN : convertedAccountIds];
         





    for(Lead l : Trigger.New){
    If(l.IsConverted){
    
   
    Contact c1=New Contact(LastName=l.True_Owner_Last_Name__c,FirstName=l.True_Owner_First_Name__c,
    Phone=l.True_Owner_Phone__c,MailingStreet=l.True_Owner_Address__c,MailingState=l.True_Owner_State__c,MailingCity=l.True_Owner_City__c,
    MailingPostalCode=l.True_Owner_Zip__c,Email=l.True_Owner_Email__c, AccountId=accounts.id);
    insert c1;
    
    Contact c2=New Contact(LastName=l.Broker_Last_Name__c,FirstName=l.Owner_First_Name__c,
    Phone=l.Owner_Phone__c,MailingStreet=l.Owner_Address__c,MailingState=l.Owner_State__c,MailingCity=l.Owner_City__c,
    MailingPostalCode=l.Owner_Zip_Code__c,Email=l.Owner_Email__c,AccountId=accounts.id);
    insert c2;
    
    Contact c3=New Contact(LastName=l.Owner_Last_Name__c,FirstName=l.Broker_First_Name__c,
    Phone=l.Broker_Phone__c,MailingStreet=l.Broker_Address__c,MailingState=l.Broker_State__c,MailingCity=l.Broker_City__c,
    MailingPostalCode=l.Broker_Zip_Code__c,Email=l.Broker_Email__c,AccountId=accounts.id);
    insert c3;
    
    }}}

Coverage:
@isTest

public class UpdateContactObject_TriggerTestClass{
Static testmethod void UpdateContactObject_TriggerTestClass(){
//insert Lead
        Lead Lead = new Lead(
        FirstName='test ',
        LastName='Test2',
        Company='test',
        Owner__c='test',
        True_Owner__c='test3',
        Broker__c='test4'
        );
        
insert Lead;

Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(lead.id);
lc.setDoNotCreateOpportunity(false);
lc.setConvertedStatus('Qualified');

Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
}}

 

Hello!

I am trying to set an field on the opportunity line items based when a field on the parent gets updated.  However I am running into some issues, and was wondering if anyone can show me where my fall out is?
 
trigger TaxUpdate on Opportunity(after update) {
        // 1

        List<OpportunityLineItem> childRecords = [Select Id, OpportunityId,Name,LineTax__c FROM OpportunityLineItem WHERE OpportunityId IN: Trigger.newMap.keySet()];
         

        // 2

        for(OpportunityLineItem child :childRecords){

            // 3

            if(trigger.isInsert && Opportunity__r.Tax__c != NULL && !child.Name.contains(eN-PRO,Shipping,Training-Adult,AP-WTY-DTLL2,AP-WTY-FRX2)){

                child.LineTax__c = 'Tax';

            }

            // 4

            else if(trigger.isUpdate && child.LineTax__c == Null && trigger.NewMap.get(child.OpportunityId).Tax__c != trigger.OldMap.get(child.OpportunityId).Tax__c){

                child.LineTax__c = 'Tax';

            }

        }

         

        // 5

        if(childRecords.size() > 0)

            update childRecords;

}

 
Hello!

I am trying to utilize the service cloud console to alert my users when a new email is associated with their case, or if a new case comment occurs or a new task is associated to that user for the case.  This should only display information for the logged in user.  So far, I have created a class that will pull in the task data but cannot get the email or the additional case logic to pull in.  Right now it is pulling in all tasks not just ones for the case.  I am stumped and dont know where else to look!  Help me Obi Wan, your my only hope!!!

Class-
global with sharing class ActivityRemindersWidgetController {
    
    Public List<Case> CaseData {get;set;}
    public List<EmailMessage> EmailData {get; set;}
    public List<CaseComment> CasecommentData {get; set;}
    
    public class TaskData {
        public Task task {get; set;}       
        public Boolean setComplete {get; set;}
        
        public TaskData(Task t){
            setComplete = false;
            task = t;
            if (t.Subject!=null) t.Subject = t.Subject.abbreviate(100);
            }
        
        
    }
    
    private integer max_list_size=25; //sets the page size or number of rows
    public List<TaskData> tasks {get; set;}
    public Boolean showReminders {get; set;}
    public Boolean showEmails {get; set;}
    public Boolean showMoreLink {get; set;}
    public Boolean checkAllReminders {get; set;}
    
    
    
    public ActivityRemindersWidgetController() {
       CaseData=[select Id, OwnerId From Case where OwnerId=:system.Userinfo.getUserId()LIMIT :max_list_size ];
       EmailData=[select id,ActivityId,ParentId,ToAddress from EmailMessage where ToAddress=:system.Userinfo.getUserEmail()];
       CasecommentData=[select id, CommentBody,ParentId,IsPublished from CaseComment where IsPublished=:True];
        
        checkAllReminders = false;
        loadTasks();
        //loadCase();
       
    }
    
    public void loadTasks() {
        tasks = new List<TaskData>();

       // for (Case c: [Select Id, Subject, OwnerId From Case Where OwnerId =:system.Userinfo.getUserId()LIMIT :max_list_size ]);
        
       // cases.add(new TaskData(cases));

        for(Task t : [SELECT Id
                            ,Subject
                            ,Status
                            ,Description
                            ,WhoId
                            ,WhatId
                            ,What.Name
                            ,Who.Name
                            ,ActivityDate
                            ,isClosed
                            ,ReminderDateTime
                        FROM Task
                        WHERE IsClosed = false
                        AND OwnerId =: system.Userinfo.getUserId()
                       // AND whatId=:casedata.Id
                        AND IsReminderSet = true
                        ORDER BY ReminderDateTime
                        LIMIT :max_list_size ]){

             tasks.add( new TaskData(t) );
        }
           
        showReminders = !tasks.isEmpty();
        showMoreLink = (max_list_size > tasks.size());//show more link if there are more tasks
    }
    
    @RemoteAction
    global static Integer getActiveRemindersAmount(){
        //method to poll for count of un actioned reminders
        Integer res = [ SELECT count() 
                        FROM Task 
                        WHERE isClosed = false 
                        AND OwnerId =: system.Userinfo.getUserId() 
                        AND IsReminderSet = true 
                        AND ReminderDateTime <= : DateTime.now()];
        return res; 
    }
    
    public void checkUncheckAllReminders(){
        for (TaskData t : tasks){
            t.setComplete = checkAllReminders;
        }
    }
    
    public void completeTasks(){
        List<Task> completeTasks = new List<Task>();
        for(TaskData t : tasks){
            if(t.setComplete){
                completeTasks.add( new Task(Id=t.task.Id, Status='Completed') );
            }
        }
        
        if(!completeTasks.isEmpty()){
            update completeTasks;
        }
        
        loadTasks();
    }
    
    public PageReference newTask(){
        return null;
    }
    
    public void refresh(){
        loadTasks();
    }
}


vf page:

 
<apex:page controller="ActivityRemindersWidgetController">
    <apex:includeScript value="/support/console/26.0/integration.js"/>
    <apex:includeScript value="/soap/ajax/26.0/connection.js"/>
    <apex:form >
        <apex:actionFunction name="refreshAll" action="{!refresh}" rerender="remindersPanel" />
    </apex:form>
    
    <script type="text/javascript">
    
        function newTaskTab(){
            sforce.console.openPrimaryTab(null, '/00T/e', true, 'New Task', function (result) {
                if (result.success) {
                    closeSelf();
                }
            });
        }
        
        function viewAllTaskTab(){
            sforce.console.openPrimaryTab(null, '/007', true, 'View All Tasks', function (result) {
                if (result.success) {
                    closeSelf();
                }
            });
        }
        
        function closeSelf() {
             sforce.console.setCustomConsoleComponentWindowVisible(false);
        }
        
        function callbackManager(numberOfCallbacksExpected, callbackManagerHistory, callbackFunction) {
            this.objectIDs = new Array();
            this.parentIDs = new Array();
            this.tabIDs = new Array();
            this.numberOfCallbacksComplete = 0;
            this.numberOfCallbacksExpected = numberOfCallbacksExpected;
            this.callbackFunction = callbackFunction;
            
            if (callbackManagerHistory!=null) {
                for (var i = 0; i < callbackManagerHistory.tabIDs.length; i) {
                    this.objectIDs.push(callbackManagerHistory.objectIDs[i] );
                    this.tabIDs.push( callbackManagerHistory.tabIDs[i] );
                    this.parentIDs.push( callbackManagerHistory.parentIDs[i] );
                }
            }
        }
        callbackManager.prototype.callbackComplete = function() {
            this.numberOfCallbacksComplete;
          
            if (this.numberOfCallbacksComplete>=this.numberOfCallbacksExpected) {
                //we have hit all callback expected
                this.callbackFunction( this );
            }
        };
        
        function openTab(recordID, recordName, autoClose) {
            buildTabIDs( trimID(recordID), recordName, autoClose );
        }
        
        function trimID( IDstring ) {
            if(IDstring.length >= 15){
                return IDstring.substring(0, 15);
            } else {
                return IDstring;
            }
        }
        
        function launchTab(recordID, recordName, findAllSubTabCallbackResult, autoClose) {
            for (var i = 0; i < findAllSubTabCallbackResult.tabIDs.length; i) {
                if (findAllSubTabCallbackResult.objectIDs[i]==recordID) {
                    //this the tab to open, check if it has a parent sub or primary
                    if (findAllSubTabCallbackResult.parentIDs[i]==null) {
                        //will open as primary
                        sforce.console.focusPrimaryTabById(findAllSubTabCallbackResult.tabIDs[i], function (result) {
                            if (!result.success) {
                                alert("Error focussing on primary tab: "  recordName);
                            } else {
                                if (autoClose) closeSelf();
                            }
                        });
                        
                        return;
                    } else {
                        sforce.console.focusSubtabById(findAllSubTabCallbackResult.tabIDs[i], function (result) {
                            if (!result.success) {
                                alert("Error focussing on sub tab: "  recordName);
                            } else {
                                if (autoClose) closeSelf();
                            }
                        });
                        
                        return;
                    }
                }
            }
            
            //will open as primary
            sforce.console.openPrimaryTab(null, '/'recordID, true, recordName, function (result) {
                if (!result.success) {
                    alert("Error opening primary tab: "  recordName);
                } else {
                    if (autoClose) closeSelf();
                }
            });
        }
        
        function buildTabIDs(recordID, recordName, autoClose) {
            //we want to try and find the ID of the record to see if its already open
            //we are now going to check all the subtabs
            sforce.console.getPrimaryTabIds( function (result) {
                //callbackManager chains the callbacks
                findTabCallBackChain = new callbackManager(result.ids.length, null, function (findTabCallbackResult) {
                    //should now have all the primary tabs
                    findAllSubTabCallBackChain = new callbackManager(findTabCallbackResult.tabIDs.length, findTabCallbackResult, function (findAllSubTabCallbackResult) {
                        //should now have all the sub tabs
                        launchTab(recordID, recordName, findAllSubTabCallbackResult, autoClose);
                    });
                    //iterate each of the primary tabs to then get all their sub tabs
                    for (var i = 0; i < findTabCallbackResult.tabIDs.length; i) {
                        thisTabID = findTabCallbackResult.tabIDs[i];
                        sforce.console.getSubtabIds( thisTabID, function (result) {
                            findSubTabCallBackChain = new callbackManager(result.ids.length, findTabCallbackResult, function (findSubTabCallbackResult) {
                                //should now have all this tabs sub tabs
                                
                                //take the callback result and update the AllSubTab Chain
                                if (findSubTabCallbackResult!=null) {
                                    for (var i = 0; i < findSubTabCallbackResult.tabIDs.length; i) {
                                        findAllSubTabCallBackChain.objectIDs.push(findSubTabCallbackResult.objectIDs[i] );
                                        findAllSubTabCallBackChain.tabIDs.push( findSubTabCallbackResult.tabIDs[i] );
                                        findAllSubTabCallBackChain.parentIDs.push( findSubTabCallbackResult.parentIDs[i] );
                                    }
                                }
                                
                                findAllSubTabCallBackChain.callbackComplete();
                            });
                            getPageInfos(result.ids, thisTabID, findSubTabCallBackChain);
                        }); 
                    }
                });
                getPageInfos(result.ids, null, findTabCallBackChain);
            });
        }
        
        function getPageInfos(tabIDArray, parentID, callBackManagerInstance) {
            //now need to loop through the results and add them to our tab list
            for (var i = 0; i < tabIDArray.length; i) {
                //get the details for the tab
                callBackManagerInstance.tabIDs.push( tabIDArray[i] );//add tabid to array
                callBackManagerInstance.parentIDs.push( parentID );//add parentid to array
                sforce.console.getPageInfo(tabIDArray[i], function (result) {
                    pageInfo = JSON.parse(result.pageInfo);
     
                    //add to map with recordID as key and tabId as value
                    callBackManagerInstance.objectIDs.push( pageInfo.objectId);//add recordid to array
                    callBackManagerInstance.callbackComplete();
                }); 
            }
        }
        
        
        /*
        Add Additional logic here...
        */
        
        
        
    </script>
    <apex:form >
    <div class="remindersContainer">
        <apex:pageBlock >
            <apex:outputPanel id="myButtons">
                <apex:commandButton action="{!completeTasks}" value="Mark Complete" rendered="{!showReminders}" reRender="remindersPanel, myButtons"/>
                <apex:commandButton action="{!refresh}" value="Refresh" style="float:right;"/>
                <apex:commandButton action="{!newTask}" value="New Reminder" oncomplete="newTaskTab();" style="float:right;"/>
            </apex:outputPanel>
            <br/><br/>        
            
            <apex:outputPanel id="remindersPanel">
            <apex:outputPanel id="myPanel" rendered="{!showReminders}" styleClass="fixedTable">
                <apex:pageMessages id="theMessages" />
                <apex:actionFunction name="checkAll" action="{!checkUncheckAllReminders}" rerender="remindersPanel" />
                <apex:pageBlockTable value="{!tasks}" var="t" align="center" columnsWidth="4%, 15%, 27%, 12%, 15%, 15%, 12%">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox value="{!checkAllReminders}" onclick="checkAll();"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!t.setComplete}"/>
                    </apex:column>
                    <apex:column headerValue="Reminder Date" value="{!t.task.ReminderDateTime}" />
                    <apex:column headerValue="Subject">
                        <apex:outputLink value="#" onclick="openTab('{!t.task.Id}', 'Task', true);">
                            <apex:outputText value="{!t.task.Subject}"/>
                        </apex:outputLink>
                    </apex:column>
                    <apex:column value="{!t.task.Status}" />
                    <apex:column headerValue="Who">
                        <apex:outputLink value="#" onclick="openTab('{!t.task.whoID}', '{!t.task.who.Name}', false);">
                            <apex:outputText value="{!t.task.who.Name}"/>
                        </apex:outputLink>
                    </apex:column>
                    <apex:column headerValue="What">
                        <apex:outputLink value="#" onclick="openTab('{!t.task.whatID}', '{!t.task.what.Name}', false);">
                            <apex:outputText value="{!t.task.what.Name}"/>
                        </apex:outputLink>
                    </apex:column>
                </apex:pageBlockTable>
                <apex:outputPanel rendered="{!showMoreLink}">
                    <a href="#" onclick="viewAllTaskTab();">Show all</a>
                </apex:outputPanel>
            </apex:outputPanel>
            <apex:outputPanel rendered="{!!showReminders}">No Reminders</apex:outputPanel>
            </apex:outputPanel>
        </apex:pageBlock>
    </div>
    </apex:form>
</apex:page>


 
Hello!

I am trying to associate some custom fields from my leads page into a custom object upon conversion of the lead.  This should create the account (standard function) and also create a record on a custom object related to accounts called Account_Address__c.  The code saves but for some reason, the address does not get created.  I need some help on where this is failing!

trigger LeadtoAccountAddress on Account (before update,before insert) {


for(Account a:trigger.new){
Lead l=[select Id,Status ,IsConverted,City__c,County__r.Id,State__c,ConvertedAccountId,Country__c,Zip_Code__c,Street_Address__c from Lead where ConvertedAccountId=:a.Id Limit 1];
//Account_Address__c aa=[select Id, Type__c,County_Lookup__c,City__c, State__c,Country__c,Postal_Code__c,Account__c,Street_Address__c from Account_Address__c where Account__c=:a.Id];


IF(l.Status=='Closed/Converted'){

if (Trigger.isInsert || (Trigger.isUpdate)){

Account_Address__c aa= new Account_Address__c(Account__c=l.ConvertedAccountId);
aa.City__c=l.City__c;
aa.State__c=l.State__c;
aa.Postal_Code__c=l.Zip_Code__c;
aa.Street_Address__c=l.Street_Address__c;
aa.Country__c=l.Country__c;
aa.County_Lookup__c=l.County__r.Id;

aa.Type__c='Main';

insert aa;
}
}
}
}

Hello!  I cracked this last week and wanted to share my working code with everyone.  This is for a scenario when you have multiple "contacts" or contact data on the lead object that will need to become multiple contacts.  For this one, we had 3 sections on the page where we were capturing data for brokers, Owners, ect.  This code takes each of those sections and creates a new contact for each section.  feel free to comment with any suggestions to enhance or if you have any addition questions about how it is setup.  Thanks!

Trigger
trigger UpdateContactObject_Trigger on Lead (before update) 
{/*
     * Create variables to store the lead values,
     * new and old.  This will be used below to
     * determine if the leads are being converted,
     * not converted yet, or has already been
     * converted.
     */
    List<Lead> newLeads = trigger.new;
    Map<Id, Lead> mOldLeads = trigger.oldMap;
    Lead oldLead;
    
    /*
     * Create sets of Ids to store the records
     * associated with the converted leads
     */
    Set<Id> convertedAccountIds = new Set<Id>();
    Set<Id> convertedContactIds = new Set<Id>();
    Set<Id> convertedOpportunityIds = new Set<Id>();

    /*
     * Loop through the leads submitted through this
     * trigger.  Populate the appropriate sets of Ids
     * for each lead with populated values.
     */
    for (Lead l : newLeads) {
        
        if (l.convertedAccountId != null) {
            convertedAccountIds.add(l.convertedAccountId);
        }
        
        if (l.convertedContactId != null) {
            convertedContactIds.add(l.convertedContactId);
        }
        }
        
        Account accounts =
        [SELECT Id, Name
         FROM Account
         WHERE Id IN : convertedAccountIds];
         





    for(Lead l : Trigger.New){
    If(l.IsConverted){
    
   
    Contact c1=New Contact(LastName=l.True_Owner_Last_Name__c,FirstName=l.True_Owner_First_Name__c,
    Phone=l.True_Owner_Phone__c,MailingStreet=l.True_Owner_Address__c,MailingState=l.True_Owner_State__c,MailingCity=l.True_Owner_City__c,
    MailingPostalCode=l.True_Owner_Zip__c,Email=l.True_Owner_Email__c, AccountId=accounts.id);
    insert c1;
    
    Contact c2=New Contact(LastName=l.Broker_Last_Name__c,FirstName=l.Owner_First_Name__c,
    Phone=l.Owner_Phone__c,MailingStreet=l.Owner_Address__c,MailingState=l.Owner_State__c,MailingCity=l.Owner_City__c,
    MailingPostalCode=l.Owner_Zip_Code__c,Email=l.Owner_Email__c,AccountId=accounts.id);
    insert c2;
    
    Contact c3=New Contact(LastName=l.Owner_Last_Name__c,FirstName=l.Broker_First_Name__c,
    Phone=l.Broker_Phone__c,MailingStreet=l.Broker_Address__c,MailingState=l.Broker_State__c,MailingCity=l.Broker_City__c,
    MailingPostalCode=l.Broker_Zip_Code__c,Email=l.Broker_Email__c,AccountId=accounts.id);
    insert c3;
    
    }}}

Coverage:
@isTest

public class UpdateContactObject_TriggerTestClass{
Static testmethod void UpdateContactObject_TriggerTestClass(){
//insert Lead
        Lead Lead = new Lead(
        FirstName='test ',
        LastName='Test2',
        Company='test',
        Owner__c='test',
        True_Owner__c='test3',
        Broker__c='test4'
        );
        
insert Lead;

Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(lead.id);
lc.setDoNotCreateOpportunity(false);
lc.setConvertedStatus('Qualified');

Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
}}

 

Hello!

I have an Email trigger that seems to be firing twice.  I cannot for the life of me figure out why.  Basically the trigger is picking up a template and a the attachments associated to a custom objects record and emailing it to a team.  This for some reason is firing 2 emails instead of one.  Its driving me mad!
 
trigger Send_TechDocs_Cloud on Sales_Handoff_Activity__c (after update) {



for(Sales_Handoff_Activity__c SHA : trigger.new){
    if (SHA.TAD_Status__c == 'TAD Complete' && SHA.Cloud__c==True && Trigger.oldMap.get(Sha.Id).TAD_Status__c != Trigger.newMap.get( Sha.Id ).TAD_Status__c ) {
   // && SHA.TAD_Status__c!=Trigger.oldMap.get(sha.id).TAD_Status__c
   
    //Retrieve Email template
     EmailTemplate et=[Select id from EmailTemplate where name=:'Cloud Tad Complete'];
     
     
    //Create email list
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

       //Create attachment list
       List<Messaging.EmailFileAttachment> efalist = new List<Messaging.EmailFileAttachment>();
       
       contact c =[select id, email from Contact where Email=:'kevin.chiles@megapath.com' limit 1];
       //Create message
       
       Messaging.SingleEmailMessage singlemail = new Messaging.SingleEmailMessage();
        //add template
       singleMail.setTemplateId(et.Id);              
        //set target object for merge fields
        singleMail.setTargetObjectId(c.Id);
        singlemail.setwhatId(SHA.Id);       
        //set to save as activity or not
        singleMail.setSaveAsActivity(false);
         
         
        //add address's that you are sending the email to
        String []ToAddress= new string[] {'ash@megapath.com' }; 

        //set addresses
        singlemail.setToAddresses(toAddress);
        
        
            //add mail
                emails.add(singleMail);
        
        {
Help me Obi Wan, you're my only hope

Chiles
    
Hello!

Below is complete code with test class for sending an Email from a custom object with all of the related attachments upon a variable on the object being set:
 
trigger Send_TechDocs on Sales_Handoff_Activity__c (before update) {



for(Sales_Handoff_Activity__c SHA : trigger.new){
    if (SHA.Tech_Doc_Status__c == 'Completed') {
    
    //Retrieve Email template
     EmailTemplate et=[Select id from EmailTemplate where name=:'Tech Doc Complete Full'];
     
     
    //Create email list
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

       //Create attachment list
       List<Messaging.EmailFileAttachment> efalist = new List<Messaging.EmailFileAttachment>();
       
       contact c =[select id, email from Contact where Email=:'Salesops@megapath.com' limit 1];
       //Create message
       
       Messaging.SingleEmailMessage singlemail = new Messaging.SingleEmailMessage();
        //add template
       singleMail.setTemplateId(et.Id);              
        //set target object for merge fields
        singleMail.setTargetObjectId(c.Id);
        singlemail.setwhatId(SHA.Id);       
        //set to save as activity or not
        singleMail.setSaveAsActivity(false);
         
         
        //add address's that you are sending the email to
        String []ToAddress= new string[] {'SSS1@Megapath.com','megapath.highcap@megapath.com' }; 

        //set addresses
        singlemail.setToAddresses(toAddress);
        
        
            //add mail
                emails.add(singleMail);
        
        {
           
                      

            // fetch attachments for Object
                     
            List<Attachment> allatt = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id];                     
         
         // Attachment att = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : SHA.id limit 1];

           for(Attachment att : allatt) {
            // List of attachments handler
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();

   {
      // try{

        

//Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(att.Name);

efa.setBody(att.Body);

efa.setContentType(att.ContentType);

efaList.add( efa );

  
    
   }

    // Attach files to email instance
   // singlemail.setFileAttachments(attachmentList);
   
  {
    singlemail.setFileAttachments(efaList);
   }
   }
    //send the message
     Messaging.sendEmail(emails);
          }

 }  
}
}

Test Class:
 
@isTest
private class EngineerNotesCreateTest
{
    static testMethod void EngineerNotesCreate()
    {
    
    Account acc=New Account(Name='test');
    insert acc;
    
     Contact ct=New Contact(FirstName='sarah',LastName='jenny',email='Salesops@megapath.com',AccountId=acc.id);
        insert ct;
      
     Opportunity opp= New Opportunity (Name='Test',Closedate=date.today(),NextStep='test',StageName='1 – Solution Design',Sales_Engineer__c='Joel Thomas',
     LeadSource='Call - Service Transfer',Type='Change Voice Services',Channel__c='SMB',    
        Install_Street__c='Test',
        Install_Zip__c='94582',
        Install_State__c='CA', 
        Install_City__c='Test',
        Install_Phone__c='3157775695',
        Install_Country__c='USA');
        Insert opp;
     
Booking_Checklist__c  bc= New Booking_Checklist__c(   
Active_Date__c=date.Today(),
Adjusted_Revenue__c=100,
Adjusted_Revenue_Reason__c='Product Line Adjustment',
Affiliate_Name_Matches__c='Yes',
Approval_Status__c='Approved',
Booked_Deal_More_Than_75_Locations__c='Yes',
Booking_Checklist_Record_Owner__c='Joy Cortez',
Checklist_Notes__c='test',
Child_or_Parent_Account_Correct__c='Yes',
Contracted_items_match_products__c='Yes',
Contracted_pricing_match_product_Pricing__c='Yes',
Contract_Signed_by_Valid_Date_Shown__c='Yes',
Correct_Shipping_Address__c='Yes',
Disposition__c='Construction Cost',
Does_Circuit_Speed_Qualify_W_Carrier__c='Yes',
Enrolled_Date__c=system.Today(),
Existing_Cust_Is_the_org_RMR_Reflected__c='Yes',
Existing_Customer__c='No',
Flowed_with_Layer_2_circuit__c='Yes',
Have_residential_services_been_ordered__c='No',
Incorrect_Missing_LCON_Information__c='No',
Is_the_contract_legible__c='Yes',
Is_this_an_out_of_contract_Move_order__c='No',
Is_this_an_R14_to_R17_voice_migration__c='No',
Is_this_a_Sylantro_or_Duet_migration__c='No',
LAN_set_up_missing__c='Yes',
Location_sold_as_new_within_6_months__c='No',
Missing_IP_Blocks__c='No',
Missing_Supp_Address_Information__c='No',
New_customer_booked_by_CAS_Dept__c='No',
NRR_Included_in_Quote__c='No',
Opportunity__c=opp.id,
Order_booked_previously_at_same_location__c='No',
Order_Stage__c='Enrolled',
Partner_splits_Partner_being_tagged__c='No',
Pre_Install_Cancelled_Date__c=system.today(),
Quote_Linked_to_Opportunity_b2b_ID__c='Yes',
Quote_Ordered_Status__c='Data Ready for Review',
Reason_Code__c='Awaiting FOC',
Agent_Matches_Named_Acct_Ent_SMB_HO_Mang__c='Yes',
SCR_Approval_completed_prior_to_booking__c='Yes',
Signed_Contract_Attached_To_Opp__c='Yes',
Signed_contract_has_additional_Writting__c='Yes',
Signed_contract_uploaded_into_MPQT__c='Yes',

Voice_Cloud_MPLS_Orders_SHA_Completed__c='Yes');

insert bc;

     
     
     
        
        Sales_Handoff_Activity__c Sha= new Sales_Handoff_Activity__c(
        Number_of_Seats_Trunks__c='5',
        Primary_Contact_Time_Zone__c='West',
        Opportunity_Name_2__c=opp.id,
        Customer_Contact_Name__c='Kevin Chiles',
        Customer_Contact_Email__c='kchiles2@gmail.com',
        Customer_Contact_Phone__c='0000000000',
        Quote_ID__c='255555.2',
        Expedite_Hand_Off_Date__c= date.today(),
        
        VPM_Notes__c='test notes',
        Assigned_VPM__c='Alex Stewart'
        
        );
        insert Sha;
        Attachment attach=new Attachment();  
        attach.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        attach.body=bodyBlob;
        attach.parentId=sha.id;
        insert attach;
        
        sha.tech_doc_status__c='Completed';
        
        update Sha;
    }
}

This works like a dream, enjoy!

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
 
Hello!

I am having an error where I do not have enough coverage on my trigger to deploy.  My code covers the whole trigger except the crucial record type update.  Any help is greatly appreciated!

Trigger:
trigger PartnerContractRecordtype on Case (before update) {

for (Case c : Trigger.New) {
 
Partner_Contract__c pc =[Select Id ,RecordTypeId from Partner_Contract__c where id=:c.Partner_Contract__c limit 1];

RecordType rt = [select id from Recordtype where SobjectType='Partner_Contract__c' and Name =:'Approval'];

if (c.Status =='Partner - Pending Paperwork' && c.Partner_Contract__c!=Null){



pc.RecordtypeId=rt.id;

update pc;
}
}
}

Class:

@isTest(SeeAllData = true)
public class PartnerContractTrigger
{
    public static testMethod void PartnerContractTrigger()
    {
    
    Account a = New Account(Name='test',recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Account' and isActive=true and Name='Affiliate'].id);
        
        insert a;
        
        Contact ct=New Contact(FirstName='sarah',LastName='jenny',email='test@test.com',AccountId=a.id);
    insert ct;
        
        Account mpdefault = New Account(Name='Megapath - Default',recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Account' and isActive=true and Name='Affiliate'].id);
        
        Contact ct2=New Contact(FirstName='sarah',LastName='jenny',email='test@test.com',AccountId=mpdefault.id);
        insert ct2;
        
        Insert mpdefault;
        
        Partner_Contract__c pc = New Partner_Contract__c(Name='0',Parent_Partner__c=mpdefault.id,Status__c='Active',
        PartnerProgram__c='Referral',Partner__c=a.Id,recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Partner_Contract__c' and isActive=true and Name='Non Approval'].id
        );
        Insert pc; 
        
        Availiable_Contract__c ac = New Availiable_Contract__c(Name='0',Contract_Rank__c=1,Partner__c=a.Id,Partner_Contract__c=pc.Id 
        );
                   
        Insert ac;       
        
        RecordType recordtypeId2=[Select Name, Id From RecordType
        Where sObjectType='Partner_Contract__c' and isActive=true and Name='Approval'];
        
        Case C= new Case(AccountId=a.id,ContactId=ct.Id,Sales_Rep__c=UserInfo.getUserId(),Case_Request_Type__c='Partner Onboarding',
        recordtypeId=[Select Name, Id From RecordType
        Where sObjectType='Case' and isActive=true and Name='Channel Support'].id,Partner_Contract__c=pc.id,Company_Name__c=a.Name,
        Clarity_Account_ID__c='N/A',Site_Contact__c='Test', Site_Contact_Phone__c='3157775695',Primary_Affiliate__c='Megapath - Default',
        Primary_Affiliate_ID_2__c='1980',Subject='Onboarding Request for New Partner',Description='Onboarding Request for New Partner');
        
        insert c;
                     
        c.Status='Pending Partner Paperwork';
        update c;
        
        
          
        Pc.Name='1234';
        pc.Status__c='Active';
        Pc.Partner_Contract_Status__c='Partner Activated';
       // pc.recordtypeId=[Select Name, Id From RecordType
       // Where sObjectType='Partner_Contract__c' and isActive=true and Name='Approval'].id;
        update pc;  




    }
}
 
Hello developers of the Salesforce World!

I need some help (probably more than I realize).  I am trying to create a trigger that will carry over products to a custom object when an opportunity is closed won.  I have this part working.  However, those products need to be updated (renewed) with a similar purchase (same account, new opp, but same products).  This part I cannot get to work.  I keep getting List has more than 1 row for assignment as an error and I do not know how to resolve it.  Any assistance would be amazing!  Thanks!
 
trigger OpportunityWon2 on Opportunity (after update, after insert) {
  for (Opportunity o : Trigger.New) {
        if (o.isWon != (Trigger.oldMap != null ? Trigger.oldMap.get(o.Id).isWon : false) && o.isWon)
        {
      
      boolean okee = false;
      if (Trigger.isUpdate) {    
        // Check if there already is a SPA, if true then skip
        Integer renewcnt = [SELECT count() FROM Renewal_Summary__c WHERE Account__c = :o.AccountId];
        if (renewcnt == 0)
          okee = true;

            List<OpportunityLineItem> prods = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c=:'Maintenance Contracts' ];
            List<OpportunityLineItem> prods2 = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c!='Maintenance Contracts' ];
            
            for(OpportunityLineItem prod : prods )
            {
            
            Id pId = [SELECT id, Product2Id FROM PriceBookEntry WHERE id = :prod.PricebookEntryId][0].Product2Id;
            Product2 p = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pId];
            
            if (Trigger.isInsert || (Trigger.isUpdate && okee)) {  
           
            Renewal_Summary__c rs = new Renewal_Summary__c(Account__c = o.AccountId); 
           
            rs.Reseller__c = o.Reseller__r.Id;
            rs.Type__c = 'Maintenance Contracts';
            rs.Status__c = 'Active';
            rs.Product__c=pId;           
            insert rs;
            
            for(OpportunityLineItem addprod : prods2 )
            {
            
            Id pId2 = [SELECT id, Product2Id,UnitPrice FROM PriceBookEntry WHERE id = :addprod.PricebookEntryId][0].Product2Id;
            Product2 p2 = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pId2];
            
           
            
           Renewal_Line_Item__c RLI = new Renewal_Line_Item__c(Renewal_Summary__c=rs.Id);
           RLI.Opportunity__c=o.Id;
           RLI.Price__c=addprod.UnitPrice;
           RLI.Quantity__c=addprod.Quantity;
           RLI.Renewal_Date__c=o.CloseDate+365;
           RLI.Purchase_Date__c=o.CloseDate;
           RLI.Product__c=pID2;
           RLI.Total_Price__c=addprod.TotalPrice;
           
           insert RLI;
           }
           }
        
        Else{
        
        List<OpportunityLineItem> prodsold = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c=:'Maintenance Contracts' ];
            List<OpportunityLineItem> prods2old = [SELECT id, PricebookEntryId,Product_Family__c, TotalPrice, Discount, UnitPrice, Quantity, name FROM OpportunityLineItem WHERE OpportunityId = :o.id AND Product_Family__c!='Maintenance Contracts' ];
            
            for(OpportunityLineItem prod2old : prodsold )
            {
            
           // Id pId = [SELECT id, Product2Id FROM PriceBookEntry WHERE id = :prodold.PricebookEntryId][0].Product2Id;
            //Product2 p = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pId];
            
            Id pIdold = [SELECT id, Product2Id,UnitPrice FROM PriceBookEntry WHERE id = :prod2old.PricebookEntryId][0].Product2Id;
            Product2 p2old = [SELECT id, name, Family, Description, Is_Asset__c, Maintenance_Cycle__c, End_Of_Life_Date__c FROM Product2 WHERE id = :pIdold];
        
            if (Trigger.isInsert || (Trigger.isUpdate)) { 
        
            
        
           Renewal_Summary__c rsold= [select Id,Name,Product__c,Account__c from Renewal_Summary__c where Account__c=:o.AccountId];
           Renewal_Line_Item__c RLIold =[select Id,Product__c,Opportunity__c,Price__c,Quantity__c, Renewal_Summary__c, Renewal_Date__c,Purchase_Date__c,Total_Price__c from Renewal_Line_Item__c where Renewal_Summary__c =:rsold.Id];
           
           
           
           RLIold.Opportunity__c=o.Id;
           RLIold.Price__c=prod2old.UnitPrice;
           RLIold.Quantity__c=prod2old.Quantity;
           RLIold.Renewal_Date__c=o.CloseDate+365;
           RLIold.Purchase_Date__c=o.CloseDate;
           RLIold.Product__c=pIDold;
           RLIold.Total_Price__c=prod2old.TotalPrice;
           
           update RLIold;
    }
}}}}}}}

 
Hello!

I am trying to raise my code coverage for a trigger that picks up a converted lead, and creates a few records and eventually will send out an email to a client.  however, I cannot get my code over 57% and wanted to turn to the Community for assistance!  Any help you can provide would be awesome!  Please see the trigger below:
 
trigger createcontract on Lead (after update) {


//trigger InsertContract on Opportunity (after insert, after update) {

  List<Sertifi2_0__TestContract__c> Childs = new List<Sertifi2_0__TestContract__c>();
  
  PageReference pdf = Page.ExcelPDF;

  
  for(lead o : trigger.new)
  
    {
    
  // if(trigger.isupdate){
   
    if(o.LeadSource=='[Liberty Reseller]'&& o.isconverted==True){
    
       Sertifi2_0__TestContract__c Child = new Sertifi2_0__TestContract__c ();
       Child.Sertifi2_0__Opportunity__c = o.ConvertedOpportunityId;
       child.Sertifi2_0__Account__c=o.ConvertedAccountId;
       child.Sertifi2_0__Settings__c='Settings';
       Child.Name = 'New Contract'; 
       child.Sertifi2_0__Contact__c=o.Convertedcontactid;
       Childs.add(Child);     
          

    insert Childs;


    Sertifi2_0__EDocument__c signDoc = new Sertifi2_0__EDocument__c(
    Sertifi2_0__TestContract__c = child.id,
    Sertifi2_0__Name__c = 'FurstPerson Agreement for '+ child.Sertifi2_0__Contact__r.Name+'.pdf',
    //Sertifi2_0__Sertifi_ID__c = 'qwerty',
    Sertifi2_0__Number_Signed__c = 0,
    Sertifi2_0__Document_Type__c = 'Signing Document');
    
insert signDoc;

if (!Test.isRUnningTest()) {
            Document thedoc = [select body from document where Name = 'Sertifi Contract1'];
            //String pdfBody = EncodingUtil.urlEncode(thedoc.body.toString(), 'UTF-8');


Contact tempContact = [select id,name,email from Contact where Id =: o.Convertedcontactid][0];
Sertifi2_0__ContractContactJunction__c signer = new Sertifi2_0__ContractContactJunction__c(
    Sertifi2_0__Contact__c = tempContact.id,
    Sertifi2_0__TestContract__c = child.id,
    Sertifi2_0__Signer_Order__c = 1,
    
    Sertifi2_0__Level_Name__c = '1st Signer',
                Sertifi2_0__Email__c = tempcontact.email);
insert signer;

Attachment attach = new Attachment();
           //AttachedContentDocument attach = new AttachedContentDocument();
           //attach.ContentDocumentId = '015J0000000gLXk';
            attach.Body = thedoc.body;
            attach.name = 'Furst Agreement for ' + child.Sertifi2_0__Contact__r.Name+'.pdf';
            attach.ParentId = signDoc.Id;
            //attach.
            insert attach;
            
            Sertify_Methods.callSertifi(child.Id);

}
}
}
}

And the test class:
@isTest (SeeAllData=true)
public class Contractreatetestclass{
    static Document document;
    
    static {

    document = new Document();
    document.Body = Blob.valueOf('Some Text');
    document.ContentType = 'application/pdf';
    document.DeveloperName = 'my_document';
    document.IsPublic = true;
    document.Name = 'Sertifi Contract1';
    document.FolderId = [select id from folder where name = 'Public Documents'].id;
    insert document;

  }
  
  static testMethod void ContractreatetestclassMethod(){
  
  Test.startTest();
  
    Lead l = new Lead(FirstName='test',LastName='test',
    Company='test',
    LeadSource='[Liberty Reseller]');
    Insert L;
    
    Database.LeadConvert lc = new database.LeadConvert();
    lc.setLeadId(l.id);
    lc.setDoNotCreateOpportunity(false);
    lc.setConvertedStatus('Qualified');

    Database.LeadConvertResult lcr = Database.convertLead(lc);
    System.assert(lcr.isSuccess());

    Sertifi2_0__TestContract__c Contract = new Sertifi2_0__TestContract__c ();
       Contract.Sertifi2_0__Opportunity__c = l.ConvertedOpportunityId;
       Contract.Sertifi2_0__Account__c=l.ConvertedAccountId;
       Contract.Sertifi2_0__Settings__c='Settings';
       Contract.Name = 'New Contract'; 
       Contract.Sertifi2_0__Contact__c=l.Convertedcontactid;
       insert contract;


    Contact tempContact = new Contact(FirstName='test',LastName='Test',AccountId=l.convertedAccountId);
    
    insert tempContact;
    
    Sertifi2_0__EDocument__c signDoc = new Sertifi2_0__EDocument__c(
    Sertifi2_0__TestContract__c = contract.id,
    Sertifi2_0__Name__c = 'FurstPerson Agreement for '+ contract.Sertifi2_0__Contact__r.Name+'.pdf',
    //Sertifi2_0__Sertifi_ID__c = 'qwerty',
    Sertifi2_0__Number_Signed__c = 0,
    Sertifi2_0__Document_Type__c = 'Signing Document');
    
    insert signDoc;


    Sertifi2_0__ContractContactJunction__c signer = new Sertifi2_0__ContractContactJunction__c(
    Sertifi2_0__Contact__c = tempContact.id,
    Sertifi2_0__TestContract__c = Contract.id,
    Sertifi2_0__Signer_Order__c = 1,
    
    Sertifi2_0__Level_Name__c = '1st Signer',
                Sertifi2_0__Email__c = tempcontact.email);
    insert signer;
    
    Attachment attach = new Attachment();
           //AttachedContentDocument attach = new AttachedContentDocument();
           //attach.ContentDocumentId = '015J0000000gLXk';
            attach.Body = document.body;
            attach.name = 'Furst Agreement for ' + Contract.Sertifi2_0__Contact__r.Name+'.pdf';
            attach.ParentId = signDoc.Id;
            //attach.
            insert attach;
            

    Test.stopTest(); 


    
   }}

Where am I failing to build out the necessary components to be successful with this code?  Thank you for any support and have a great day!

Kevin Chiles
 
Hello!

I have a trigger that is creating a contact role on the Opportunity when a lookup field is populated but I cannot get my code coverage above 66%!
What can I do to get better coverage?!
Trigger:
trigger addContactRole on Opportunity (after Insert, after update) {

List<OpportunityContactRole> newContactRoleList=new List<OpportunityContactRole>();
List<OpportunityContactRole> oldContactRoleList=new List<OpportunityContactRole>();
Set<Id> OppId=new Set<Id>();
Set<Id> ContactId=new Set<Id>();

for(Opportunity oppObj: Trigger.new)
{
//Insert condition
if(Trigger.isInsert)
{
if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
{
//Creating new contact role
newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c,OpportunityId=oppObj.Id, Role='Decision Maker', IsPrimary = true));

}
}
else
{

if(oppObj.Investor__c==null && Trigger.oldMap.get(oppObj.Id).Investor__c!=null)
{
//Getting the contact and oppty Id from old values and adding this in set
Opportunity OldoppObj=Trigger.oldMap.get(oppObj.Id);
OppId.add(OldoppObj.id);
ContactId.add(OldoppObj.Investor__c);

}
else if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
{
//Creating new contact role
newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c, OpportunityId=oppObj.Id, Role='Decision Maker', IsPrimary = true));
}
}
}


try
{
//inserting new Contacts
if(newContactRoleList.size()>0) insert newContactRoleList;

//Selecting old contact roles
if (OppId.size()>0) oldContactRoleList=[Select Id from OpportunityContactRole where ContactId in : ContactId and OpportunityId in : OppId];

//Deleting old contact roles
if (oldContactRoleList.size()>0) delete oldContactRoleList;
}
catch(Exception e)
{
System.debug(e);
trigger.new[0].addError('Technical error occurred. Please contact to your system administrator or try after some time.');

}




}

Test Class:
 
@isTest(SeeAllData=true)

public class YourTriggerTestClass{
    static testMethod void yourTestMethod(){
    
        //fill all the required field and make sure your data passes the validation rules.
        //insert account
        account acc = new account(
        Name='test account');
        
        insert acc;
        
        //insert contact
        contact ct2 = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct2;
        
        contact ct = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct;
        
        //insert propert
        Property__c p = new Property__c(
        Name='test');
        
        insert p;
        
        //insert campaign
        Campaign camp = new Campaign(
        Name='test camp',
        IsActive=True,
        Property__c=p.Id);
        
        insert camp;
        
        
        //Insert Opportunity
        opportunity opp = new opportunity(
        Name = 'Test oppty',
        
        CampaignId=camp.id,
        StageName='Prospecting',
        CloseDate=system.today(),
        AccountId=acc.id
        );
        
        insert opp;
        
        opp.Investor__r=ct2;
        
        update opp;
        
        
        
        }
        }

 
Hello!

I am trying to associate some custom fields from my leads page into a custom object upon conversion of the lead.  This should create the account (standard function) and also create a record on a custom object related to accounts called Account_Address__c.  The code saves but for some reason, the address does not get created.  I need some help on where this is failing!

trigger LeadtoAccountAddress on Account (before update,before insert) {


for(Account a:trigger.new){
Lead l=[select Id,Status ,IsConverted,City__c,County__r.Id,State__c,ConvertedAccountId,Country__c,Zip_Code__c,Street_Address__c from Lead where ConvertedAccountId=:a.Id Limit 1];
//Account_Address__c aa=[select Id, Type__c,County_Lookup__c,City__c, State__c,Country__c,Postal_Code__c,Account__c,Street_Address__c from Account_Address__c where Account__c=:a.Id];


IF(l.Status=='Closed/Converted'){

if (Trigger.isInsert || (Trigger.isUpdate)){

Account_Address__c aa= new Account_Address__c(Account__c=l.ConvertedAccountId);
aa.City__c=l.City__c;
aa.State__c=l.State__c;
aa.Postal_Code__c=l.Zip_Code__c;
aa.Street_Address__c=l.Street_Address__c;
aa.Country__c=l.Country__c;
aa.County_Lookup__c=l.County__r.Id;

aa.Type__c='Main';

insert aa;
}
}
}
}

Hi,

 

I have a custom field on the opportunity object named 'contact__c'. This is a simple lookup field.

If populated I want a trigger that creates an Opportunity contact role for that same contact.

 

Any ideas?

 

I can update the contact__c field based on the primary contact role but I need this work the other way round.

 

Any ideas?

 

Thanks

 

 

I am trying to implement my own email-to-case class and I have the following code, which is working in my sandbox, to create an EmailMessage on a case using email services:
 
EmailMessage[] newEmail = new EmailMessage[0];
 
newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
FromName = email.fromName,
ToAddress = email.toAddresses[0],
Subject = email.subject,
TextBody = email.plainTextBody,
HtmlBody = email.htmlBody,
ParentId = newCase[0].Id, 
ActivityId = newTask[0].Id));   // (newCase and newTask are the newly created case and task from earlier code)
 
insert newEmail;
 
I have several questions.  Is it possible to set the email message status to "New"?  If I attempt to add "Status = 'New'" in the .add() method I get an error: Message: Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, Status: bad value for restricted picklist field: New: [Status] null.  If I don't attempt to set the status, it defaults to "Sent".
 
Also, does anyone have any sample code to share that adds headers and attachments from an inbound email to an Email Message object?  I'm struggling with that one.
 
Another minor issue that is bugging me is that in the Email Section of the Case page in my sandbox, the column labelled "Email Address" shows the 'to address' and my production version using the the standard SFDC email to case application will have the 'from address' (contact's address) displayed.  Does anyone know what field in the Email Message object this data comes from?
 
Thanks for the help!