• Tatiana Cooke 9
  • NEWBIE
  • 25 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 34
    Replies
Team, 

New to development. Please please help, need this working as soon as possible. Can somone look at the error and code below.

I created a button on the opportunity which can attach a file from the notes and attachment and send an email with a template. 

Getting below error when trying to deploy to production. 

System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.OpenEscrowBttn.<init>: line 18, column 1 Class.TestOpenEscrowBttn.TestOpenEscrowBttn: line 57, column 1


Test Class
@isTest
public with sharing class TestOpenEscrowBttn {
  public static testMethod void TestOpenEscrowBttn(){
    Schema.DescribeSObjectResult acctSchema = Schema.SObjectType.Account; 
    Map<String,Schema.RecordTypeInfo> AccountRecordTypeInfo = acctSchema.getRecordTypeInfosByName(); 
    Id acctRTId = AccountRecordTypeInfo.get('Ward Residential Buyers').getRecordTypeId();
    
    Schema.DescribeSObjectResult propSchema = Schema.SObjectType.Property__c; 
    Map<String,Schema.RecordTypeInfo> PropertyRecordTypeInfo = propSchema.getRecordTypeInfosByName();     
    Id propRTId = PropertyRecordTypeInfo.get('Ward Residential').getRecordTypeId();
    
    Schema.DescribeSObjectResult spaceSchema = Schema.SObjectType.Space__c; 
    Map<String,Schema.RecordTypeInfo> SpaceRecordTypeInfo = spaceSchema.getRecordTypeInfosByName();     
    Id spaceRTId = SpaceRecordTypeInfo.get('Ward Residential').getRecordTypeId();
    Property__c prop = new Property__c(recordtypeid=propRTId, Name='Test Property');
    insert prop;

    Space__c spaces = new Space__c(recordtypeid=spaceRTId, Name='Test Ward Residential', property__c = prop.id);
    insert spaces;
    
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    User thisUser = new User(Alias = 'tCook', Email='tatianaCooke@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='tCooke91@testorg.com'); //Changed

   System.runAs ( thisUser ) { 
   WE_Process__c obj=new WE_Process__c();
   obj.Name='test';
   insert obj; 
        
        Account acc = new Account(recordtypeid=acctRTId, FirstName='First Name', LastName='Last Name', Phone='111-111-1111', PersonEmail='first.last@test.com', type='Prospect');
        insert acc;

    Opportunity opty = new Opportunity(Name='Test Opty', AccountId=acc.Id, Unit_Number__c=spaces.Id, Financing_Type__c='Cash Buyer', Purchaser_Type__c='Person(s)', Reason_for_Purchase__c='Primary Residence', Nature_of_Tenancy__c='Joint Tenants', Sale_Type__c='Direct', CloseDate=date.today()+10, StageName='S1: Ready to Contract');
    insert opty;    
    
    ApexPages.currentPage().getParameters().put('optyId', opty.id);                
    ApexPages.StandardController sc = new ApexPages.StandardController(opty);
    OpenEscrowBttn ctrl = new OpenEscrowBttn(sc);
    
    ctrl.doEditEmail();
    
    ctrl.doCancel();
    
    Opportunity opty1 = new Opportunity(Name='Test Opty 1', AccountId=acc.Id, Unit_Number__c=spaces.Id, Financing_Type__c='Cash Buyer', Purchaser_Type__c='Person(s)', Reason_for_Purchase__c='Primary Residence', Nature_of_Tenancy__c='Joint Tenants', Sale_Type__c='Direct', CloseDate=date.today()+10, StageName='S1: Ready to Contract');
    insert opty1;    
    
        Attachment attach=new Attachment();     
      attach.Name='Software Eval.txt';
      Blob bodyBlob=Blob.valueOf('Software Eval');
      attach.body=bodyBlob;
        attach.parentId=opty1.id;
        insert attach;    
        
    ApexPages.currentPage().getParameters().put('optyId', opty1.id);
    ApexPages.StandardController sc1 = new ApexPages.StandardController(opty1);    
    OpenEscrowBttn ctrl1 = new OpenEscrowBttn(sc1);
    
    System.debug('***attSize: '+ctrl1.attSize);
    System.debug('***optyDocsSize: '+ctrl1.opptyDocs.size());
    ctrl1.OpptyDocs[0].lCheck = true;
    
    ctrl1.doEditEmail();
    
    ApexPages.currentPage().getParameters().put('optyId', null);                
    ApexPages.currentPage().getParameters().put('acctId', null);                
    ApexPages.StandardController sc2 = new ApexPages.StandardController(acc);
    OpenEscrowBttn ctrl2 = new OpenEscrowBttn(sc2);
        
    //ctrl2.doEditEmail();
    
    ctrl2.doCancel();

    ApexPages.currentPage().getParameters().put('optyId', null);                
    ApexPages.currentPage().getParameters().put('acctId', acc.Id);                
    ApexPages.StandardController sc3 = new ApexPages.StandardController(acc);
    OpenEscrowBttn ctrl3 = new OpenEscrowBttn(sc3);
        
    ctrl3.doEditEmail();

        
  }
}
}

Class
 
public with sharing class OpenEscrowBttn {
    public Id targetId {get;set;}
    public String AdditionalEmailId { get;set;}
    public String[] selDocs = new String[]{};   
    //public Transient List<Attachment> optyDocs {get;set;} 
    Id TempFolderId;
    Id TempTemplateId;
    String TemplateName;
    public Transient Attachment[] oldAttachments;
    public Integer attSize {get;set;}
    public List<DocItem> OpptyDocs {get;set;}    

    public OpenEscrowBttn(ApexPages.StandardController controller) {      
        Id optyId = ApexPages.currentPage().getParameters().get('optyId');
        Id acctId = ApexPages.currentPage().getParameters().get('acctId');
        if (optyId != Null) {
            targetId = optyId;
            List<Opportunity>  oppObj = [SELECT Id, AccountId, Name FROM Opportunity where Id = :optyId ];
            System.debug('******oppObj******'+oppObj);
            if(oppObj.size() > 0)
            {
               List<Account> accObj =[SELECT Id, AnnualRevenue, Appointment_Changes__c, AdditionalEmails__c FROM Account where Id = :oppObj[0].AccountId];
                System.debug('******accObj ******'+accObj );
                if(accObj.size()> 0)
                {
                  if(accObj[0].AdditionalEmails__c != null)
                  {
                    AdditionalEmailId = accObj[0].AdditionalEmails__c;
                  }
                }
            }
        } else if (acctId != Null){
          targetId = acctId;
          List<Account> accObj =[SELECT Id, AnnualRevenue, Appointment_Changes__c, AdditionalEmails__c FROM Account where Id = :acctId ];
          System.debug('******accObj ******'+accObj );
          if(accObj.size()> 0)
           {
             if(accObj[0].AdditionalEmails__c != null)
               {
                    AdditionalEmailId = accObj[0].AdditionalEmails__c;
               }
           }
          
        } else {
            targetId = Null;
        }
  
        system.debug('\n\n targetId = '+targetId);
    
        attSize = 0;
        //optyDocs = new List<Attachment>();
    set<Id> RelatedContracts = new  set<Id>();        
        if ( acctId != Null) {          
          for (Contract ct : [select id from Contract where accountId =:acctId]) {
            RelatedContracts.add(ct.id);
          }
        } 
          
        if (targetId != null) {
            OpptyDocs = new List<DocItem>();
            for (Attachment at : [Select id, Name, Body, ParentId from Attachment where (ParentId = :targetId OR ParentId in :RelatedContracts)]) {                   
                //optyDocs.add(at);
                OpptyDocs.add(new DocItem(at.Id,false,at.Name)); 
                attSize++;
            } 
            //attSize = optyDocs.size();
            if (attSize <= 0) {             
                //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'No attachments found!'));
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No attachments found for this opportunity!'));
            }          
        }           
    }

    public PageReference doEditEmail(){

        Folder TFolderId = [Select id from Folder where DeveloperName = 'Ward_Residential_Workflow_Templates' limit 1];      
        TempFolderId = TFolderId.Id;
                    
        TemplateName = 'Ke Kilohana Open Escrow Email';      
        EmailTemplate[] Temp = [Select id from EmailTemplate where Name = :TemplateName and FolderId = :TempFolderId limit 1];
                    
        if ( Temp.size() > 0 ) {
            TempTemplateId = Temp[0].id;
/*
        } else {
            EmailTemplate[] Temp1 = [Select id from EmailTemplate where FolderId = :TempFolderId limit 1];
            if ( Temp1.size() > 0 ) {
                TempTemplateId = Temp1[0].id;
            }
*/                       
        }       
        
        //Delete All current Attachments
        oldAttachments = [select id from Attachment where ParentId = :TempTemplateId ];
        
        if ( oldAttachments.size() > 0 ) {    
            delete oldAttachments;
        }        

        List<EmailTemplate> t = [Select id, FolderId, TemplateType, HtmlValue, subject, body from EmailTemplate where Id = :TempTemplateid];
        
        List<Attachment> nTlist =new  list<Attachment>();
        //Id attId = selDocs[0];
        
        set<id> aList= new set<id>();
        for (DocItem d: OpptyDocs) {
            system.debug('lCheck:'+d.lcheck);
          if ( d.lcheck ) {
            aList.add(d.DocId);
            //numDoc++;
          }
        }
        
        if (aList.size() == 0) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No attachments selected!'));
            return null;
        } else {
                        
            Attachment tnew;
                    
            Attachment[] tList = [Select Name, Body, ParentId from Attachment where id IN :aList];
            
            for (Attachment o: tList) {
                tnew = new Attachment();
                //tnew.Name = '(From Attachments)-'+o.name;
                tnew.Name = o.name;
                tnew.Body = o.Body;
                tnew.ParentId = t[0].id ;
                system.debug ('\n\n parent '+t[0].id );
                nTlist.add(tnew);           
            }       
            
            insert nTlist;
            
            /*
            set<id> sTlist = new set<id>();
            
            for (Attachment n: nTlist) {
              sTlist.add(n.id);
            }          
            */
            
            //PageReference pg = new PageReference('/_ui/core/email/author/EmailAuthor?id=' + attId + '&retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&p2_lkid=&template_id='+t.id+'&new_template=1'); 
            //PageReference pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&rtype=003' + '&p2_lkid=&template_id='+t.id+'&new_template=1');
            PageReference pg;
            if(AdditionalEmailId != null)
            {
              pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p2_lkid=003i000003hY6XKAA0' + '&p3_lkid=' + targetId +'&p24=' +AdditionalEmailId+'&rtype=003' + '&p2_lkid=&template_id='+t[0].id+ '&p4=dmoreira@tghawaii.com,jnelson@tghawaii.com,abastatas@tghawaii.com' +'&new_template=1');
            } 
            
            else 
            {
              pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&rtype=003' + '&p2_lkid=&template_id='+t[0].id+'&new_template=1');
            } 
              
            
            pg.setRedirect(true);
            return pg;
        }       
    }
        
    public PageReference doCancel(){
        PageReference pg = new PageReference('/'+targetId); 
        pg.setRedirect(true);
        return pg;
    }  
    
    public class DocItem  {    // Referral Request Wrapper
        public id DocId {get; set;}
        public boolean lcheck {get; set;}
        public string DocName {get; set;} 
         
           
        public DocItem (id i, boolean c, string s)
            {
                DocId = i;
                lcheck = c;  
                DocName =s; 
            }
    }
      
}
Visualforce Page
 
