• utz1
  • NEWBIE
  • 20 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 15
    Replies
Hello,

I want to send mail with attachment. When Mail is sent to contact on parent case then same mail should send to contact o realted case. For this I am writing trigger on email message object. I am able to send mail. But when I sent attachemnet it sent to contact o parent case only. Not to contact on child case. How can we achive this?

trigger EmailMessgaeTrigger on EmailMessage (after insert, after update)
//created to send mail to child cases when mail is sent to parent cases on case feed
{
    if (Trigger.isAfter && Trigger.isInsert) {
        
//        system.debug([select id,(select id from attachments) from emailmessage where id in : Trigger.new]);
        
        Set<Id> contactIds = new Set<Id>();
        EmailMessage ems = trigger.new[0];
        /*   set<id> eid = new set<id>();

for(EmailMessage ems: trigger.new){
if(ems.ParentId != null) 
{
eid.add(ems.ParentId);
}
} */
        
        if(ems.ParentId != null)  
        {
            Case c = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail
                      FROM Case where Id =: ems.ParentId];   
            system.debug('List of Case :='+c);
            
            Case[] caseId = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail
                             FROM Case where ParentId=: c.Id];
            system.debug('List Related Child Case '+caseId);
            
            EmailMessage em =    [select id, ccaddress, BccAddress, FromAddress, Subject, ActivityId,ToAddress, ParentId, HasAttachment, HtmlBody, TextBody, CreatedDate
                                  from EmailMessage where ParentId=: c.Id  order by CreatedDate desc limit 1];
            system.debug('Case Ids to get email message '+em);
            system.debug('em.ParentId:----->'+em.ParentId);
            system.debug('Email Message Id:---->' +em.Id);
            
            
            List<Attachment> attachments = new List<Attachment>();
            
            if(em.HasAttachment)
            {
                
                attachments  = [SELECT Id, Name, Body, BodyLength,ContentType, ParentId from Attachment  where ParentId=:em.Id];
                //   system.debug('List Of attachement.size:--->'+attachments.size());
                // String attachments1 = [SELECT Id, Name, Body, BodyLength,ContentType, ParentId from Attachment  where ParentId=:em.ParentId].ParentId;
                
                
                system.debug('List Of attachement:--->'+attachments);
            }
            system.debug('*************caseIdcaseId****************'+caseId);
            for (Case c1 : caseId)         
                //for (Case c1 : Trigger.new) 
                
            {  
                
                contactIds.add(c1.ContactId);
                system.debug('c1.ContactId:----->'+c1.ContactId);
                system.debug('c1.contactemail:----->'+c1.ContactEmail);
                Map<Id,String> ContactEmail = new Map<Id, String>();
                Map<Id, String> ContactFirstname = new Map<Id, String>();
                
                for(Contact c2: [select id, email from Contact where id IN :contactIds])
                {
                    system.debug('c2:'+c2);
                    
                    ContactEmail.put(c2.id,c2.email);
                    system.debug('c2.id:---->'+c2.id);
                    system.debug('c2.email:---->'+c2.email);
                    
                    if (em.id != Null) 
                    {
                        system.debug('c1.CaseNumber:---->'+c1.CaseNumber);
                        
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();    
                        
                        String[] toAddresses = new String[] {ContactEmail.get(c2.id)}; 
                            
                        mail.setToAddresses(toAddresses);
                        mail.setSubject(em.Subject);
                        mail.setUseSignature(false);
                        string msg = '';
                        msg = msg +em.HtmlBody;
                        mail.setHtmlBody(msg);
                        // mail.setCcAddresses(ccAddresses);
                        //mail.setReplyTo(toaddress);
                        // mail.setSenderDisplayName('Name');
                        mail.setBccSender(false);
                        if(attachments.size() > 0)
                        {
                            
                            List<Messaging.EmailFileAttachment> emailAttachments = new List<Messaging.EmailFileAttachment>();
                            for(Attachment att : attachments) {
                                
                                Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                                efa.setFileName(att.Name);
                                efa.setBody(att.Body);
                                efa.setContentType(att.ContentType);
                                emailAttachments.add(efa);
                            }
                            
                            mail.setFileAttachments(emailAttachments);
                            //     mail.saveAsActivity = True;
                            mail.setSaveAsActivity(True);
                            
                        } 
                        
                        // Send the email
                        // mail.setFileAttachments(new Messaging.EmailFileAttachment[] { efa }); 
                        
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                        system.debug('Email is sent--------------------->'+mail);
                    
                    
                    
                }
                
            }
        }
    }
    
}

Thanks,
Utkarsha
  • February 01, 2018
  • Like
  • 0
Hello,

Functionality need to implement: when mail is sent to contact on parent cases then same mail should send to contact on realted case.

For this functionality I am using trigger. I am able to send mail. But I am using html body to send mail instead I want to send template. I am not able to send template. How can I achive this using below code?

Html Body: mail.setHTMLBody('Case Number:  &nbsp;' +c.CaseNumber +' &nbsp;  &nbsp; Based on product send email to contact Product: &nbsp;'+ 
                                             parentCase.Product__c + ' &nbsp;  &nbsp; &nbsp; Latest Update: &nbsp;'+ parentCase.Latest_Update__c + ' Updated Successfully'); 