<apex:page id="thePage" standardController="Opportunity" extensions="OpenEscrowBttn" tabStyle="Opportunity">
    <apex:messages style="color:red; font-weight:bold; text-align:center;" />
    <apex:form id="theForm">  
        <apex:pageBlock id="PB" title="Send Email">
            <apex:pageBlockButtons >
                <apex:commandButton value="Edit Email and Send" action="{!doEditEmail}" rendered="{!IF(attSize>0, true, false)}"/>                     
                <apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>            
            </apex:pageBlockButtons>        
            <apex:pageblockSection id="PBS1" title="Select Attachments" columns="1">
                  <apex:pageBlockTable value="{!OpptyDocs}" var="s"  >
                        <apex:column width="10%">
                             <apex:facet name="header">Select</apex:facet>
                             <apex:inputcheckbox value="{!s.lcheck}"/> 
                        </apex:column>
                        <apex:column width="30%"> 
                            <apex:facet name="header">Attachments</apex:facet>
                            {!s.DocName}
                        </apex:column>
                  </apex:pageBlockTable>                           
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>


 
Can someone help me fix this. I am trying to deploy code into production but am getting the above error on the below trigger. 

I am new to development and this is something written by an outsourced developer. 

Appreciate any help!
Trigger WE_PersonAccount_Trigger on Account (after insert,after update) 
{

    if(Trigger.isAfter && Trigger.isInsert)
    {
       List <WE_Process__c> weProcessList  = [SELECT Id, Name, WE_Process_Sample_Data__c, WE_Batch_Process__c, WE_Account_Batch_Process__c FROM WE_Process__c];
       List<Wealth_Engine_Setting__c> wealthEngineSettingList = [SELECT Id, Name, APIKey__c, AddressURL__c, PhoneURL__c, EmailURL__c FROM Wealth_Engine_Setting__c];
        if(WE_RecusionWrapper.runPersonAccount ==true && weProcessList[0].WE_Account_Batch_Process__c  == false &&  wealthEngineSettingList.size() > 0)
        {
             WE_RecusionWrapper.runPersonAccount=false;
             List<Sobject> sobjListData = new List<Sobject>();
             List<Sobject> updateList= new List<Sobject> ();
             Set<String> accIdSet = new Set<String>();
             
             List<Account> accList = [SELECT Id, Name, LastName, FirstName, Salutation, Type, RecordTypeId, ParentId, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry, BillingStateCode, BillingCountryCode, ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry, ShippingStateCode, ShippingCountryCode, Phone, Fax, Website, Sic, Industry, PersonContactId, IsPersonAccount, PersonMailingStreet, PersonMailingCity, PersonMailingState, PersonMailingPostalCode, PersonMailingCountry, PersonMailingStateCode, PersonMailingCountryCode, PersonOtherStreet, PersonOtherCity, PersonOtherState, PersonOtherPostalCode, PersonOtherCountry, PersonOtherStateCode, PersonOtherCountryCode, PersonMobilePhone, PersonHomePhone, PersonOtherPhone, PersonAssistantPhone, PersonEmail, PersonTitle, PersonDepartment, PersonAssistantName, PersonLeadSource, PersonBirthdate, PAContactId__c, StatusCode__c, WE_Enhance__c, SSN__pc, Middle_Name__c, Gift_Capacity__pc, WE_ID__pc, WE_Age__pc, WE_Gender__pc, WE_First_Name__pc, WE_Last_Name__pc, WE_Full_Name__pc, WE_Emails__pc, WE_Has_Children__pc, WE_Spouse_First_Name__pc, WE_Spouse_Last_Name__pc, WE_Cash_on_Hand_Max_Score__pc, WE_Cash_on_Hand_Score__pc, WE_Cash_On_Hand__pc, WE_Networth_Max_Score__pc, WE_Networth_Score__pc, WE_Networth__pc, WE_Total_Income_Max_Score__pc, WE_Total_Income_Score__pc, WE_Total_Income__pc, WE_Business_Ownership_Max_Score__pc, WE_Business_Ownership_Score__pc, WE_Business_Ownership__pc, WE_Business_Sales_Volume_Max_Score__pc, WE_Business_Sales_Volume_Score__pc, WE_Business_Sales_Volume__pc, WE_Accredited_Investor__pc, WE_Total_Stock_Max_Score__pc, WE_Total_Stock_Score__pc, WE_Total_Stock__pc, WE_Direct_Stock_Holdings_Max_Score__pc, WE_Direct_Stock_Holdings_Score__pc, WE_Direct_Stock_Holdings__pc, WE_Indirect_Stock_Holdings_Max_Score__pc, WE_Indirect_Stock_Holdings_Score__pc, WE_Indirect_Stock_Holdings__pc, WE_Investable_Assets_Max_Score__pc, WE_Investable_Assets_Score__pc, WE_Investable_Assets__pc, WE_Total_Assets_Max_Score__pc, WE_Total_Assets_Score__pc, WE_Total_Assets__pc, WE_Total_Pensions_Max_Score__pc, WE_Total_Pensions_Score__pc, WE_Total_Pensions__pc, WE_Affiliation_Inclination__pc, WE_Affiliation_Inclination_Score__pc, WE_Planned_Giving__pc, WE_Influence_Rating__pc, WE_Influence_Rating_Value__pc, WE_P2G_Score__pc, WE_P2G__pc, WE_Gifting_Capacity_Max_Score__pc, WE_Gifting_Capacity_Score__pc, WE_Gifting_Capacity__pc, WE_Charitable_Donations_Max_Score__pc, WE_Charitable_Donations_Score__pc, WE_Charitable_Donations__pc, WE_Total_Political_Donations_Max_Score__pc, WE_Total_Political_Donations_Score__pc, WE_Total_Political_Donations__pc, WE_Estimated_Annual_Donations_Max_Score__pc, WE_Estimated_Annual_Donations_Score__pc, WE_Estimated_Annual_Donations__pc, WE_Locations__pc, WE_Num_Properties_Owned__pc, WE_Total_Real_Estate_Max_Score__pc, WE_Total_Real_Estate_Score__pc, WE_Total_Real_Estate__pc, WE_Vehicle__pc, WE_Vehicle_Value__pc, WE_Jobs__pc, WE_Last_Search__pc, WE_Last_Update__pc, WE_Full_Profile_Details__pc, WE_Marital_Status__pc, WE_Search__pc, WE_Update__pc FROM Account where Id  IN: Trigger.newMap.KeySet()];
             for(Account objAccount : accList)
             {
                if((objAccount.BillingStreet != null && objAccount.BillingCity != null && objAccount.BillingState != null && objAccount.BillingStateCode != null && objAccount.BillingPostalCode != null && objAccount.LastName != null && objAccount.FirstName != null) || (objAccount.PersonEmail != null) || (objAccount.phone != null) || (objAccount.PersonMobilePhone != null) || (objAccount.PersonHomePhone != null) && (objAccount.WE_Enhance__c)) 
                 {
                  { 
                  if(objAccount.IsPersonAccount)
                    accIdSet.add(objAccount.Id);
                  }
                }
             }
             if(accIdSet.size() > 0 )
             {
                 if(accIdSet.size() >= 5 )
                 {
                     WE_PA_NewlyImportedRecordForUpdate_Batch b= new WE_PA_NewlyImportedRecordForUpdate_Batch(accIdSet,'account',null,'Trigger','Insert');
                     Database.executeBatch(b,5);
                 }
                 else
                 {
                     WE_UtilCommon.processAndUpdateWealthEngineDataForTrigger(accIdSet,'account','Trigger');
                 }
                 
             }
             
             
        }
    }
    
    else if(Trigger.isAfter && Trigger.isUpdate )
    {
        System.debug('*****Inside WE Account Update Trigger****');
        System.debug('*****WE_RecusionWrapper.runPersonAccount****'+WE_RecusionWrapper.runPersonAccount);
        List<Wealth_Engine_Setting__c> wealthEngineSettingList = [SELECT Id, Name, APIKey__c, AddressURL__c, PhoneURL__c, EmailURL__c FROM Wealth_Engine_Setting__c];
        List <WE_Process__c> weProcessList  = [SELECT Id, Name, WE_Process_Sample_Data__c,WE_On_Demand_Process__c, WE_Batch_Process__c, WE_Account_Batch_Process__c FROM WE_Process__c];
        System.debug('*******WE_RecusionWrapper.runPersonAccount*******'+WE_RecusionWrapper.runPersonAccount);
        if( WE_RecusionWrapper.runPersonAccount=true && weProcessList[0].WE_Account_Batch_Process__c  == false && weProcessList[0].WE_On_Demand_Process__c == false && wealthEngineSettingList.size() > 0)
        {
             WE_RecusionWrapper.runPersonAccount=false;
             List<Sobject> sobjListData = new List<Sobject>();
             List<Sobject> updateList= new List<Sobject> ();
             Set<String> accIdSet = new Set<String>();
             Map<String,String>  valueFiledUpdateListMap = new Map<String,String>();
             for(Account acc : Trigger.New)
             {
                if(acc.IsPersonAccount)
                {
                  if((acc.BillingStreet != null && acc.BillingCity != null && acc.BillingState != null && acc.BillingStateCode != null && acc.BillingPostalCode != null && acc.LastName != null && acc.FirstName != null) || (acc.PersonEmail != null) || (acc.phone != null) || (acc.PersonMobilePhone != null) || (acc.PersonHomePhone != null) && (acc.WE_Enhance__c))
                  {
                     List<Integer> changedIndexFieldList = new List<Integer>();
                     Account oldAccount =  Trigger.OldMap.get(acc.Id);
                     String item = '';
                     if((acc.BillingStreet  != oldAccount.BillingStreet) || (acc.BillingCity != oldAccount.BillingCity ) ||(acc.BillingState != oldAccount.BillingState) || (acc.BillingStateCode != oldAccount.BillingStateCode ) || (acc.BillingPostalCode != oldAccount.BillingPostalCode ) || (acc.LastName != oldAccount.LastName) || (acc.FirstName != oldAccount.FirstName))
                     {
                         changedIndexFieldList.add(1);
                         accIdSet.add(acc.Id);
                         item = item + '1,';
                     }
                    if(acc.PersonEmail != oldAccount.PersonEmail)
                    {
                        changedIndexFieldList.add(2);
                        accIdSet.add(acc.Id);
                        item = item + '2,';
                    }
                    if(acc.phone != oldAccount.phone)
                    {
                        changedIndexFieldList.add(3);
                        accIdSet.add(acc.Id);
                        item = item + '3,';
                    }
                    if(acc.PersonMobilePhone != oldAccount.PersonMobilePhone)
                    {
                        changedIndexFieldList.add(4);
                        accIdSet.add(acc.Id);
                        item = item + '4,';
                    }
                    if(acc.PersonHomePhone != oldAccount.PersonHomePhone)
                    {
                        changedIndexFieldList.add(5);
                        accIdSet.add(acc.Id);
                        item = item + '5,';
                    } 
                    if(item != '')
                    {
                         if(item.contains(','))
                         {
                              item = item.removeEnd(',');
                         }
                        valueFiledUpdateListMap.put(acc.Id,item);
                    }
                 }
                }
                 
                 
             }
             System.debug('*****accIdSet****'+accIdSet);
             System.debug('*****valueFiledUpdateListMap****'+valueFiledUpdateListMap);
             if(accIdSet.size() > 0 && valueFiledUpdateListMap != null)
             {
                 if(accIdSet.size() > =5  )
                 {
                      WE_PA_NewlyImportedRecordForUpdate_Batch b= new WE_PA_NewlyImportedRecordForUpdate_Batch(accIdSet,'account',valueFiledUpdateListMap,'Trigger','Update');
                      Database.executeBatch(b,5);
                 }
                 else
                 {
                    WE_UtilCommon.ProcessAndUpdateWealthEngineDataDuringUpdateTrigger(accIdSet,'account',valueFiledUpdateListMap,'Trigger'); 
                 }
                
                //WE_UtilCommon.ProcessAndUpdateWealthEngineDataDuringUpdateTrigger(accIdSet,'account',valueFiledUpdateListMap,'Trigger');
             }
        }
        else
        {
            weProcessList  = [SELECT Id, Name, WE_Process_Sample_Data__c,WE_On_Demand_Process__c, WE_Batch_Process__c, WE_Account_Batch_Process__c FROM WE_Process__c];
            weProcessList[0].WE_On_Demand_Process__c = false;
            update weProcessList;
        }
        
    }
}

 
Team, 

I have created a button that will allow you to add attachments from the notes and attachments section before sending out an email. Code coverage is 95% in sandbox but am getting the below errors in production. 

Getting the below erros when running my test class in production: 
System.QueryException: List has no rows for assignment to SObject 
Stack Trace: Class.OpenEscrowBttn.doEditEmail: line 100, column 1 Class.TestOpenEscrowBttn.TestOpenEscrowBttn: line 58, column 1

Can someone please take a look and see what I am doing wrong?

Apex Class: 
public with sharing class OpenEscrowBttn {
    public Id targetId {get;set;}
    public String AdditionalEmailId { get;set;}
    public String[] selDocs = new String[]{};   
    //public Transient List<Attachment> optyDocs {get;set;} 
    Id TempFolderId;
    Id  TempTemplateId;
    String TemplateName;
    public Transient Attachment[] oldAttachments;
    public Integer attSize {get;set;}
    public List<DocItem> OpptyDocs {get;set;}    

    public OpenEscrowBttn(ApexPages.StandardController controller) {      
        Id optyId = ApexPages.currentPage().getParameters().get('optyId');
        Id acctId = ApexPages.currentPage().getParameters().get('acctId');
        if (optyId != Null) {
            targetId = optyId;
            List<Opportunity>  oppObj = [SELECT Id, AccountId, Name FROM Opportunity where Id = :optyId ];
            System.debug('******oppObj******'+oppObj);
            if(oppObj.size() > 0)
            {
               List<Account> accObj =[SELECT Id, AnnualRevenue, Appointment_Changes__c, AdditionalEmails__c FROM Account where Id = :oppObj[0].AccountId];
                System.debug('******accObj ******'+accObj );
                if(accObj.size()> 0)
                {
                  if(accObj[0].AdditionalEmails__c != null)
                  {
                    AdditionalEmailId = accObj[0].AdditionalEmails__c;
                  }
                }
            }
        } else if (acctId != Null){
          targetId = acctId;
          List<Account> accObj =[SELECT Id, AnnualRevenue, Appointment_Changes__c, AdditionalEmails__c FROM Account where Id = :acctId ];
          System.debug('******accObj ******'+accObj );
          if(accObj.size()> 0)
           {
             if(accObj[0].AdditionalEmails__c != null)
               {
                    AdditionalEmailId = accObj[0].AdditionalEmails__c;
               }
           }
          
        } else {
            targetId = Null;
        }
  
        system.debug('\n\n targetId = '+targetId);
    
        attSize = 0;
        //optyDocs = new List<Attachment>();
    set<Id> RelatedContracts = new  set<Id>();        
        if ( acctId != Null) {          
          for (Contract ct : [select id from Contract where accountId =:acctId]) {
            RelatedContracts.add(ct.id);
          }
        } 
          
        if (targetId != null) {
            OpptyDocs = new List<DocItem>();
            for (Attachment at : [Select id, Name, Body, ParentId from Attachment where (ParentId = :targetId OR ParentId in :RelatedContracts)]) {                   
                //optyDocs.add(at);
                OpptyDocs.add(new DocItem(at.Id,false,at.Name)); 
                attSize++;
            } 
            //attSize = optyDocs.size();
            if (attSize <= 0) {             
                //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'No attachments found!'));
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No attachments found for this opportunity!'));
            }          
        }           
    }

    public PageReference doEditEmail(){

        Folder TFolderId = [Select id from Folder where DeveloperName = 'Ward_Residential_Workflow_Templates' limit 1];      
        TempFolderId = TFolderId.Id;
                    
        TemplateName = 'Ke Kilohana Open Escrow Email';      
        EmailTemplate[] Temp = [Select id from EmailTemplate where Name = :TemplateName and FolderId = :TempFolderId limit 1];
                    
        if ( Temp.size() > 0 ) {
            TempTemplateId = Temp[0].id;
/*
        } else {
            EmailTemplate[] Temp1 = [Select id from EmailTemplate where FolderId = :TempFolderId limit 1];
            if ( Temp1.size() > 0 ) {
                TempTemplateId = Temp1[0].id;
            }
*/                       
        }       
        
        //Delete All current Attachments
        oldAttachments = [select id from Attachment where ParentId = :TempTemplateId ];
        
        if ( oldAttachments.size() > 0 ) {    
            delete oldAttachments;
        }        

        EmailTemplate t = [Select id, FolderId, TemplateType, HtmlValue, subject, body from EmailTemplate where Id  = :TempTemplateid];
        
        List<Attachment> nTlist =new  list<Attachment>();
        //Id attId = selDocs[0];
        
        set<id> aList= new set<id>();
        for (DocItem d: OpptyDocs) {
            system.debug('lCheck:'+d.lcheck);
          if ( d.lcheck ) {
            aList.add(d.DocId);
            //numDoc++;
          }
        }
        
        if (aList.size() == 0) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No attachments selected!'));
            return null;
        } else {
                        
            Attachment tnew;
                    
            Attachment[] tList = [Select Name, Body, ParentId from Attachment where id IN :aList];
            
            for (Attachment o: tList) {
                tnew = new Attachment();
                //tnew.Name = '(From Attachments)-'+o.name;
                tnew.Name = o.name;
                tnew.Body = o.Body;
                tnew.ParentId = t.id;
                system.debug ('\n\n parent '+t.id );
                nTlist.add(tnew);           
            }       
            
            insert nTlist;
            
            /*
            set<id> sTlist = new set<id>();
            
            for (Attachment n: nTlist) {
              sTlist.add(n.id);
            }          
            */
            
            //PageReference pg = new PageReference('/_ui/core/email/author/EmailAuthor?id=' + attId + '&retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&p2_lkid=&template_id='+t.id+'&new_template=1'); 
            //PageReference pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&rtype=003' + '&p2_lkid=&template_id='+t.id+'&new_template=1');
            PageReference pg;
            if(AdditionalEmailId != null)
            {
              pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId +'&p24=' +AdditionalEmailId+'&rtype=003' + '&p2_lkid=003i000003hY6XKAA0' + '&p2_lkid=&template_id='+t.id+ '&p4=dmoreira@tghawaii.com,jnelson@tghawaii.com,abastatas@tghawaii.com' +'&new_template=1');
            } 
            
            else 
            {
              pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&rtype=003' + '&p2_lkid=&template_id='+t.id+'&new_template=1');
            } 
              
            
            pg.setRedirect(true);
            return pg;
        }       
    }
        
    public PageReference doCancel(){
        PageReference pg = new PageReference('/'+targetId); 
        pg.setRedirect(true);
        return pg;
    }  
    
    public class DocItem  {    // Referral Request Wrapper
        public id DocId {get; set;}
        public boolean lcheck {get; set;}
        public string DocName {get; set;} 
         
           
        public DocItem (id i, boolean c, string s)
            {
                DocId = i;
                lcheck = c;  
                DocName =s; 
            }
    }
      
}
VF Page: 
 