Code:
  public static void SendMailToChildCases(List<Case> CaseList) {
        //Start Trigger: Send mail to child cases
        Set<Id> contactIds = new Set<Id>();
        Set<Id> CId = new Set<Id>();
        Map<Id,String> ContactEmail = new Map<Id, String>();
        Map<Id, String> ContactFirstname = new Map<Id, String>();
        
        for(Case p: CaseList)
        {
            CId.add(p.Id);
            system.debug('******CASE ID******'+ p.id);
          // p.Ischanged_Latest_Update__c = false;

        }
        Case[] caseId = [SELECT Id, Reason, CaseNumber, ContactId, EntitlementId, Subject, Description, ContactEmail, contact.name, Latest_Update__c, Product__c, ParentId, SuppliedEmail FROM Case WHERE ParentId=:CId];   
      EmailTemplate et=[SELECT Id, Body, DeveloperName ,HtmlValue, Subject, IsActive FROM EmailTemplate Where DeveloperName = 'Outage_email'];  
        system.debug('******CASEID******'+ caseId);
        
        for (Case c1 : caseId)         
        {  
            contactIds.add(c1.ContactId);
            system.debug('******contactIds*******'+contactIds);
        }
        
        list<contact> conList=[select id, email from Contact where id IN :contactIds];
        system.debug('******conList*******'+conList);
        
        if(conList.size()!=null)
        {
            for(Contact c2: conList)
            {                            
                ContactEmail.put(c2.id,c2.email);
                System.debug('*******c2.id**********'+c2.id);
                system.debug('********c2.email*********'+c2.email);
            }
        }
        
        for(Case parentCase: CaseList)
        {
            Case caseOld= (Case)Trigger.OldMap.get(parentCase.id);
            system.debug('parentCase.Latest_Update__c : '+parentCase.Latest_Update__c);
            system.debug('caseOld.Latest_Update__c : '+caseOld.Latest_Update__c);
            for(case c:caseId)
            {
                system.debug('*******c.contactid*******'+c.contactid);
                for(Contact c2: conList)
                {
                    system.debug('*********parentCase.Reason***********'+parentCase.Reason+'Case id'+c.id);
                    system.debug('*********parentCase.Latest_Update__c****************'+parentCase.Latest_Update__c);
                    system.debug('**************parentCase.Update_Timer__c*******************'+parentCase.Update_Timer__c);
                    system.debug('********************parentCase.Status********************'+parentCase.Status);
                    system.debug('********************caseOld.Status********************'+caseOld.Status);
                    system.debug('********************parentCase.Start_Time__c********************'+parentCase.Start_Time__c);
                    system.debug('********************caseOld.Start_Time__c********************'+caseOld.Start_Time__c);
                    system.debug('********************caseOld.Finish_Time__c********************'+caseOld.Finish_Time__c);
                    system.debug('********************parentCase.Finish_Time__c********************'+parentCase.Finish_Time__c);
                    system.debug('*********************caseOld.Update_Timer__c**************************'+caseOld.Update_Timer__c);
                    system.debug('***************************parentCase.Ischanged_Start_Time__c*****************************'+parentCase.Ischanged_Start_Time__c);
                    system.debug('***************************parentCase.Ischanged_Finish_Time__c*****************************'+parentCase.Ischanged_Finish_Time__c);
                    
                    
                    if(AvoidEntitlemetRecursion.isFirstRun1())
                    {
                        
                        if(c.contactid==c2.id && c.ParentId != null && parentCase.Reason == 'Support-Outage' &&
                           (
                               
                               (parentCase.Latest_Update__c != null && parentCase.Update_Timer__c == null && (parentCase.Status == 'New Case' || parentCase.Status == 'Awaiting Mobile Support')) ||
                               
                               (parentCase.Latest_Update__c != null && parentCase.Update_Timer__c != null &&
                                parentCase.Status == 'New Case' || ( c.contactid==c2.id && c.ParentId != null && parentCase.Reason == 'Support-Outage' && parentCase.Latest_Update__c != null &&
                                                                    parentCase.Status == 'Awaiting Mobile Support')) ||
                               
                               (parentCase.Update_Timer__c == null && caseOld.Update_Timer__c != null && parentCase.Latest_Update__c == caseOld.Latest_Update__c) ||
                               
                               (parentCase.Status == 'Awaitng Accounts Team' && caseOld.Update_Timer__c == null && parentCase.Update_Timer__c == null)
                               
                           )
                          )
                            
                        {
                            system.debug('****** inside contactid********'+c.contactid);
                            system.debug('************ Inside send mail if c.Reason****************'+parentCase.Reason);
                            List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
                            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                            String[] toAddresses = new String[] {ContactEmail.get(c2.id)}; 
                                
                                mail.setToAddresses(toAddresses);
                            mail.setSenderDisplayName('IPsolutions Support');
                        mail.setHTMLBody('Case Number:  &nbsp;' +c.CaseNumber +' &nbsp;  &nbsp; Based on product send email to contact Product: &nbsp;'+ 
                                             parentCase.Product__c + ' &nbsp;  &nbsp; &nbsp; Latest Update: &nbsp;'+ parentCase.Latest_Update__c + ' Updated Successfully'); 
                            mail.setSaveAsActivity(false);
                           mail.setWhatId(c.ContactId);
                            // mail.getSaveAsActivity(true);
                            allmsg.add(mail);
                         mail.setTemplateId(et.id);
                        mail.setTargetObjectId(c2.id);
                            Messaging.sendEmail(allmsg,false);
                            system.debug('Outage Mail Is Sent');
                            
                        }

Thanks,
Utz
  • February 01, 2018
  • Like
  • 0
Hello,

We want to use success, warning and violation action used in milestone[Entitlement Process] programmatically. Is this possible in salesforce? How to call this event programmatically for the specific conditions on the milestone.

Thanks,
Utkarsha
  • January 16, 2018
  • Like
  • 0
Hello,

When I click on cancel button then I want to redirect on console page. Right now, when I click on Cancel Or Save button it holds me on same page. I want my screen should be pops back to console screen when I click on cancel button.

<apex:page standardController="OpportunityLineItem">
  <SCRIPT>
  window.top.location.replace("{!URLFOR($Action.OpportunityLineItem.Edit, OpportunityLineItem.id, [saveURL='/'+OpportunityLineItem.id , cancelURL='/console'], true)}");
  if(top.location.href == "https://eu9.salesforce.com/console") {
  //https://cs89.salesforce.com/console
        if(window.confirm(top.location.href)) {
            window.top.location.replace("{!URLFOR($Action.OpportunityLineItem.Edit, OpportunityLineItem.id, [saveURL='/console' , cancelURL='/console'], true)}");
        }
  }
  else {
    <!--if(window.confirm("Are you Sure ??")) { -->
       window.top.location.replace("{!URLFOR($Action.OpportunityLineItem.Edit, OpportunityLineItem.id,[saveURL='/'+OpportunityLineItem.id , cancelURL='/'+OpportunityLineItem.Opportunity.id ],true)}");
    <!--}-->
  }      
  </SCRIPT>
</apex:page>

Thanks,
Utkarsha
  • January 15, 2018
  • Like
  • 0
Hello, 

On case object I am sending some mail on feed. I want chain of all the sent and received email on email template. How is this achivable?

Thanks & Regards,
Utz
  • January 08, 2018
  • Like
  • 0
Hello,

I want to take 'Post body' on feeditem object in email template. How is this achivable?

Thanks & Regards,
Utz
  • January 08, 2018
  • Like
  • 0
Hello,
i want to write entry criteria where I want if value is changed then only checkbox field is updated to true. Now if Latest update is blank and we put anything in to it then also it checkes the checkbox. I want If Latesr Update field is filled and we changed it then only checkbox get checked


AND( OR(ISPICKVAL( Reason , "Support-Outage"),ISPICKVAL( Reason , "Support-Supplier Maintenance")) ,   AND( LEN(Latest_Update__c  ) <> 0 ,ISCHANGED( Latest_Update__c  ))   ,  OR(Entitlement.Name  =  "MSO Entitlement Process",Entitlement.Name  =  "Planned Maintenance Process"))
  • December 04, 2017
  • Like
  • 0
Hello,

I am working on enttilement process, where I am updating chechkbox(reset milestone) on case object whenewer milestone is violated. Then my trigger fires which checks whether 'reset milestone' is true or not. If it is true then trigger will fire and milestone will reset. For this i am putting system.now() in start date field on casemilestone object.

Well, My issue is I am able to reset milestone through this processs when i edit case and then save. But I want this procedure should run automatically. When check box get checked then trigger wont fire till i am not editing the case. Is there any way to run this automatically?

Here is the code i am using to reset the milestone.

trigger startdate on Case (after update) {
List<CaseMilestone> cmUpdatedList =new List<CaseMilestone>();
List<Case> cList = [SELECT CaseNumber, AccountId, Id, ContactId, Reset_Milestone__c, Subject, Description, ContactEmail, contact.name,  Product__c, SuppliedEmail 
FROM Case WHERE Reset_Milestone__c = true AND Id IN :Trigger.new];  
List<CaseMilestone> cmList= [SELECT Id , CaseId, StartDate, IsViolated, case.Reset_Milestone__c, IsCompleted FROM CaseMilestone where CaseId =: cList AND IsCompleted = false];
for(case cd : cList)
{
   if(cd.Reset_Milestone__c == true )
   {
       for(CaseMilestone cms : cmList)
       {
               cms.StartDate =  System.now();
               system.debug('********cms.StartDate*********'+cms.StartDate);
               cmUpdatedList.add(cms);
       } 
         
       
   }
   Update cmUpdatedList;
   
}
  }

Thanks,
Utz
  • December 01, 2017
  • Like
  • 0
Hello, 

I am working on entitlement process. When milestone is violated I am updating checkbox field on case object. I want after chechk box is checked. This trigger should fire. This trigger reset milestone on case. Well, trigger is working. 

My concern is, when Checkbox on case object checked by violation action it does not autoamtically fires trigger and reste the milestone. Insetad to run trigger I have to edit case. I want this should be done automatically

Thanks,
Utz

trigger startdate on Case (after update) {
    
   List<CaseMilestone> cmUpdatedList =new List<CaseMilestone>();
   List<Case> cList = [SELECT CaseNumber, AccountId, Id, ContactId, Reset_Milestone__c, Subject, Description, ContactEmail, contact.name,  Product__c, SuppliedEmail 
   FROM Case WHERE Reset_Milestone__c = true AND Id IN :Trigger.new];  
   List<CaseMilestone> cmList= [SELECT Id , CaseId, StartDate, IsViolated, case.Reset_Milestone__c, IsCompleted FROM CaseMilestone where CaseId =: cList AND IsCompleted = false];
   for(case cd : cList)
   {
       if(cd.Reset_Milestone__c == true )
       {
           for(CaseMilestone cms : cmList)
           {
                   cms.StartDate =  System.now();
                   system.debug('********cms.StartDate*********'+cms.StartDate);
                   cmUpdatedList.add(cms);
           } 
       }
       Update cmUpdatedList;
      

     
}
   
 
  • November 28, 2017
  • Like
  • 0
Hello,

I am working on entitlement. I want to reset milestone if action is not taken by agent. Support i have set milestone for 10 minutes and after 10 minutes action is not performed on milestone. that means if milestone is not completed within SLA time then same milestone should again reset for 10 minutes. How is this possible?

Thnx,
utz

 
  • November 24, 2017
  • Like
  • 0
Hello,

I am using entitlement process. I want to reset milestone when we will update case on case feed. When we will click on update button then milestone success action should fire but milestone should run again and again. How is  this possible?

Thanks,
Utz
  • November 23, 2017
  • Like
  • 0

Hello,
I am writing a trigger where i am sending mail. But I dont want to send plain mail. I want to send email template through trigger. I have written a trigger and receiving an email but I am not receiving any content in body.

trigger Sendmailtochildcases on Case (before update) {
    
 
       Set<Id> contactIds = new Set<Id>();
       Set<Id> CId = new Set<Id>();
    
           for(Case p:trigger.new) {
           system.debug('******CASE ID******'+ p.id);
            
            if((p.CaseNumber != null && p.Send_Mail__c == True)) {
                CId.add(p.Id);
             }
           }

Case[] caseId = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail FROM Case WHERE ParentId=:CId];   
system.debug('*******************List Of Child Case******************='+caseId);
 
//Case[] caseId = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail FROM Case where ParentId=: c.Id];
//system.debug('List Related Child Case '+caseId);
   
    
   for (Case c1 : caseId)         
            //for (Case c1 : Trigger.new) 

  {  

     contactIds.add(c1.ContactId);
      system.debug('***********c1.ContactId:*****************'+c1.ContactId);
     Map<Id,String> ContactEmail = new Map<Id, String>();
     Map<Id, String> ContactFirstname = new Map<Id, String>();
     
     for(Contact c2: [select id, email from Contact where id IN :contactIds])
    {
         system.debug('*************c2*************:'+c2);
         EmailTemplate et=[SELECT Id, DeveloperName , IsActive FROM EmailTemplate WHERE DeveloperName = 'Outage_is_cleared'];
         system.Debug('**************et************'+et);
        
        ContactEmail.put(c2.id,c2.email);
        system.debug('*************c2.id:*****************'+c2.id);
        system.debug('*************c2.email:*****************'+c2.email);
        
 //     if (c1.Send_Mail__c == True) 
  //  {
      system.debug('************c1.CaseNumber:*****************'+c1.CaseNumber);

      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      String[] toAddresses = new String[] {ContactEmail.get(c2.id)}; 
      mail.setToAddresses(toAddresses);
      mail.setSubject('Email to Contact');
      mail.setUseSignature(false);
      string msg = '';
      mail.setHtmlBody(msg);
      mail.setBccSender(false);
      mail.setSaveAsActivity(True);          
       mail.setTemplateId(et.Id);
      //mail.treatbodiesastemplate();
      // Send the email
      Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
      system.debug('*************Email is sent***********************>'+mail);
        }
    }
//  }

}

Thnx,
Utz

  • November 21, 2017
  • Like
  • 0
Hello,
I am writing trigger where i want to send email to related cases when email is sent to parent cases. well, I am able to send mail to related cases with plian body and tempaltes. but not able to send attachment to the related case. Is there any way to send email with atatchement?

trigger Sendemailmessage on EmailMessage (after insert)
{
        system.debug([select id,(select id from attachments) from emailmessage where id in : Trigger.new]);

Set<Id> contactIds = new Set<Id>();
EmailMessage ems = trigger.new[0];
  /*   set<id> eid = new set<id>();

       for(EmailMessage ems: trigger.new){
           if(ems.ParentId != null) 
           {
        eid.add(ems.ParentId);
           }
    } */

if(ems.ParentId != null)  
 {
Case c = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail
               FROM Case where Id =: ems.ParentId];   
system.debug('List of Case :='+c);
 
Case[] caseId = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail
                FROM Case where ParentId=: c.Id];
   system.debug('List Related Child Case '+caseId);
     
     EmailMessage em =    [select id, ccaddress, BccAddress, FromAddress, Subject, ActivityId,ToAddress,ParentId,HasAttachment, HtmlBody, TextBody
                          from EmailMessage where ParentId=: c.Id  order by CreatedDate desc limit 1];
     system.debug('Case Ids to get email message '+em);
     system.debug('em.ParentId:----->'+em.ParentId);
     system.debug('Email Message Id:---->' +em.Id);
         
   
List<Attachment> attachments = new List<Attachment>();

    if(em.HasAttachment)
    {
  
   attachments  = [SELECT Id, Name, Body, BodyLength,ContentType, ParentId from Attachment  where ParentId=:em.Id];
  //   system.debug('List Of attachement.size:--->'+attachments.size());
         // String attachments1 = [SELECT Id, Name, Body, BodyLength,ContentType, ParentId from Attachment  where ParentId=:em.ParentId].ParentId;


     system.debug('List Of attachement:--->'+attachments);
    }
        for (Case c1 : caseId)         
            //for (Case c1 : Trigger.new) 

  {  

     contactIds.add(c1.ContactId);
      system.debug('c1.ContactId:----->'+c1.ContactId);
     Map<Id,String> ContactEmail = new Map<Id, String>();
     Map<Id, String> ContactFirstname = new Map<Id, String>();
     
     for(Contact c2: [select id, email from Contact where id IN :contactIds])
    {
        system.debug('c2:'+c2);
        
      ContactEmail.put(c2.id,c2.email);
        system.debug('c2.id:---->'+c2.id);
        system.debug('c2.email:---->'+c2.email);
        
      if (em.id != Null) 
  {
      system.debug('c1.CaseNumber:---->'+c1.CaseNumber);

      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      String[] toAddresses = new String[] {ContactEmail.get(c2.id)}; 
      mail.setToAddresses(toAddresses);
      mail.setSubject(em.Subject);
      mail.setUseSignature(false);
      string msg = '';
      msg = msg +em.HtmlBody;
      mail.setHtmlBody(msg);
     // mail.setCcAddresses(ccAddresses);
     //mail.setReplyTo(toaddress);
    // mail.setSenderDisplayName('Name');
     mail.setBccSender(false);
    if(attachments.size() > 0)
      {
      
      List<Messaging.EmailFileAttachment> emailAttachments = new List<Messaging.EmailFileAttachment>();
for(Attachment att : attachments) {

    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    // You may need to do some work here to figure out the correct file extension
    efa.setFileName(att.Name);
    // Take the blob data from the Attachment and put it on the email.
    efa.setBody(att.Body);
    efa.setContentType(att.ContentType);
    emailAttachments.add(efa);
}

mail.setFileAttachments(emailAttachments);
   //     mail.saveAsActivity = True;
   mail.setSaveAsActivity(True);

      } 
      
       // Send the email
      Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
      system.debug('Email is sent--------------------->'+mail);
        }
    
    
}
 
}
}
  • November 01, 2017
  • Like
  • 0
Hello,

I am writing trigger where i want to update child case when parent case field is updated. 
In debug logs parent field value assigned to child field value but update action is not performing on child case.

trigger CaseT on Case (before update, after update) {

if( Trigger.isBefore && Trigger.isUpdate )
{
    for(Case c : Trigger.New){
        c.desc__c = c.Description;
    }
    }
    
   
if( Trigger.isAfter && Trigger.isUpdate )
{    
      if(AvoidRecursion.isFirstRun())
    {
   
      
Set<Id> parentIds = new Set<Id>();
    
           for(Case p:trigger.new) {
           system.debug('******CASE ID******'+ p.id);
            
            if((p.CaseNumber != null)) {
                parentIds.add(p.Id);
             }
           }
       
        System.debug('------------- Parent Ids -------- ' + parentIds);
    
        if(parentIds.size() != null) {
            for(case c : trigger.new){
            for(Case ch : [SELECT Id, Status, Notes__c, ContactId, ParentId  FROM Case WHERE Id=:parentIds]) {
               system.debug('********Child Cases*********'+ch);
                 ch.Notes__c = c.Notes__c;
                 ch.ContactId = c.ContactId;
                
                system.debug('ch.Notes__c 1'+ch.Notes__c );
                system.debug('ch.ContactId 1 '+ch.ContactId );
         
            
                update ch;
                
                system.debug('***********ch.Notes__c 2***********'+ch.Notes__c );
                system.debug('***********ch.ContactId 2**********'+ch.ContactId );
            }

            }
            }
            
            }
           
            
        }
    }


thanks & best regards,
Utz
  • November 01, 2017
  • Like
  • 0
Hello,
I am writing trigger where i want parent id of email message having an attachment. 

List<Attachment> attachments = new List<Attachment>();
     
    if(em.HasAttachment)
    {
  
   attachments  = [SELECT Id, Name, Body, BodyLength,ContentType, ParentId from Attachment  where ParentId=:em.ParentId];
     system.debug('List Of attachement.size:--->'+attachments.size());

     
     system.debug('List Of attachement:--->'+attachments);

Its not taking any value over here, where ParentId=:em.ParentId
  • October 31, 2017
  • Like
  • 0
Hello,

I want to develop functionality where mail should be send to related cases when mail sent to parent case.
How can we achive this?

Thanks & Regards,
Utkarsha
  • October 27, 2017
  • Like
  • 0
Hello,

I have written a test class. Its code coverage is 745. I want to increase its coverage.

Test class:
@isTest
private class CreateNewQuoteTest {
    private static testMethod void testManipulateOrders(){
       
        Pricebook2 customPB = new Pricebook2(Name='SDEC GBP Distributor Price Sheet', isActive=true);
        insert customPB;
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = customPB.id ;
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = 'Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

       Id pricebookId = Test.getStandardPricebookId();

        system.debug('standardPb--------------->test'+pricebookId);
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = pricebookId;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
      
        PricebookEntry custompbe2 = new PricebookEntry();
        custompbe2.Pricebook2Id = customPB.Id;
        custompbe2.Product2Id = p.Id;
        custompbe2.UnitPrice = 1;
        custompbe2.IsActive = true;
        custompbe2.UseStandardPrice = false;
        insert custompbe2 ;  
        
        Opportunity o = new Opportunity();
        o.Name = 'Opp';
        o.AccountId = a.Id;
        o.CloseDate= system.today();
        o.StageName = 'Proposal';
        insert o;
        update o;
             
        Quote q = new Quote();
        q.Name= o.Id;
        q.OpportunityId = o.Id;
        q.status = 'Draft'; 
        q.Pricebook2Id = customPB.id;
        insert q;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Quote__c = q.Id;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Opportunity__c = o.Id;
        d.Quote__c = q.Id;
        insert d;
               
        test.StartTest();

        o.StageName = 'Closed Won';
        o.Invoice__r.size();
        system.debug('test---------o.StageName'+o.StageName);
        system.debug('test---------o.Invoice__r.size()'+o.Invoice__r.size());
       
        if(o.StageName  == 'Closed Won' && o.Invoice__r.size() == 0){
                Invoice__c i2 = new Invoice__c();
                system.debug('test---------Invoice'+i2);
        }
        update o;   
               test.StopTest();  

    } 
    
    private static testMethod void testManipulateOrders1(){
          
        Pricebook2 customPB = new Pricebook2(Name='SDEC GBP Distributor Price Sheet', isActive=true);
        insert customPB;
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = customPB.id;
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = 'Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

        Id pricebookId = Test.getStandardPricebookId();

        system.debug('standardPb--------------->test'+pricebookId);
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = pricebookId;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
      
        PricebookEntry custompbe2 = new PricebookEntry();
        custompbe2.Pricebook2Id = customPB.Id;
        custompbe2.Product2Id = p.Id;
        custompbe2.UnitPrice = 1;
        custompbe2.IsActive = true;
        custompbe2.UseStandardPrice = false;
        insert custompbe2 ;   
        
        Opportunity o = new Opportunity();
        o.Name = 'Test opportunity';
        o.AccountId = a.Id;
        o.CloseDate= system.today();
        o.StageName = 'Proposal';
        
        insert o;
        update o;
        
        Quote q = new Quote();
        q.Name= o.Id;
        q.OpportunityId = o.Id;
        q.status = 'Draft'; 
        q.Pricebook2Id = customPB.id;

        insert q;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Quote__c = q.Id;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Opportunity__c = o.Id;
        d.Quote__c = q.Id;
        insert d;
        
       test.StartTest();
              
        o.StageName = 'Closed Won';
        o.Delivery_Notes__r.size();
        system.debug('test---------o.StageName'+o.StageName);
        system.debug('test---------o.Delivery_Notes__r.size()'+o.Delivery_Notes__r.size());
      
        if(o.StageName  == 'Closed Won' && o.Delivery_Notes__r.size() == 0)
                {
            Delivery_Notes__c newDelivery = new Delivery_Notes__c();
            system.debug('test---------Delivery'+newDelivery);
                }
           //update o;
           
          else if(o.StageName  != 'Closed Won' && o.Delivery_Notes__r.size() != 0)
          {
        system.debug('o.StageName  == Closed Won && o.Delivery_Notes__r.size() == 0');
           }

       test.StopTest(); 
      
    }

     private static testMethod void testManipulateOrders2(){
     
        Pricebook2 customPB = new Pricebook2(Name='SDEC GBP Distributor Price Sheet', isActive=true);
        insert customPB;
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = customPB.id;
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = 'Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

        Id pricebookId = Test.getStandardPricebookId();

        system.debug('standardPb--------------->test'+pricebookId);
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = pricebookId;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
      
        PricebookEntry custompbe2 = new PricebookEntry();
        custompbe2.Pricebook2Id = customPB.Id;
        custompbe2.Product2Id = p.Id;
        custompbe2.UnitPrice = 1;
        custompbe2.IsActive = true;
        custompbe2.UseStandardPrice = false;
        insert custompbe2 ;   
        
        Opportunity o = new Opportunity();
        o.Name = 'Test opportunity';
        o.AccountId = a.Id;
        o.CloseDate= system.today();
        o.StageName = 'Proposal';
        
        insert o;
   
        Quote q = new Quote();
        q.Name= o.Id;
        q.OpportunityId = o.Id;
        q.status = 'Draft'; 
        q.Pricebook2Id = customPB.id;

        insert q;
         
        Order od = new Order();
        od.Name = 'Test';
        od.AccountId = a.Id;
        od.status = 'Draft'; 
        od.Your_Order_Reference__c = '123';
        od.EffectiveDate = system.today();
        od.Pricebook2Id =customPB.Id;
        od.OpportunityId = o.Id;
        od.QuoteId= q.id;
        insert od;
       // update od;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Quote__c = q.Id;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Opportunity__c = o.Id;
        d.Quote__c = q.Id;
        insert d;
        
        test.StartTest();
              
        od.status = 'Closed Won';
        od.Orders.size();
        system.debug('test--------- od.status'+ od.status);
        system.debug('test---------od.Orders.size()'+od.Orders.size());
      
        if( od.status  == 'Closed Won' && od.Orders.size() == 0)
                {
         Order newOrder = new Order();
         newOrder.AccountId = a.Id;
         newOrder.OpportunityId = o.Id;
       //  newOrder.QuoteId = q.SyncedQuoteId;
         newOrder.Status = 'Closed Won';
         newOrder.EffectiveDate = system.today();
         newOrder.Pricebook2Id = o.Pricebook2Id;
        insert newOrder;
            system.debug('test---------Order'+newOrder);
                }
       update od;

       test.StopTest(); 
      
    }
}


Trigger:
User-added imageUser-added image

Its giving an error System.DmlException: Update failed. First exception on row 0 with id 0068E00000BqCLfQAN; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateNewQuote: execution of AfterUpdate

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

caused by: System.QueryException: List has no rows for assignment to SObject

Thanks & regards,
Utz
  • October 05, 2017
  • Like
  • 0
Hello, I want to cover my test class for If condition. 

@isTest(seeAllData = true)
public class CreateInvoiceDelTest {
    public static testMethod void testManipulateOrders(){
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = '01s8E000000DOci';
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = ' Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

        Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
    
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = standardPb.Id;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        PricebookEntry pbe = [ SELECT Id,Product2Id,Pricebook2Id,UnitPrice FROM PricebookEntry WHERE  isActive=true LIMIT 1 ];
    
        Order od = new Order();
        od.Name = 'Test';
        od.AccountId = a.Id;
        od.status = 'Draft'; 
        od.Your_Order_Reference__c = '123';
        od.EffectiveDate = system.today();
        insert od;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Contact__c = c.Id;
        i.Order__c = od.Id;
        i.Your_Reference__c =  od.Your_Order_Reference__c;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Contact__c = c.Id;
        d.Your_Reference__c =  od.Your_Order_Reference__c;
        d.Order__c = od.Id;
        insert d;
        
         test.StartTest();
        od.Status = 'Closed Won';
        system.debug('Test od.Status------>'+od.Status);
        if(od.Status == 'Closed Won' && od.Invoice__r.size() == 0){
           Invoice__c i2 = new Invoice__c();
           system.debug('Invoice__C Created---->'+i2);
        }
      /*  else if(od.Status != 'Closed Won' && od.Invoice__r.size() >= 0)
        {
            system.debug('Error');
        }*/
        
           if(od.Status == 'Closed Won' && od.Delivery_Notes__r.size() == 0 ){
               Delivery_Notes__c d1 = new Delivery_Notes__c(); 
           }
          update od;
         test.StopTest();
    }
    
    
        public static testMethod void testManipulateOrders1(){
            Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = '01s8E000000DOci';
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = ' Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

        Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
    
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = standardPb.Id;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        PricebookEntry pbe = [ SELECT Id,Product2Id,Pricebook2Id,UnitPrice FROM PricebookEntry WHERE  isActive=true LIMIT 1 ];
    
        Order od = new Order();
        od.Name = 'Test';
        od.AccountId = a.Id;
        od.status = 'Draft'; 
        od.Your_Order_Reference__c = '123';
        od.EffectiveDate = system.today();
        insert od;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Contact__c = c.Id;
        i.Order__c = od.Id;
        i.Your_Reference__c =  od.Your_Order_Reference__c;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Contact__c = c.Id;
        d.Your_Reference__c =  od.Your_Order_Reference__c;
        d.Order__c = od.Id;
        insert d;
        
         test.StartTest();
        od.Status = 'Draft';
        system.debug('Test od.Status------>'+od.Status);
        if(od.Status != 'Closed Won' && od.Invoice__r.size() >= 0){
           system.debug('Error');
        }
      
           if(od.Status != 'Closed Won' && od.Delivery_Notes__r.size() >= 0 ){
           system.debug('Error');
           }
          update od;
         test.StopTest();
        }


}

My trigger is:
Invoice__c newInvoice1 = new Invoice__c();
            
        System.debug('New Inovice Is Created');
            
        // newInvoice.Name ='Invoice';
         newInvoice1.Account__c = o.AccountId;
         newInvoice1.Order__c= o.Id;
         newInvoice1.Your_Reference__c= o.Your_Order_Reference__c;
         newInvoice1.Contact__c= o.Contact__c;

        // newInvoice.Status__c = 'Pending';
        // newInvoice.Pricebook2Id = q.Pricebook2Id;

       insert newInvoice1;
       System.debug('Invoices Created with data'+newInvoice1);


I am not able to cover these statements in my test clss

Thanks & Regrads,
Utz
  • September 19, 2017
  • Like
  • 0
Hello,
I want some changes in my code suppose there is already invoice record for opportunity then it should not create invoice when we update opportunity
trigger CreateNewQuote on Opportunity(after insert , after update) {

        
        for (Opportunity o1 : Trigger.new){
        if(o1.StageName  == 'Closed Won' ){
     
        Invoice__c newInvoice = new Invoice__c();
        System.debug('New Inovice Is Created');
         newInvoice.Account__c = o1.AccountId;
         newInvoice.Opportunity__c = o1.Id;
         newInvoice.Quote__c =  o1.SyncedQuoteId;
       //newInvoice.Pricebook2Id = o1.Pricebook2Id;

        insert newInvoice;
        System.debug('Invoices Created with data:='+newInvoice); 

    }
    }      
}
}
  • September 13, 2017
  • Like
  • 0
Hello,

I am creating invoice lie item same as quote line item. My code is giving error of recursive call. can someone help me with this.

trigger CreateInvoiceLineItem on Invoice__c(after insert, after update) {
/* This Trigger Creates Invoice Line Item. Invoice Line Item will be Same as Quote Line Item 
We need to set pricebook for Invoice
Ref: https://developer.salesforce.com/forums/?id=906F00000008llQIAQ */

Invoice__c inv = trigger.new[0];
system.debug('List of Invoice:'+inv);
   
// Fetch Quote Id for Invoice
Quote oppId = [SELECT AccountId, Id, Pricebook2Id FROM Quote where id=:inv.Quote__c];
system.debug('Quote Ids '+oppId);
    
// Fetch Quote Lines 
List<QuoteLineItem> opplines=[select id, quantity, PriceBookEntry.Product2Id ,UnitPrice,PriceBookEntry.Pricebook2Id
from QuoteLineItem where QuoteId=:oppId.id];

system.debug('List Of Quote Line Item  '+opplines);


    // Loop Opportunity Lines
    for(QuoteLineItem oppline:opplines){
        
        // Create Order Line Object
        Invoice_Line_Item__c OrderLine = new Invoice_Line_Item__c();
        OrderLine.Invoice__c= inv.Id;
      //OrderLine.Product2Id = oppline.PriceBookEntry.Product2Id;
        OrderLine.Quantity__c = oppline.Quantity;
      //OrderLine.PriceBookEntryId  = oppline.PriceBookEntryId;
        OrderLine.Unit_Price__c = oppline.UnitPrice;
      //oppline.PriceBookEntry.Pricebook2Id
              insert OrderLine;

    }
}

thanks & best regards,
utz
  • September 07, 2017
  • Like
  • 0
Hello,
i want to write entry criteria where I want if value is changed then only checkbox field is updated to true. Now if Latest update is blank and we put anything in to it then also it checkes the checkbox. I want If Latesr Update field is filled and we changed it then only checkbox get checked


AND( OR(ISPICKVAL( Reason , "Support-Outage"),ISPICKVAL( Reason , "Support-Supplier Maintenance")) ,   AND( LEN(Latest_Update__c  ) <> 0 ,ISCHANGED( Latest_Update__c  ))   ,  OR(Entitlement.Name  =  "MSO Entitlement Process",Entitlement.Name  =  "Planned Maintenance Process"))
  • December 04, 2017
  • Like
  • 0
Hello,

I am working on enttilement process, where I am updating chechkbox(reset milestone) on case object whenewer milestone is violated. Then my trigger fires which checks whether 'reset milestone' is true or not. If it is true then trigger will fire and milestone will reset. For this i am putting system.now() in start date field on casemilestone object.

Well, My issue is I am able to reset milestone through this processs when i edit case and then save. But I want this procedure should run automatically. When check box get checked then trigger wont fire till i am not editing the case. Is there any way to run this automatically?

Here is the code i am using to reset the milestone.

trigger startdate on Case (after update) {
List<CaseMilestone> cmUpdatedList =new List<CaseMilestone>();
List<Case> cList = [SELECT CaseNumber, AccountId, Id, ContactId, Reset_Milestone__c, Subject, Description, ContactEmail, contact.name,  Product__c, SuppliedEmail 
FROM Case WHERE Reset_Milestone__c = true AND Id IN :Trigger.new];  
List<CaseMilestone> cmList= [SELECT Id , CaseId, StartDate, IsViolated, case.Reset_Milestone__c, IsCompleted FROM CaseMilestone where CaseId =: cList AND IsCompleted = false];
for(case cd : cList)
{
   if(cd.Reset_Milestone__c == true )
   {
       for(CaseMilestone cms : cmList)
       {
               cms.StartDate =  System.now();
               system.debug('********cms.StartDate*********'+cms.StartDate);
               cmUpdatedList.add(cms);
       } 
         
       
   }
   Update cmUpdatedList;
   
}
  }

Thanks,
Utz
  • December 01, 2017
  • Like
  • 0

Hello,
I am writing a trigger where i am sending mail. But I dont want to send plain mail. I want to send email template through trigger. I have written a trigger and receiving an email but I am not receiving any content in body.

trigger Sendmailtochildcases on Case (before update) {
    
 
       Set<Id> contactIds = new Set<Id>();
       Set<Id> CId = new Set<Id>();
    
           for(Case p:trigger.new) {
           system.debug('******CASE ID******'+ p.id);
            
            if((p.CaseNumber != null && p.Send_Mail__c == True)) {
                CId.add(p.Id);
             }
           }

Case[] caseId = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail FROM Case WHERE ParentId=:CId];   
system.debug('*******************List Of Child Case******************='+caseId);
 
//Case[] caseId = [SELECT CaseNumber, AccountId, Id, ContactId, Subject, Description, ContactEmail, contact.name, ParentId, SuppliedEmail FROM Case where ParentId=: c.Id];
//system.debug('List Related Child Case '+caseId);
   
    
   for (Case c1 : caseId)         
            //for (Case c1 : Trigger.new) 

  {  

     contactIds.add(c1.ContactId);
      system.debug('***********c1.ContactId:*****************'+c1.ContactId);
     Map<Id,String> ContactEmail = new Map<Id, String>();
     Map<Id, String> ContactFirstname = new Map<Id, String>();
     
     for(Contact c2: [select id, email from Contact where id IN :contactIds])
    {
         system.debug('*************c2*************:'+c2);
         EmailTemplate et=[SELECT Id, DeveloperName , IsActive FROM EmailTemplate WHERE DeveloperName = 'Outage_is_cleared'];
         system.Debug('**************et************'+et);
        
        ContactEmail.put(c2.id,c2.email);
        system.debug('*************c2.id:*****************'+c2.id);
        system.debug('*************c2.email:*****************'+c2.email);
        
 //     if (c1.Send_Mail__c == True) 
  //  {
      system.debug('************c1.CaseNumber:*****************'+c1.CaseNumber);

      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      String[] toAddresses = new String[] {ContactEmail.get(c2.id)}; 
      mail.setToAddresses(toAddresses);
      mail.setSubject('Email to Contact');
      mail.setUseSignature(false);
      string msg = '';
      mail.setHtmlBody(msg);
      mail.setBccSender(false);
      mail.setSaveAsActivity(True);          
       mail.setTemplateId(et.Id);
      //mail.treatbodiesastemplate();
      // Send the email
      Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
      system.debug('*************Email is sent***********************>'+mail);
        }
    }
//  }

}

Thnx,
Utz

  • November 21, 2017
  • Like
  • 0
Hello,

I am writing trigger where i want to update child case when parent case field is updated. 
In debug logs parent field value assigned to child field value but update action is not performing on child case.

trigger CaseT on Case (before update, after update) {

if( Trigger.isBefore && Trigger.isUpdate )
{
    for(Case c : Trigger.New){
        c.desc__c = c.Description;
    }
    }
    
   
if( Trigger.isAfter && Trigger.isUpdate )
{    
      if(AvoidRecursion.isFirstRun())
    {
   
      
Set<Id> parentIds = new Set<Id>();
    
           for(Case p:trigger.new) {
           system.debug('******CASE ID******'+ p.id);
            
            if((p.CaseNumber != null)) {
                parentIds.add(p.Id);
             }
           }
       
        System.debug('------------- Parent Ids -------- ' + parentIds);
    
        if(parentIds.size() != null) {
            for(case c : trigger.new){
            for(Case ch : [SELECT Id, Status, Notes__c, ContactId, ParentId  FROM Case WHERE Id=:parentIds]) {
               system.debug('********Child Cases*********'+ch);
                 ch.Notes__c = c.Notes__c;
                 ch.ContactId = c.ContactId;
                
                system.debug('ch.Notes__c 1'+ch.Notes__c );
                system.debug('ch.ContactId 1 '+ch.ContactId );
         
            
                update ch;
                
                system.debug('***********ch.Notes__c 2***********'+ch.Notes__c );
                system.debug('***********ch.ContactId 2**********'+ch.ContactId );
            }

            }
            }
            
            }
           
            
        }
    }


thanks & best regards,
Utz
  • November 01, 2017
  • Like
  • 0
Hello,

I want to develop functionality where mail should be send to related cases when mail sent to parent case.
How can we achive this?

Thanks & Regards,
Utkarsha
  • October 27, 2017
  • Like
  • 0
Hello,

I have written a test class. Its code coverage is 745. I want to increase its coverage.

Test class:
@isTest
private class CreateNewQuoteTest {
    private static testMethod void testManipulateOrders(){
       
        Pricebook2 customPB = new Pricebook2(Name='SDEC GBP Distributor Price Sheet', isActive=true);
        insert customPB;
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = customPB.id ;
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = 'Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

       Id pricebookId = Test.getStandardPricebookId();

        system.debug('standardPb--------------->test'+pricebookId);
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = pricebookId;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
      
        PricebookEntry custompbe2 = new PricebookEntry();
        custompbe2.Pricebook2Id = customPB.Id;
        custompbe2.Product2Id = p.Id;
        custompbe2.UnitPrice = 1;
        custompbe2.IsActive = true;
        custompbe2.UseStandardPrice = false;
        insert custompbe2 ;  
        
        Opportunity o = new Opportunity();
        o.Name = 'Opp';
        o.AccountId = a.Id;
        o.CloseDate= system.today();
        o.StageName = 'Proposal';
        insert o;
        update o;
             
        Quote q = new Quote();
        q.Name= o.Id;
        q.OpportunityId = o.Id;
        q.status = 'Draft'; 
        q.Pricebook2Id = customPB.id;
        insert q;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Quote__c = q.Id;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Opportunity__c = o.Id;
        d.Quote__c = q.Id;
        insert d;
               
        test.StartTest();

        o.StageName = 'Closed Won';
        o.Invoice__r.size();
        system.debug('test---------o.StageName'+o.StageName);
        system.debug('test---------o.Invoice__r.size()'+o.Invoice__r.size());
       
        if(o.StageName  == 'Closed Won' && o.Invoice__r.size() == 0){
                Invoice__c i2 = new Invoice__c();
                system.debug('test---------Invoice'+i2);
        }
        update o;   
               test.StopTest();  

    } 
    
    private static testMethod void testManipulateOrders1(){
          
        Pricebook2 customPB = new Pricebook2(Name='SDEC GBP Distributor Price Sheet', isActive=true);
        insert customPB;
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = customPB.id;
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = 'Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

        Id pricebookId = Test.getStandardPricebookId();

        system.debug('standardPb--------------->test'+pricebookId);
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = pricebookId;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
      
        PricebookEntry custompbe2 = new PricebookEntry();
        custompbe2.Pricebook2Id = customPB.Id;
        custompbe2.Product2Id = p.Id;
        custompbe2.UnitPrice = 1;
        custompbe2.IsActive = true;
        custompbe2.UseStandardPrice = false;
        insert custompbe2 ;   
        
        Opportunity o = new Opportunity();
        o.Name = 'Test opportunity';
        o.AccountId = a.Id;
        o.CloseDate= system.today();
        o.StageName = 'Proposal';
        
        insert o;
        update o;
        
        Quote q = new Quote();
        q.Name= o.Id;
        q.OpportunityId = o.Id;
        q.status = 'Draft'; 
        q.Pricebook2Id = customPB.id;

        insert q;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Quote__c = q.Id;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Opportunity__c = o.Id;
        d.Quote__c = q.Id;
        insert d;
        
       test.StartTest();
              
        o.StageName = 'Closed Won';
        o.Delivery_Notes__r.size();
        system.debug('test---------o.StageName'+o.StageName);
        system.debug('test---------o.Delivery_Notes__r.size()'+o.Delivery_Notes__r.size());
      
        if(o.StageName  == 'Closed Won' && o.Delivery_Notes__r.size() == 0)
                {
            Delivery_Notes__c newDelivery = new Delivery_Notes__c();
            system.debug('test---------Delivery'+newDelivery);
                }
           //update o;
           
          else if(o.StageName  != 'Closed Won' && o.Delivery_Notes__r.size() != 0)
          {
        system.debug('o.StageName  == Closed Won && o.Delivery_Notes__r.size() == 0');
           }

       test.StopTest(); 
      
    }

     private static testMethod void testManipulateOrders2(){
     
        Pricebook2 customPB = new Pricebook2(Name='SDEC GBP Distributor Price Sheet', isActive=true);
        insert customPB;
       
        Account a = new Account();
        a.Name = 'Test Account';
        a.Price_Book__c = customPB.id;
        insert a;
        
        Contact c = new Contact();
        c.LastName='test';
        insert c;

        Product2 p = new Product2();
        p.Name = 'Test Product ';
        p.Description='Test Product Entry 1';
        p.productCode = 'ABC';
        p.isActive = true;
        p.Family = 'Blackbox'; 
        insert p;

        Id pricebookId = Test.getStandardPricebookId();

        system.debug('standardPb--------------->test'+pricebookId);
        PricebookEntry standardPrice = new PricebookEntry();
        standardPrice.Pricebook2Id = pricebookId;
        standardPrice.Product2Id = p.Id;
        standardPrice.UnitPrice = 1;
        standardPrice.IsActive = true;
        standardPrice.UseStandardPrice = false;
        insert standardPrice ;    
      
        PricebookEntry custompbe2 = new PricebookEntry();
        custompbe2.Pricebook2Id = customPB.Id;
        custompbe2.Product2Id = p.Id;
        custompbe2.UnitPrice = 1;
        custompbe2.IsActive = true;
        custompbe2.UseStandardPrice = false;
        insert custompbe2 ;   
        
        Opportunity o = new Opportunity();
        o.Name = 'Test opportunity';
        o.AccountId = a.Id;
        o.CloseDate= system.today();
        o.StageName = 'Proposal';
        
        insert o;
   
        Quote q = new Quote();
        q.Name= o.Id;
        q.OpportunityId = o.Id;
        q.status = 'Draft'; 
        q.Pricebook2Id = customPB.id;

        insert q;
         
        Order od = new Order();
        od.Name = 'Test';
        od.AccountId = a.Id;
        od.status = 'Draft'; 
        od.Your_Order_Reference__c = '123';
        od.EffectiveDate = system.today();
        od.Pricebook2Id =customPB.Id;
        od.OpportunityId = o.Id;
        od.QuoteId= q.id;
        insert od;
       // update od;
        
        Invoice__c i = new Invoice__c();
        i.Account__c = a.Id;
        i.Quote__c = q.Id;
        insert i;
        
        Delivery_Notes__c d = new Delivery_Notes__c();
        d.Account__c = a.id;
        d.Opportunity__c = o.Id;
        d.Quote__c = q.Id;
        insert d;
        
        test.StartTest();
              
        od.status = 'Closed Won';
        od.Orders.size();
        system.debug('test--------- od.status'+ od.status);
        system.debug('test---------od.Orders.size()'+od.Orders.size());
      
        if( od.status  == 'Closed Won' && od.Orders.size() == 0)
                {
         Order newOrder = new Order();
         newOrder.AccountId = a.Id;
         newOrder.OpportunityId = o.Id;
       //  newOrder.QuoteId = q.SyncedQuoteId;
         newOrder.Status = 'Closed Won';
         newOrder.EffectiveDate = system.today();
         newOrder.Pricebook2Id = o.Pricebook2Id;
        insert newOrder;
            system.debug('test---------Order'+newOrder);
                }
       update od;

       test.StopTest(); 
      
    }
}


Trigger:
User-added imageUser-added image

Its giving an error System.DmlException: Update failed. First exception on row 0 with id 0068E00000BqCLfQAN; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateNewQuote: execution of AfterUpdate

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

caused by: System.QueryException: List has no rows for assignment to SObject

Thanks & regards,
Utz
  • October 05, 2017
  • Like
  • 0
Hello,
I want some changes in my code suppose there is already invoice record for opportunity then it should not create invoice when we update opportunity
trigger CreateNewQuote on Opportunity(after insert , after update) {

        
        for (Opportunity o1 : Trigger.new){
        if(o1.StageName  == 'Closed Won' ){
     
        Invoice__c newInvoice = new Invoice__c();
        System.debug('New Inovice Is Created');
         newInvoice.Account__c = o1.AccountId;
         newInvoice.Opportunity__c = o1.Id;
         newInvoice.Quote__c =  o1.SyncedQuoteId;
       //newInvoice.Pricebook2Id = o1.Pricebook2Id;

        insert newInvoice;
        System.debug('Invoices Created with data:='+newInvoice); 

    }
    }      
}
}
  • September 13, 2017
  • Like
  • 0
Hello,

I am creating invoice lie item same as quote line item. My code is giving error of recursive call. can someone help me with this.

trigger CreateInvoiceLineItem on Invoice__c(after insert, after update) {
/* This Trigger Creates Invoice Line Item. Invoice Line Item will be Same as Quote Line Item 
We need to set pricebook for Invoice
Ref: https://developer.salesforce.com/forums/?id=906F00000008llQIAQ */

Invoice__c inv = trigger.new[0];
system.debug('List of Invoice:'+inv);
   
// Fetch Quote Id for Invoice
Quote oppId = [SELECT AccountId, Id, Pricebook2Id FROM Quote where id=:inv.Quote__c];
system.debug('Quote Ids '+oppId);
    
// Fetch Quote Lines 
List<QuoteLineItem> opplines=[select id, quantity, PriceBookEntry.Product2Id ,UnitPrice,PriceBookEntry.Pricebook2Id
from QuoteLineItem where QuoteId=:oppId.id];

system.debug('List Of Quote Line Item  '+opplines);


    // Loop Opportunity Lines
    for(QuoteLineItem oppline:opplines){
        
        // Create Order Line Object
        Invoice_Line_Item__c OrderLine = new Invoice_Line_Item__c();
        OrderLine.Invoice__c= inv.Id;
      //OrderLine.Product2Id = oppline.PriceBookEntry.Product2Id;
        OrderLine.Quantity__c = oppline.Quantity;
      //OrderLine.PriceBookEntryId  = oppline.PriceBookEntryId;
        OrderLine.Unit_Price__c = oppline.UnitPrice;
      //oppline.PriceBookEntry.Pricebook2Id
              insert OrderLine;

    }
}

thanks & best regards,
utz
  • September 07, 2017
  • Like
  • 0
Hello, 

I am writing trigger on Opportunity Object. In this there is child (Invoice) object of opportunity. On Invoice object i have taken custom lookup field. 
It lookup to Quote object. I am creating new Invoice. Here i want to capture Quote ID. How to get Quote Id here?

trigger CreateNewQuote on Opportunity (after insert , after update) {
/* This trigger creates new quote record when opportunity is created
 * Ref: https://developer.salesforce.com/forums/?id=906F00000008llQIAQ */
    
if (Trigger.isAfter) {
  if (Trigger.isInsert) {
      
    for (Opportunity o: Trigger.new){
        System.debug('List Of Opportunity'+o);
        if(o.Name  != Null ){
        
        Quote newQuote = new Quote();
        System.debug('New Quote Is Created');

        newQuote.OpportunityId = o.Id;
        newQuote.Name  = o.Name ;
        newQuote.Status = 'Draft';
      //  newQuote.Pricebook2Id = o.AccountId.Pricebook2Id;

        System.debug('Quote Created with data'+newQuote);
                insert newQuote;
        }
    }
}
    if (Trigger.isUpdate) {
        
        for (Opportunity o1 : Trigger.new){
        if(o1.StageName  == 'Closed Won' ){
     
        Inovice__c newInvoice = new Inovice__c();
        System.debug('New Inovice Is Created');
         newInvoice.Name ='Invoice';
         newInvoice.Account__c = o1.AccountId;
         newInvoice.Opportunity__c = o1.Id;
         newInvoice.Quote__c =     o1.QuoteId;
         newInvoice.Status__c = 'Pending';
       //  newInvoice.Pricebook2Id = o1.Pricebook2Id;

        insert newInvoice;
        System.debug('Invoices Created with data'+newInvoice); 

    }
    }      
    }
    
}
}

 
Thanks & Regards,
Utz
  • September 06, 2017
  • Like
  • 0
Hello,

When Opportunity record is created then Quote record gets created automatically using process builder. But i want to add Opportunity line item as Quote line item same time. I have created process builder on opportunity product and use refernce to map the fields. But its giving me error and i  am not able to save product in that case.

I am using Professional Edition hence trigger and flows are not allowed. I have to do this using process builder only. 
Is there any solution to complete this task?

Thanks & Regards,
​Utkarsha
  • August 22, 2017
  • Like
  • 0