<apex:page id="thePage" standardController="Opportunity" extensions="OpenEscrowBttn" tabStyle="Opportunity">
    <apex:messages style="color:red; font-weight:bold; text-align:center;" />
    <apex:form id="theForm">  
        <apex:pageBlock id="PB" title="Send Email">
            <apex:pageBlockButtons >
                <apex:commandButton value="Edit Email and Send" action="{!doEditEmail}" rendered="{!IF(attSize>0, true, false)}"/>                     
                <apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>            
            </apex:pageBlockButtons>        
            <apex:pageblockSection id="PBS1" title="Select Attachments" columns="1">
                  <apex:pageBlockTable value="{!OpptyDocs}" var="s"  >
                        <apex:column width="10%">
                             <apex:facet name="header">Select</apex:facet>
                             <apex:inputcheckbox value="{!s.lcheck}"/> 
                        </apex:column>
                        <apex:column width="30%"> 
                            <apex:facet name="header">Attachments</apex:facet>
                            {!s.DocName}
                        </apex:column>
                  </apex:pageBlockTable>                           
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Test Class: 
 
@isTest
public with sharing class TestOpenEscrowBttn {
  public static testMethod void TestOpenEscrowBttn(){
    Schema.DescribeSObjectResult acctSchema = Schema.SObjectType.Account; 
    Map<String,Schema.RecordTypeInfo> AccountRecordTypeInfo = acctSchema.getRecordTypeInfosByName(); 
    Id acctRTId = AccountRecordTypeInfo.get('Ward Residential Buyers').getRecordTypeId();
    
    Schema.DescribeSObjectResult propSchema = Schema.SObjectType.Property__c; 
    Map<String,Schema.RecordTypeInfo> PropertyRecordTypeInfo = propSchema.getRecordTypeInfosByName();     
    Id propRTId = PropertyRecordTypeInfo.get('Ward Residential').getRecordTypeId();
    
    Schema.DescribeSObjectResult spaceSchema = Schema.SObjectType.Space__c; 
    Map<String,Schema.RecordTypeInfo> SpaceRecordTypeInfo = spaceSchema.getRecordTypeInfosByName();     
    Id spaceRTId = SpaceRecordTypeInfo.get('Ward Residential').getRecordTypeId();

    
    Property__c prop = new Property__c(recordtypeid=propRTId, Name='Test Property');
    insert prop;

    Space__c spaces = new Space__c(recordtypeid=spaceRTId, Name='Test Ward Residential', property__c = prop.id);
    insert spaces;
    
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    User thisUser = new User(Alias = 'tCook', Email='tatianaCooke@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='tCooke91@testorg.com'); //Changed

    RecordType personAccountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Ward Residential Buyers' and SObjectType = 'Account']; 

    System.runAs ( thisUser ) { 
   WE_Process__c obj=new WE_Process__c();
   obj.Name='test';
   insert obj; 

   Account acc = new Account(); 
   acc.FirstName='John'; 
   acc.LastName='DoeTest1'; 
   acc.PersonEmail = 'doetest1@test.com';
   acc.RecordTypeId = personAccountRecordType.Id; //Changed
   insert acc; 

    Opportunity optyId = new Opportunity();
    optyId.Name = 'optyId';
    optyId.AccountId = acc.Id;
    optyId.Unit_Number__c  = spaces.id;
    optyId.Financing_Type__c = 'Cash Buyer';
    optyId.Purchaser_Type__c  = 'Person(s)';
    optyId.CloseDate = System.today();
    optyId.StageName ='S1: Ready to Contract';
    optyId.Reason_for_Purchase__c ='Primary Residence';
    optyId.Nature_of_Tenancy__c ='Severalty';
    optyId.Sale_Type__c  ='Founder';

    INSERT optyId;
    
    ApexPages.currentPage().getParameters().put('optyId', optyid.id);                
    ApexPages.StandardController sc = new ApexPages.StandardController(optyId);
    OpenEscrowBttn ctrl = new OpenEscrowBttn(sc);
    
    ctrl.doEditEmail();
    
    ctrl.doCancel();
    
    Opportunity optyId1 = new Opportunity(Name='optyId', AccountId=acc.Id, Unit_Number__c=spaces.Id, Financing_Type__c='Cash Buyer', Purchaser_Type__c='Person(s)', Reason_for_Purchase__c='Primary Residence', Nature_of_Tenancy__c='Joint Tenants', Sale_Type__c='Direct', CloseDate=date.today()+10, StageName='S1: Ready to Contract');
    insert optyId1;    
    
        Attachment attach=new Attachment();     
      attach.Name='Software Eval.txt';
      Blob bodyBlob=Blob.valueOf('Software Eval');
      attach.body=bodyBlob;
        attach.parentId=optyId.id;
        insert attach;    
        
    ApexPages.currentPage().getParameters().put('optyId', optyId.id);
    ApexPages.StandardController sc1 = new ApexPages.StandardController(optyId);    
    OpenEscrowBttn ctrl1 = new OpenEscrowBttn(sc1);
    
    System.debug('***attSize: '+ctrl1.attSize);
    System.debug('***optyDocsSize: '+ctrl1.opptyDocs.size());
    ctrl1.OpptyDocs[0].lCheck = true;
    
    ctrl1.doEditEmail();
    
    ApexPages.currentPage().getParameters().put('optyId', null);                
    ApexPages.currentPage().getParameters().put('acctId', null);                
    ApexPages.StandardController sc2 = new ApexPages.StandardController(acc);
    OpenEscrowBttn ctrl2 = new OpenEscrowBttn(sc2);
        
    //ctrl2.doEditEmail();
    
    ctrl2.doCancel();

    ApexPages.currentPage().getParameters().put('optyId', null);                
    ApexPages.currentPage().getParameters().put('acctId', acc.Id);                
    ApexPages.StandardController sc3 = new ApexPages.StandardController(acc);
    OpenEscrowBttn ctrl3 = new OpenEscrowBttn(sc3);
        
    ctrl3.doEditEmail();
    
        
  }
}
}


 
Team, 

Am trying to use the google gauge functionality to bring in a guage chart on an account. I it to show the percent compelete of a record. I am using this link as a reference. http://salesforceselflearn.blogspot.in/

For some reason the visualforce page component is not showing up in the page layout of the Account. I have created the class and the visualforce page in our sandbox. Below is the code. 

Class
 
public class googleChartController {

    Public String acctId {get; set;}
    Public String query {get;set;}
    Private Decimal TotalFieldCount {get;set;}
    Private Decimal FilledFieldCount {get;set;}
    Public Decimal TotalPercentage {get;set;}
    
    Public GoogleChartController(ApexPages.StandardController controller){
        acctId = controller.getRecord().id;
        fetch();
    }
    
    public void fetch() {
        String SObjectApiName = 'Account';
        Map<String, Schema.SObjectType> objectMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = objectMap.get(SObjectApiName).getDescribe().fields.getMap();
        
        String fieldString = '';
        for (String fieldName : fieldMap.keyset())
        {
            if(fieldString == '')
            {
                fieldString = FieldName; 
                } else{
                    fieldString = FieldString + ',' + fieldName;
                }
            }
        query = 'Select' + fieldString + 'from' + SObjectApiName + 'WHERE id = :accID' ;
        Account accountRecord = Database.query(query);
        TotalFieldCount = 0;
        FilledFieldCount = 0;
        for (String fieldName : fieldMap.keyset())
        {
            TotalFieldCount++;
            if(accountRecord.get(fieldName) != null || string.isBlank(fieldName))
            {
                FilledFieldCount++;
            }
        }
        TotalPercentage = (FilledFieldCount/TotalFieldCount) * 100;
        TotalPercentage = TotalPercentage.setScale(0);
        }
}

Visualforce Page
 
<apex:page > standardController="Account" extensions="googleChartController">
    <head>
        <script type = "text/javascript" src = "https://www.google.com/jsapi"> </script>
        <script type = "text/javascript">
            google.load("visualization", "1", {packages: ["guage"]});
            google.setOnLoadCallback (drawChart);
            
            
           function drawChart() {
                var totalFields = {TotalPercentage};
                var data= google.visualization.arrayToDataTable([
                    ['Label', 'Value'],
                    [' % ', totalFields],
                    ]);                
                var options = {
                    width: 400, height: 200,
                    redFrom: 0, redTo: 75,
                    greenFrom: 75, greenTo: 100,
                    minorTricks: 10
               };
               
            var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
            chart.draw(data, options);
            
          }
       </script>
   </head>
   <body>
       <div id="chart_div" style="width: 400px; height: 200px;"></div>
   </body>
</apex:page>


Apprecaite any help. 

Regards, 

TC
 
Team, 

keep getting errors when trying to insert an account for a test class. 

Error: 
System.AssertException: Assertion Failed: Expected: 2, Actual: 1

New to coding so don't understand the error. I am trying to set up trigger that creates a change log record every time the person account email is changed. 
@isTest
private class TestPersonAccountChangeLog {

    static testMethod void LogPersonAccountChangeTest() {
        
        RecordType personAccountRecordType =  [SELECT Id FROM RecordType WHERE Name = 'Ward Residential Buyers' and SObjectType = 'Account'];
        User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
        System.runAs ( thisUser ) {
        
            WE_Process__c obj=new WE_Process__c();
    obj.Name='test';
    insert obj;
    
            Account a = NEW Account();
            a.FirstName='John';
            a.LastName='DoeTest1';
            a.PersonEmail = 'doetest1@test.com';
            a.RecordType = personAccountRecordType;
            insert a;
            
    System.assertEquals(2, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :A.PersonEmail AND pi__ObjectState__c = 1]);
    
    delete A;
    System.assertEquals(0, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :A.PersonEmail AND pi__ObjectState__c = 2]);
    
    undelete A;
    System.assertEquals(1, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :A.PersonEmail AND pi__ObjectState__c = 3]);
    }

}}

 
Team

I have a custom object for which I have made visualforce buttons that adds attachments to the notes and attachments section. 

The parent page is a custom object. NOT a visualforce page. I know somehow I need to factor in two different domains. = /

Can someone help me with the code?  So far it inserts the record but I have to manually refresh the page to see the attachment. 

User-added image
Visualforce Page
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
         <apex:actionFunction name="reloadparent" action="{!reload}" />  
    </apex:form>
</apex:page>
Class
Team

I have a custom object for which I have made visualforce buttons that adds attachments to the notes and attachments section. 

The parent page is a custom object. NOT a visualforce page. I know somehow I need to factor in two different domains. = /

Can someone help me with the code?  So far it inserts the record but I have to manually refresh the page to see the attachment. 



Visualforce Page 
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
         <apex:actionFunction name="reloadparent" action="{!reload}" />  
    </apex:form>
</apex:page>

Class

public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         insert a;
        PageReference parentPage = new PageReference('/' + accid); 
        parentPage.setRedirect(true); 
        return parentPage;
    }   

}

Appreciate any help!

I found something online that might be able to help but I haven't been able to make it work.


If you do not want to add any Javascript in parent window and you have some parameter that is passed to popup window, you can reload parent window using the below script,
function closeWindow(){     
            window.opener.location.href="/{!$CurrentPage.parameters.id}";
            window.top.close();
   }

In my case I am passing Id of the record as parameter to the popup window. Make sure that "Developer Mode" is not enabled. If it is enabled, it will not work.

Link tgo site http://salesforce.stackexchange.com/questions/46192/how-to-refresh-the-parent-window-after-opening-a-pop-up-window-from-inline-page/46195#46195
Code for refreshing a visual force page to the parent object upon hitting save. I created a visualforce page that attaches documents in the notes and attachement section, however it doesn't ALWAYS work. 

Sometimes when I hit save it does refresh the parent record and show me the attached document in the notes and attachement section and sometimes I have to manually refresh the page to see the recod. 

Can someone help me with the below code?

Visualforce Page
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
         <apex:actionFunction name="reloadparent" action="{!reload}" />  
    </apex:form>
</apex:page>

class
 
public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         /* insert the attachment */
         insert a;
        PageReference parentPage = new PageReference('/' + accid); 
        parentPage.setRedirect(true); 
        return parentPage;
    }   
    
    
 public void reload(){  
}
}

Please help!
Code for refreshing a visual force page to the parent object upon hitting save. I created a visualforce page that attaches documents in the notes and attachement section, however it doesn't ALWAYS work. 

Sometimes when I hit save it does refresh the parent record and show me the attached document in the notes and attachement section and sometimes I have to manually refresh the page to see the recod. 

Can someone help me with the below code?

Visualforce Page
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
    </apex:form>
</apex:page>


Class
public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         /* insert the attachment */
         insert a;
        return NULL;
    }   

}

Please help!

 
Team, 

I thought this trigger was working and I dont know how it is not now. When the secondary owner lookup field is populated on the opportunity I need it to create an opportunity with read write access. 

it is only giving the users Read Only access. 
Appreciate any help
trigger OTOpportunityTrigger on Opportunity (before update) {
    List<OpportunityTeamMember> listOpptyTeamMem = new List<OpportunityTeamMember>();
    Set<Id> OpptyIdSet  =  new Set<Id>();
    
    for(Opportunity oppty : trigger.New)
    {
        //Checking Oppty SecondaryOwner 
        if(oppty.Secondary_Owner__c != null)
        {
            OpportunityTeamMember OTM = new OpportunityTeamMember();
            OTM.OpportunityId = oppty.Id;
            OTM.TeamMemberRole = 'Secondary Owner'; 
            OTM.UserId = oppty.Secondary_Owner__c;
            listOpptyTeamMem.add(OTM);
        } 
    }
        
       
        if(listOpptyTeamMem.size() > 0)
        {
        insert listOpptyTeamMem;
                
        // get all of the team members' sharing recordsPost to Community
        List<OpportunityShare> shares = [select Id, OpportunityAccessLevel, 
          RowCause from OpportunityShare where OpportunityId IN : OpptyIdSet
          and RowCause = 'Team'];
 
        // set all team members access to read/write
        for (OpportunityShare share : shares) 
          share.OpportunityAccessLevel = 'Edit';
 
        update shares;
        }

}
Team, 

I thought this trigger was working and I dont know how it is not now. When the secondary owner lookup field is populated on the opportunity I need it to create an opportunity with read write access. 

it is only giving the users Read Only access. 

Appreicate any help. 
trigger OTOpportunityTrigger on Opportunity (before update) {
    List<OpportunityTeamMember> listOpptyTeamMem = new List<OpportunityTeamMember>();
    Set<Id> OpptyIdSet  =  new Set<Id>();
    
    for(Opportunity oppty : trigger.New)
    {
        //Checking Oppty SecondaryOwner 
        if(oppty.Secondary_Owner__c != null)
        {
            OpportunityTeamMember OTM = new OpportunityTeamMember();
            OTM.OpportunityId = oppty.Id;
            OTM.TeamMemberRole = 'Secondary Owner'; 
            OTM.UserId = oppty.Secondary_Owner__c;
            listOpptyTeamMem.add(OTM);
        } 
    }
        
       
        if(listOpptyTeamMem.size() > 0)
        {
        insert listOpptyTeamMem;
                
        // get all of the team members' sharing recordsPost to Community
        List<OpportunityShare> shares = [select Id, OpportunityAccessLevel, 
          RowCause from OpportunityShare where OpportunityId IN : OpptyIdSet
          and RowCause = 'Team'];
 
        // set all team members access to read/write
        for (OpportunityShare share : shares) 
          share.OpportunityAccessLevel = 'Edit';
 
        update shares;
        }

}

 
Team,
 
So I have an issue detailed below, I contacted docusign to see if they could help and got a very bland "call salesforce" 

Error: Test coverage of selected Apex Trigger is 0%, at lease 1% test coverage is required.  

I have the following code coverage errors in org (screenshot below). How do I fix these? Its preventing me from other deploying code due to coverage. 

User-added image
Team, 

I have the following trigger on my person accounts and am trying to run the below test class with the following error. 
Error: " System.ListException: List index out of bounds: 0 "  Saying its in line 3570 of my test class (which doesn't exsit)

Appreciate any guidance.

Trigger:
 
trigger LogPersonAccountChange on Account (before delete, after insert, after undelete)
{
  List<pi__ObjectChangeLog__c> logs = new List<pi__ObjectChangeLog__c>(); 

  if (Trigger.new != null) {
    for (Account account : Trigger.new) {

      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();
        log.pi__ObjectFid__c = Account.PersonContactId;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;

        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;

        }
        logs.add(log);
      }
    }
  } else if (Trigger.old != null) {
    for (Account account : Trigger.old) {
      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();

        log.pi__ObjectFid__c = Account.PersonContactId

        ;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;
        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;
        }
        logs.add(log);
      }
    }
  }

  if (logs.size() > 0) {

    insert logs;
  }
}

Test Class: 
 
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class TestPersonAccountChangeLog {

    static testMethod void LogPersonAccountChangeTest() {
    	
String RecTypeId= [select Id from RecordType where (Name='Ward Residential Buyers') and (SobjectType='Account')].Id;
    	   
    WE_Process__c obj=new WE_Process__c();
    obj.Name='test';
    insert obj;
     
    Account account = new Account();    
    account.FirstName='Test Acc';
    account.LastName='Last Name';
    Account.PersonEmail = 'abc@123.com';
    account.RecordTypeID=RecTypeId;
    insert Account;

    pi__ObjectChangeLog__c  p1 = new pi__ObjectChangeLog__c (); 

    p1.name = 'fgasfsa'; 
    p1.pi__ObjectState__c = 1; 
    p1.pi__ObjectEmail__c = Account.PersonEmail; 
    p1.pi__ObjectFid__c = 'Sample Fid'; 
    p1.pi__ObjectType__c = 1; 
    Insert p1; 

    System.assertEquals(1, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 1]);
    delete Account;
    System.assertEquals(0, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 2]);
    undelete Account;
    System.assertEquals(1, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c =:Account.PersonEmail AND pi__ObjectState__c = 1]);
    }
}



 
Team, 

I have the following trigger on my person accounts and am trying to run the below test class with the following error. 
Error: " System.ListException: List index out of bounds: 0 "  Saying its in line 3570 of my test class (which doesn't exsit)

Appreciate any guidance.

Trigger:
trigger LogPersonAccountChange on Account (before delete, after insert, after undelete)
{
  List<pi__ObjectChangeLog__c> logs = new List<pi__ObjectChangeLog__c>(); 

  if (Trigger.new != null) {
    for (Account account : Trigger.new) {

      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();
        log.pi__ObjectFid__c = Account.PersonContactId;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;

        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;

        }
        logs.add(log);
      }
    }
  } else if (Trigger.old != null) {
    for (Account account : Trigger.old) {
      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();

        log.pi__ObjectFid__c = Account.PersonContactId

        ;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;
        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;
        }
        logs.add(log);
      }
    }
  }

  if (logs.size() > 0) {

    insert logs;
  }
}

Test class: 
 
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class TestPersonAccountChangeLog {

    static testMethod void LogPersonAccountChangeTest() {
    	
String RecTypeId= [select Id from RecordType where (Name='Ward Residential Buyers') and (SobjectType='Account')].Id;
    	   
    WE_Process__c obj=new WE_Process__c();
    obj.Name='test';
    insert obj;
     
    Account account = new Account();    
    account.FirstName='Test Acc';
    account.LastName='Last Name';
    Account.PersonEmail = 'abc@123.com';
    account.RecordTypeID=RecTypeId;
    insert Account;

    pi__ObjectChangeLog__c  p1 = new pi__ObjectChangeLog__c (); 

    p1.name = 'fgasfsa'; 
    p1.pi__ObjectState__c = 1; 
    p1.pi__ObjectEmail__c = Account.PersonEmail; 
    p1.pi__ObjectFid__c = 'Sample Fid'; 
    p1.pi__ObjectType__c = 1; 
    Insert p1; 

    System.assertEquals(1, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 1]);
    delete Account;
    System.assertEquals(0, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 2]);
    undelete Account;
    System.assertEquals(1, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c =:Account.PersonEmail AND pi__ObjectState__c = 1]);
    }
}


 
Team, 

Pretty new to the development side of things and need help on the following class. It a class with a visualforce page (Button) that adds attachements to the notes and attachements section and refreshes to the parent page when ckick save. 

For some reason the test class is not running my class and achieving any code coverage. 

Appreciate any help. 

Below is the test class: 
public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         /* insert the attachment */
         insert a;
        return NULL;
    }   

}

Test class:
@isTest
public class Test2attachmentsample {
  private static testMethod void attachmentsampletest() {


    Tenant_Coordination__C TC = new Tenant_Coordination__C(Name ='Test');
    insert TC; 
    
     Attachment attach=new Attachment();    
     attach.Name='Unit Test Attachment';
     Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
     attach.body=bodyBlob;
     attach.parentId=TC.id;
     insert attach;

     List<Attachment> attachments=[select id, name from Attachment where parent.id=: TC.Id];
     System.assertEquals(1, attachments.size());
    }
}

 
Team, 

I have the following trigger on my person accounts and am trying to run the below test class with the following error. 

Error: "System.AssertException: Assertion Failed: Expected: 0, Actual: 1"  on line 40 of my test class.

Appreciate any guidance.

Trigger:
trigger LogPersonAccountChange on Account (before delete, after insert, after undelete)
{
  List<pi__ObjectChangeLog__c> logs = new List<pi__ObjectChangeLog__c>(); 

  if (Trigger.new != null) {
    for (Account account : Trigger.new) {

      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();
        log.pi__ObjectFid__c = Account.PersonContactId;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;

        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;

        }
        logs.add(log);
      }
    }
  } else if (Trigger.old != null) {
    for (Account account : Trigger.old) {
      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();

        log.pi__ObjectFid__c = Account.PersonContactId

        ;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;
        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;
        }
        logs.add(log);
      }
    }
  }

  if (logs.size() > 0) {

    insert logs;
  }
}
Here is the test class:
 
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class TestPersonAccountChangeLog {

    static testMethod void LogPersonAccountChangeTest() {
    	
String RecTypeId= [select Id from RecordType where (Name='Ward Residential Buyers') and (SobjectType='Account')].Id;
    	   
    WE_Process__c obj=new WE_Process__c();
    obj.Name='test';
    insert obj;
     
    Account account = new Account();    
    account.FirstName='Test Acc';
    account.LastName='Last Name';
    Account.PersonEmail = 'abc@123.com';
    account.RecordTypeID=RecTypeId;
    insert Account;
        
        System.assertEquals([SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 1], 1);
        delete Account;
        System.assertEquals([SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 2], 1);
        undelete Account;
        System.assertEquals([SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 3], 1);
    }

}


 
Team, 

New to development. Please please help, need this working as soon as possible. Can somone look at the error and code below.

I created a button on the opportunity which can attach a file from the notes and attachment and send an email with a template. 

Getting below error when trying to deploy to production. 

System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.OpenEscrowBttn.<init>: line 18, column 1 Class.TestOpenEscrowBttn.TestOpenEscrowBttn: line 57, column 1


Test Class
@isTest
public with sharing class TestOpenEscrowBttn {
  public static testMethod void TestOpenEscrowBttn(){
    Schema.DescribeSObjectResult acctSchema = Schema.SObjectType.Account; 
    Map<String,Schema.RecordTypeInfo> AccountRecordTypeInfo = acctSchema.getRecordTypeInfosByName(); 
    Id acctRTId = AccountRecordTypeInfo.get('Ward Residential Buyers').getRecordTypeId();
    
    Schema.DescribeSObjectResult propSchema = Schema.SObjectType.Property__c; 
    Map<String,Schema.RecordTypeInfo> PropertyRecordTypeInfo = propSchema.getRecordTypeInfosByName();     
    Id propRTId = PropertyRecordTypeInfo.get('Ward Residential').getRecordTypeId();
    
    Schema.DescribeSObjectResult spaceSchema = Schema.SObjectType.Space__c; 
    Map<String,Schema.RecordTypeInfo> SpaceRecordTypeInfo = spaceSchema.getRecordTypeInfosByName();     
    Id spaceRTId = SpaceRecordTypeInfo.get('Ward Residential').getRecordTypeId();
    Property__c prop = new Property__c(recordtypeid=propRTId, Name='Test Property');
    insert prop;

    Space__c spaces = new Space__c(recordtypeid=spaceRTId, Name='Test Ward Residential', property__c = prop.id);
    insert spaces;
    
    Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    User thisUser = new User(Alias = 'tCook', Email='tatianaCooke@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='tCooke91@testorg.com'); //Changed

   System.runAs ( thisUser ) { 
   WE_Process__c obj=new WE_Process__c();
   obj.Name='test';
   insert obj; 
        
        Account acc = new Account(recordtypeid=acctRTId, FirstName='First Name', LastName='Last Name', Phone='111-111-1111', PersonEmail='first.last@test.com', type='Prospect');
        insert acc;

    Opportunity opty = new Opportunity(Name='Test Opty', AccountId=acc.Id, Unit_Number__c=spaces.Id, Financing_Type__c='Cash Buyer', Purchaser_Type__c='Person(s)', Reason_for_Purchase__c='Primary Residence', Nature_of_Tenancy__c='Joint Tenants', Sale_Type__c='Direct', CloseDate=date.today()+10, StageName='S1: Ready to Contract');
    insert opty;    
    
    ApexPages.currentPage().getParameters().put('optyId', opty.id);                
    ApexPages.StandardController sc = new ApexPages.StandardController(opty);
    OpenEscrowBttn ctrl = new OpenEscrowBttn(sc);
    
    ctrl.doEditEmail();
    
    ctrl.doCancel();
    
    Opportunity opty1 = new Opportunity(Name='Test Opty 1', AccountId=acc.Id, Unit_Number__c=spaces.Id, Financing_Type__c='Cash Buyer', Purchaser_Type__c='Person(s)', Reason_for_Purchase__c='Primary Residence', Nature_of_Tenancy__c='Joint Tenants', Sale_Type__c='Direct', CloseDate=date.today()+10, StageName='S1: Ready to Contract');
    insert opty1;    
    
        Attachment attach=new Attachment();     
      attach.Name='Software Eval.txt';
      Blob bodyBlob=Blob.valueOf('Software Eval');
      attach.body=bodyBlob;
        attach.parentId=opty1.id;
        insert attach;    
        
    ApexPages.currentPage().getParameters().put('optyId', opty1.id);
    ApexPages.StandardController sc1 = new ApexPages.StandardController(opty1);    
    OpenEscrowBttn ctrl1 = new OpenEscrowBttn(sc1);
    
    System.debug('***attSize: '+ctrl1.attSize);
    System.debug('***optyDocsSize: '+ctrl1.opptyDocs.size());
    ctrl1.OpptyDocs[0].lCheck = true;
    
    ctrl1.doEditEmail();
    
    ApexPages.currentPage().getParameters().put('optyId', null);                
    ApexPages.currentPage().getParameters().put('acctId', null);                
    ApexPages.StandardController sc2 = new ApexPages.StandardController(acc);
    OpenEscrowBttn ctrl2 = new OpenEscrowBttn(sc2);
        
    //ctrl2.doEditEmail();
    
    ctrl2.doCancel();

    ApexPages.currentPage().getParameters().put('optyId', null);                
    ApexPages.currentPage().getParameters().put('acctId', acc.Id);                
    ApexPages.StandardController sc3 = new ApexPages.StandardController(acc);
    OpenEscrowBttn ctrl3 = new OpenEscrowBttn(sc3);
        
    ctrl3.doEditEmail();

        
  }
}
}

Class
 
public with sharing class OpenEscrowBttn {
    public Id targetId {get;set;}
    public String AdditionalEmailId { get;set;}
    public String[] selDocs = new String[]{};   
    //public Transient List<Attachment> optyDocs {get;set;} 
    Id TempFolderId;
    Id TempTemplateId;
    String TemplateName;
    public Transient Attachment[] oldAttachments;
    public Integer attSize {get;set;}
    public List<DocItem> OpptyDocs {get;set;}    

    public OpenEscrowBttn(ApexPages.StandardController controller) {      
        Id optyId = ApexPages.currentPage().getParameters().get('optyId');
        Id acctId = ApexPages.currentPage().getParameters().get('acctId');
        if (optyId != Null) {
            targetId = optyId;
            List<Opportunity>  oppObj = [SELECT Id, AccountId, Name FROM Opportunity where Id = :optyId ];
            System.debug('******oppObj******'+oppObj);
            if(oppObj.size() > 0)
            {
               List<Account> accObj =[SELECT Id, AnnualRevenue, Appointment_Changes__c, AdditionalEmails__c FROM Account where Id = :oppObj[0].AccountId];
                System.debug('******accObj ******'+accObj );
                if(accObj.size()> 0)
                {
                  if(accObj[0].AdditionalEmails__c != null)
                  {
                    AdditionalEmailId = accObj[0].AdditionalEmails__c;
                  }
                }
            }
        } else if (acctId != Null){
          targetId = acctId;
          List<Account> accObj =[SELECT Id, AnnualRevenue, Appointment_Changes__c, AdditionalEmails__c FROM Account where Id = :acctId ];
          System.debug('******accObj ******'+accObj );
          if(accObj.size()> 0)
           {
             if(accObj[0].AdditionalEmails__c != null)
               {
                    AdditionalEmailId = accObj[0].AdditionalEmails__c;
               }
           }
          
        } else {
            targetId = Null;
        }
  
        system.debug('\n\n targetId = '+targetId);
    
        attSize = 0;
        //optyDocs = new List<Attachment>();
    set<Id> RelatedContracts = new  set<Id>();        
        if ( acctId != Null) {          
          for (Contract ct : [select id from Contract where accountId =:acctId]) {
            RelatedContracts.add(ct.id);
          }
        } 
          
        if (targetId != null) {
            OpptyDocs = new List<DocItem>();
            for (Attachment at : [Select id, Name, Body, ParentId from Attachment where (ParentId = :targetId OR ParentId in :RelatedContracts)]) {                   
                //optyDocs.add(at);
                OpptyDocs.add(new DocItem(at.Id,false,at.Name)); 
                attSize++;
            } 
            //attSize = optyDocs.size();
            if (attSize <= 0) {             
                //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'No attachments found!'));
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No attachments found for this opportunity!'));
            }          
        }           
    }

    public PageReference doEditEmail(){

        Folder TFolderId = [Select id from Folder where DeveloperName = 'Ward_Residential_Workflow_Templates' limit 1];      
        TempFolderId = TFolderId.Id;
                    
        TemplateName = 'Ke Kilohana Open Escrow Email';      
        EmailTemplate[] Temp = [Select id from EmailTemplate where Name = :TemplateName and FolderId = :TempFolderId limit 1];
                    
        if ( Temp.size() > 0 ) {
            TempTemplateId = Temp[0].id;
/*
        } else {
            EmailTemplate[] Temp1 = [Select id from EmailTemplate where FolderId = :TempFolderId limit 1];
            if ( Temp1.size() > 0 ) {
                TempTemplateId = Temp1[0].id;
            }
*/                       
        }       
        
        //Delete All current Attachments
        oldAttachments = [select id from Attachment where ParentId = :TempTemplateId ];
        
        if ( oldAttachments.size() > 0 ) {    
            delete oldAttachments;
        }        

        List<EmailTemplate> t = [Select id, FolderId, TemplateType, HtmlValue, subject, body from EmailTemplate where Id = :TempTemplateid];
        
        List<Attachment> nTlist =new  list<Attachment>();
        //Id attId = selDocs[0];
        
        set<id> aList= new set<id>();
        for (DocItem d: OpptyDocs) {
            system.debug('lCheck:'+d.lcheck);
          if ( d.lcheck ) {
            aList.add(d.DocId);
            //numDoc++;
          }
        }
        
        if (aList.size() == 0) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,'No attachments selected!'));
            return null;
        } else {
                        
            Attachment tnew;
                    
            Attachment[] tList = [Select Name, Body, ParentId from Attachment where id IN :aList];
            
            for (Attachment o: tList) {
                tnew = new Attachment();
                //tnew.Name = '(From Attachments)-'+o.name;
                tnew.Name = o.name;
                tnew.Body = o.Body;
                tnew.ParentId = t[0].id ;
                system.debug ('\n\n parent '+t[0].id );
                nTlist.add(tnew);           
            }       
            
            insert nTlist;
            
            /*
            set<id> sTlist = new set<id>();
            
            for (Attachment n: nTlist) {
              sTlist.add(n.id);
            }          
            */
            
            //PageReference pg = new PageReference('/_ui/core/email/author/EmailAuthor?id=' + attId + '&retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&p2_lkid=&template_id='+t.id+'&new_template=1'); 
            //PageReference pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&rtype=003' + '&p2_lkid=&template_id='+t.id+'&new_template=1');
            PageReference pg;
            if(AdditionalEmailId != null)
            {
              pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p2_lkid=003i000003hY6XKAA0' + '&p3_lkid=' + targetId +'&p24=' +AdditionalEmailId+'&rtype=003' + '&p2_lkid=&template_id='+t[0].id+ '&p4=dmoreira@tghawaii.com,jnelson@tghawaii.com,abastatas@tghawaii.com' +'&new_template=1');
            } 
            
            else 
            {
              pg = new PageReference('/_ui/core/email/author/EmailAuthor?retURL=%2F' + targetId + '&p3_lkid=' + targetId + '&rtype=003' + '&p2_lkid=&template_id='+t[0].id+'&new_template=1');
            } 
              
            
            pg.setRedirect(true);
            return pg;
        }       
    }
        
    public PageReference doCancel(){
        PageReference pg = new PageReference('/'+targetId); 
        pg.setRedirect(true);
        return pg;
    }  
    
    public class DocItem  {    // Referral Request Wrapper
        public id DocId {get; set;}
        public boolean lcheck {get; set;}
        public string DocName {get; set;} 
         
           
        public DocItem (id i, boolean c, string s)
            {
                DocId = i;
                lcheck = c;  
                DocName =s; 
            }
    }
      
}
Visualforce Page
 
<apex:page id="thePage" standardController="Opportunity" extensions="OpenEscrowBttn" tabStyle="Opportunity">
    <apex:messages style="color:red; font-weight:bold; text-align:center;" />
    <apex:form id="theForm">  
        <apex:pageBlock id="PB" title="Send Email">
            <apex:pageBlockButtons >
                <apex:commandButton value="Edit Email and Send" action="{!doEditEmail}" rendered="{!IF(attSize>0, true, false)}"/>                     
                <apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>            
            </apex:pageBlockButtons>        
            <apex:pageblockSection id="PBS1" title="Select Attachments" columns="1">
                  <apex:pageBlockTable value="{!OpptyDocs}" var="s"  >
                        <apex:column width="10%">
                             <apex:facet name="header">Select</apex:facet>
                             <apex:inputcheckbox value="{!s.lcheck}"/> 
                        </apex:column>
                        <apex:column width="30%"> 
                            <apex:facet name="header">Attachments</apex:facet>
                            {!s.DocName}
                        </apex:column>
                  </apex:pageBlockTable>                           
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>


 
Team, 

keep getting errors when trying to insert an account for a test class. 

Error: 
System.AssertException: Assertion Failed: Expected: 2, Actual: 1

New to coding so don't understand the error. I am trying to set up trigger that creates a change log record every time the person account email is changed. 
@isTest
private class TestPersonAccountChangeLog {

    static testMethod void LogPersonAccountChangeTest() {
        
        RecordType personAccountRecordType =  [SELECT Id FROM RecordType WHERE Name = 'Ward Residential Buyers' and SObjectType = 'Account'];
        User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
        System.runAs ( thisUser ) {
        
            WE_Process__c obj=new WE_Process__c();
    obj.Name='test';
    insert obj;
    
            Account a = NEW Account();
            a.FirstName='John';
            a.LastName='DoeTest1';
            a.PersonEmail = 'doetest1@test.com';
            a.RecordType = personAccountRecordType;
            insert a;
            
    System.assertEquals(2, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :A.PersonEmail AND pi__ObjectState__c = 1]);
    
    delete A;
    System.assertEquals(0, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :A.PersonEmail AND pi__ObjectState__c = 2]);
    
    undelete A;
    System.assertEquals(1, [SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :A.PersonEmail AND pi__ObjectState__c = 3]);
    }

}}

 
Team

I have a custom object for which I have made visualforce buttons that adds attachments to the notes and attachments section. 

The parent page is a custom object. NOT a visualforce page. I know somehow I need to factor in two different domains. = /

Can someone help me with the code?  So far it inserts the record but I have to manually refresh the page to see the attachment. 

User-added image
Visualforce Page
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
         <apex:actionFunction name="reloadparent" action="{!reload}" />  
    </apex:form>
</apex:page>
Class
Team

I have a custom object for which I have made visualforce buttons that adds attachments to the notes and attachments section. 

The parent page is a custom object. NOT a visualforce page. I know somehow I need to factor in two different domains. = /

Can someone help me with the code?  So far it inserts the record but I have to manually refresh the page to see the attachment. 



Visualforce Page 
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
         <apex:actionFunction name="reloadparent" action="{!reload}" />  
    </apex:form>
</apex:page>

Class

public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         insert a;
        PageReference parentPage = new PageReference('/' + accid); 
        parentPage.setRedirect(true); 
        return parentPage;
    }   

}

Appreciate any help!

I found something online that might be able to help but I haven't been able to make it work.


If you do not want to add any Javascript in parent window and you have some parameter that is passed to popup window, you can reload parent window using the below script,
function closeWindow(){     
            window.opener.location.href="/{!$CurrentPage.parameters.id}";
            window.top.close();
   }

In my case I am passing Id of the record as parameter to the popup window. Make sure that "Developer Mode" is not enabled. If it is enabled, it will not work.

Link tgo site http://salesforce.stackexchange.com/questions/46192/how-to-refresh-the-parent-window-after-opening-a-pop-up-window-from-inline-page/46195#46195
Code for refreshing a visual force page to the parent object upon hitting save. I created a visualforce page that attaches documents in the notes and attachement section, however it doesn't ALWAYS work. 

Sometimes when I hit save it does refresh the parent record and show me the attached document in the notes and attachement section and sometimes I have to manually refresh the page to see the recod. 

Can someone help me with the below code?

Visualforce Page
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
         <apex:actionFunction name="reloadparent" action="{!reload}" />  
    </apex:form>
</apex:page>

class
 
public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         /* insert the attachment */
         insert a;
        PageReference parentPage = new PageReference('/' + accid); 
        parentPage.setRedirect(true); 
        return parentPage;
    }   
    
    
 public void reload(){  
}
}

Please help!
Code for refreshing a visual force page to the parent object upon hitting save. I created a visualforce page that attaches documents in the notes and attachement section, however it doesn't ALWAYS work. 

Sometimes when I hit save it does refresh the parent record and show me the attached document in the notes and attachement section and sometimes I have to manually refresh the page to see the recod. 

Can someone help me with the below code?

Visualforce Page
<apex:page standardController="Tenant_Coordination__c" extensions="attachmentsample">
    <apex:form >
    <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
       <apex:commandbutton value="Save" action="{!Save}" onclick="window.top.location='/{!Tenant_Coordination__c.id}'; return true"/>
    </apex:form>
</apex:page>


Class
public class attachmentsample {

    public attachmentsample(ApexPages.StandardController controller) {

    }
    Public Attachment myfile;
    Public Attachment getmyfile()
    {
        myfile = new Attachment();
        return myfile;
    }
   
    Public Pagereference Save()
    {
        String accid = System.currentPagereference().getParameters().get('id');

        Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
         
         /* insert the attachment */
         insert a;
        return NULL;
    }   

}

Please help!

 
Team, 

I have the following trigger on my person accounts and am trying to run the below test class with the following error. 

Error: "System.AssertException: Assertion Failed: Expected: 0, Actual: 1"  on line 40 of my test class.

Appreciate any guidance.

Trigger:
trigger LogPersonAccountChange on Account (before delete, after insert, after undelete)
{
  List<pi__ObjectChangeLog__c> logs = new List<pi__ObjectChangeLog__c>(); 

  if (Trigger.new != null) {
    for (Account account : Trigger.new) {

      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();
        log.pi__ObjectFid__c = Account.PersonContactId;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;

        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;

        }
        logs.add(log);
      }
    }
  } else if (Trigger.old != null) {
    for (Account account : Trigger.old) {
      if (Account.PersonEmail != null && Account.PersonEmail != '') {
        pi__ObjectChangeLog__c log = new pi__ObjectChangeLog__c();

        log.pi__ObjectFid__c = Account.PersonContactId

        ;
        log.pi__ObjectType__c = 1;
        log.pi__ObjectEmail__c = Account.PersonEmail;
        if  (System.Trigger.isInsert) {
          log.pi__ObjectState__c = 1;
        } else if  (System.Trigger.isDelete) {
          log.pi__ObjectState__c = 2;
        } else if  (System.Trigger.isUnDelete) {
          log.pi__ObjectState__c = 3;
        }
        logs.add(log);
      }
    }
  }

  if (logs.size() > 0) {

    insert logs;
  }
}
Here is the test class:
 
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class TestPersonAccountChangeLog {

    static testMethod void LogPersonAccountChangeTest() {
    	
String RecTypeId= [select Id from RecordType where (Name='Ward Residential Buyers') and (SobjectType='Account')].Id;
    	   
    WE_Process__c obj=new WE_Process__c();
    obj.Name='test';
    insert obj;
     
    Account account = new Account();    
    account.FirstName='Test Acc';
    account.LastName='Last Name';
    Account.PersonEmail = 'abc@123.com';
    account.RecordTypeID=RecTypeId;
    insert Account;
        
        System.assertEquals([SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 1], 1);
        delete Account;
        System.assertEquals([SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 2], 1);
        undelete Account;
        System.assertEquals([SELECT COUNT() FROM pi__ObjectChangeLog__c WHERE pi__ObjectEmail__c = :Account.PersonEmail AND pi__ObjectState__c = 3], 1);
    }

}