• Jay reddy
  • NEWBIE
  • 30 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 34
    Questions
  • 20
    Replies
I have a batch class and I'm trying to write a test class for that batch class but the test class is not covering the execute method. Could someone please help me on this. 
global class ACMContactDocumentExpiration implements Database.Batchable<sObject>,database.stateful {

   public List<Aircraft_Training__c> AirTrn = new List<Aircraft_Training__c>();
    public List<Crew_Staff__c> Crewlist=new List<Crew_Staff__c>();
    public List<Experience__c> Exp = new List<Experience__c>();
    public List<Training__c> Trn = new List<Training__c>();
    public List<Contact> Con = new List<Contact>();
    global Database.QueryLocator start(Database.BatchableContext BC)
   {
        AirTrn = [Select Id, Name, Experience__c,Experience__r.Name, Aircraft_Rating__c, PPC_Expiration_Date__c, PPC_Date__c, Training_Date__c FROM Aircraft_Training__c WHERE PPC_Expiration_Date__c =: Date.today()+Integer.valueOf(System.label.AL_PPC_Expiration_Days)];
        Set<String> AirTrnIds = new Set<String>();
        for(Aircraft_Training__c a: AirTrn)
            {
                AirTrnIds.add(a.Experience__r.Name);
            }
            system.debug('----------'+AirTrnIds.size()); 
        
        Exp = [Select Id, Name, Contact__c, Contact__r.Id, Last_Recurrent_Date__c FROM Experience__c WHERE Name IN: AirTrnIds AND (Last_Recurrent_Date__c =: Date.today()-Integer.valueOf(System.label.Exp_Last_Recurrent_Days) OR Last_Recurrent_Date__c != null OR Last_Recurrent_Date__c =: null)];
        Set<String> ExpIds = new Set<String>();
        for(Experience__c e: Exp)
            {
                ExpIds.add(e.Contact__r.Id);
            }
            system.debug('----------'+ExpIds.size());
            
        Trn = [Select Id, Name, Contact__c, Contact__r.Id, Expiration_Date__c, Exam_Date__c, Training_Type__c FROM  Training__c WHERE Expiration_Date__c =: Date.today()+Integer.valueOf(System.label.Training_Expiration_Days) AND (Training_Type__c =: System.label.Training_Type_Intl_Procedures OR Training_Type__c =: System.label.Training_Type_RVSM)];
        Set<String> TrnIds = new Set<String>();
        for(Training__c t: Trn)
            {
                TrnIds.add(t.Contact__r.Id);
            }
            system.debug('----------'+TrnIds.size()); 
            
        Con = [Select Id, Email FROM Contact WHERE ID IN: ExpIds OR ID IN: TrnIds]; 
        Set<String> ConIds = new Set<String>();
        for(Contact c: Con)
            {
                ConIds.add(c.Id);
            }
            system.debug('----------'+ConIds.size());
        
        string query= 'Select Id, Contact__c, Contact__r.Name, Active_License__r.License_Type__c, Active_Medical__r.Medical_Type__c,  Mandate_Record_Type__c,  Contact_Record_Type__c, License_Expiration_Date__c, Medical_Expiration_Date__c,Training_Expiration_Date__c, Crew_Email__c from Crew_Staff__c WHERE Contact__r.Id IN : ConIds';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Crew_Staff__c> scope) {
        List<Crew_Staff__c> newCrew = new List<Crew_Staff__c>();
        Set<Id> newCrewIds = new Set<Id>();
        for(Crew_Staff__c crew:scope) {               
        if(
            
            ((crew.Contact_Record_Type__c == 'Pilot') &&
            (crew.Mandate_Record_Type__c == 'ACM') &&
            (crew.Crew_Email__c != null)) ||
            (date.valueof(crew.License_Expiration_Date__c) == System.today()+Integer.valueOf(System.label.Date_2)) ||
            (date.valueof(crew.Medical_Expiration_Date__c) == System.today()+Integer.valueof(System.label.Medical_Expiration_Days))
          
          ) {        
            Crewlist.add(crew);
            }
            newCrewIds.add(crew.Id);
        }
          system.debug('----------'+Crewlist.size());
         
      
    }
    
    global void finish(Database.BatchableContext BC) {    
    system.debug('------>'+Crewlist.size());
 
    List<Messaging.SingleEmailMessage> maillist  = new List<Messaging.SingleEmailMessage>();
        
        if(Crewlist.size()>0) {       
            for(Crew_Staff__c crewrec:Crewlist)
            {
                // Query on OrgWideEmailAddress would set "FROM address" in the email
                OrgWideEmailAddress[] owea = [Select Id From OrgWideEmailAddress where Address = 'test@test.com'];
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                if (owea.size()>0) {
                    mail.setOrgWideEmailAddressId(owea.get(0).Id);
                }
                mail.setSubject('Pilot Documents Expiring Soon');
                mail.setToAddresses(new String[]{crewrec.Crew_Email__c});              
                mail.setReplyTo('flightops@acass.ca');
                string htmlBody;
              
                htmlBody =  '<p><span style=font-family:calibri, monospace> Dear  '+ crewrec.Contact__r.Name +', </span> </p>' +
               '<p><span style=font-family:calibri, monospace> This is a friendly reminder that you have the following documents coming due for renewal: </span></br>';
              
                          
                  String lType = crewrec.Active_License__r.License_Type__c;
                  Date lExpDate = date.newInstance(crewrec.License_Expiration_Date__c.year(), crewrec.License_Expiration_Date__c.month(), crewrec.License_Expiration_Date__c.day() );
                  String mType = crewrec.Active_Medical__r.Medical_Type__c;
                  Date mExpDate = crewrec.Medical_Expiration_Date__c;
                  htmlBody += +lType+ ' license will expire on ' +lExpDate+'</br>';
                  htmlBody += +mType+ ' medical will expire on ' +mExpDate+'</br>';
          
              for(Training__c t: Trn)
              {
                  String tType = t.Training_Type__c;
                  Date tExpDate = t.Expiration_Date__c;
                  htmlBody += +tType+' training will expire on ' +tExpDate +'</br>';
              }
              
              for(Aircraft_Training__c a1: AirTrn)
              {
                  String aName = a1.Aircraft_Rating__c;
                  Date aPPCexp = a1.PPC_Expiration_Date__c;
                  htmlBody += +aName+' aircraft training will expire on ' + aPPCexp +'</br>'; 
              }              
              
            
              htmlBody += '<p><span style=font-family:calibri, monospace> Please send clear, colour photos/scans the renewed document  prior to the expiration date. </span></p>'+
              '<p><span style=font-family:calibri, monospace>Kindest regards,</span></br>'+
              '<span style=font-family:calibri, monospace>Flight Operations </span></p>';
              mail.setHtmlBody(htmlBody);
               maillist.add(mail);         
            
            }
            Messaging.sendEmail(maillist);
        }
     }
 
@isTest
public class SendEmailToCrewJobscheduledtest {

public static testmethod void myUnitTest() {


List<Contact> con = new List<Contact>();
Contact c = new Contact(
Accident_Note__c = 'Test',FirstName = 'Test',LastName = 'test');
con.add(c);
insert con;

Test.startTest();


String CRON_EXP = '0 0 0 3 9 ? 2022';
String jobId = System.schedule('SendEmailToCrewJobscheduledtest', CRON_EXP, new SendEmailToCrewJobscheduled());
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; 
System.assertEquals(0, ct.TimesTriggered); 
System.assertEquals('2022-09-03 00:00:00', String.valueOf(ct.NextFireTime)); 


ACMContactDocumentExpiration b = new ACMContactDocumentExpiration();
Database.QueryLocator q1 = b.start(null);
Database.executeBatch(b, 200);

Test.stopTest();
}
}

 
Heya mates,

I'm trying to create multiple child records with the help of apex, when the parent record is created. My issue is there is picklist field on Child object with 20 values and when we create a parent record, the apex should create 20 different child records based on the picklist value on child object.

OBJECTS: CustomObjA, CustomObjB [Masterdetail]

I know below code is very ametuer, which explains my range in apex coding. Also, the code should be builkfied.
 
trigger CreateBuyingInfluence on CustomObjA (after insert)

 {
    List<CustomObjB> Childs = new List<CustomObjB>();

    for(CustomObjA a : trigger.new)
    {
       CustomObjB Child = new CustomObjB ();
       Child.SCOP__c = a.id;
       Child.Name = 'testName'; 

       Childs.add(Child);      
    }

    insert Childs;
}

 
Heya mates,

I'm trying to access a custom label in apex class but I guess I'm missing something.

My custom label: Date
value = System.today()+30

I'm referencing this custom label in apex class but it's throwing me an error as "invalid date"
 
Date endvalue = Date.valueOf(System.Label.Date);
        //String n = System.Label.Date_2;
        
        for(Contact con:scope) {
        
       
        if(date.valueof(con.License_Expiration_Date__c) == endvalue ) {
        
            Conlist.add(crew);
           }
          }
I really appreciate if someone could help me.
 
When creating an Opportunity I'm trying to setup an opportunity record type/page layout that will automatically be applied based on the Account record type chosen. My users already choose from a drop down with creating an account, so I don't want them to have to do it again when creating an opportunity. it should just be assigned based off the account record type choosen dynamically.

Tried Workflows, PB ... didn't work! Can't use URL hack because of lightning. 
For instance, we have "Custom Object A" and "Custom Object B" (Master-detail relationship). And Custom Object A has Record Type 'A' & 'B', Custom Object B has Record Types 'A1' & 'B1'. So, whenever I create a custom object 'A' record with record type 'A' and try to create a child object (Cus. Object B) through related list of Cus. Object A, it should automatically select record type 'A1' of Cus. object 'B' and same with record type 'B1' of cus. object B.

If (Custom Object A's record RT is A ---> Then Custom Object B's record RT should 'A1')
If (Custom Object A's record RT is B ---> Then Custom Object B's record RT should 'B1')

I've tried PB, WF, VR... but doesn't meet my requirement cuz i need the logic to be applied while creating the records of Cus. Object B, not after creating the record (needed to be in ligtning). There's coding solution for this requirement (below is the link) but it doesn't work if we click "Cancel" or "Save & New" button. I really appreciate if anyone could help.
https://force201.wordpress.com/2011/05/21/automatically-setting-the-record-type-of-a-detail-object-based-on-the-record-type-of-its-master-object/ 
 
Heya Mates!

I have requirement where I have to replicate a javascript button for Lightning version. As we know, we cannot have Javascript button in Lightning. I'd like to have the same button in Lightning version. Below is the Javascript code for the button in Classic version.

Any help is appreciated!

Many Thanks!
GR
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')} 
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')} 
try{ 
jQuery(function() { 
/*Append the jQuery CSS CDN Link to the Head tag.*/ 
jQuery('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css" type="text/css" />'); 

/*Create the HTML(DIV Tag) for the Dialog.*/ 
var html = 
'<div id="dialog" title="Questionnaire"><p>Please ask for Contact Birthdate</p><p>Please ask for Contact Email address</p><p>Please ask for Contact Phone Number</p></div>'; 

/*Check if the Dialog(DIV Tag) already exists if not then Append the same to the Body tag.*/ 
if(!jQuery('[id=dialog]').size()){ 
jQuery('body').append(html); 
} 

/*Open the jQuery Dialog.*/ 
jQuery( "#dialog" ).dialog({ 
autoOpen: true, 
modal: true, 
show: { 
effect: "bounce", 
duration: 1000 
}, 
hide: { 
effect: "bounce", 
duration: 1000 
}, 
buttons: { 
"Continue": function() { 
location.replace('/home/home.jsp'); 
jQuery( this ).dialog( "close" ); 
}, 
Cancel: function() { 
jQuery( this ).dialog( "close" ); 
} 
} 
}); 
}); 
} 
catch(e){ 
alert('An Error has Occured. Error: ' + e); 
}

 
I have received an email from SALESFORCE regarding WINTER '18 APEX COMPLIER CHANGES [ACTION REQUIRED: Code Changes Required for your Apex Compiler].
 
https://help.salesforce.com/articleView?id=000264742&type=1&language=en_US

in that, could someone help me understanding the BEHAVIOR 6

BEHAVIOR 6:

"Account" type binds to "Schema.Account" when namespace is null or empty
The compiler is not correctly requiring the use of the Schema namespace when there is a user-defined type with the same name. For example, in the following code, the type Contact should be specified to be in the Schema namespace if there is also a Contact class in the same implicit namespace:

public map<String, Contact> getContacts(List<String> mails){
return getContactsByMap([SELECT Id, Email FROM Contact WHERE Email IN :mails]);
}

It's possible that your code is not behaving the way you expect because it may be binding to a different type than the one you intended. In other words, if you have shadowed a standard SObject type with an apex class of the same name, this change will cause your custom class to take precedence over the standard SObject type, unless the Schema namespace is explicitly specified.
Suggested fix
We suggest fixing the code by prepending the correct namespace to types in the Schema namespace if a name collision with a user-defined type is possible, and you intend to bind to the Schema SObject type.

public map<String, Schema.Contact> getContacts(List<String> mails){
return getContactsByMap([SELECT Id, Email FROM Contact WHERE Email IN :mails ]);
}

I really appreciate your time and help.

Thanks
GR
 
Hi all,

I have an email about Code changes required for Apex compiler. In that, one of the scenario is binding SCHEMA to objectname in the code.

Should I have to add/ modify map<Id, OpportunityLineItem> TO map<Id, Schema.OpportunityLineItem> in all codes??

I appreciate your help.



User-added image
Thanks
GR
Hi,

I've recently recieved an email from Salesforce regarding Code Changes Required for Apex compiler.

in that they have stated that ILLEGAL ANNOTATIONS are not supporitive anymore. Just wondering what are the legal annotations in APEX? Could anyone help me in knowing that?

Thanks,
GR
Hi,

I've recieved an email from Salesforce about Apex Compiler - Product & Service Notification. In that,one of the scenario is removing the FINAL keyword on Variables.

Does it mean to remove the FINAL keyword from the below instances

#1) Decimal finalAmountOnTR = 0;
#2) private final Integer listLimit = 1000;

Thanks,
GR
 
Hello,

I'm getting javascript error when entering a text with line break in a field, which is mentioned in the javascript code. Is there a way to skip that error from a line break. I used JSENCODE but it's working for special characters only and not for line breaks. Below is the way I have defined the field in Javascript.
 
var field = '{!JSENCODE(Opportunity.Closing_instructions__c)}';
field = field.replace(/(/\r?\n|\r/),"");
Thanks,
GR
 
Hello,

I'm stuck with updating the records when one of the records is deleted from the list. Below is the code which updates the terms and Conditions related list in the quote when a quote line item is added to the quote. I'd like to delete the related Terms and Conditions of a product from the T&C Related list once the product is removed from the quote. Could someone help on that, please?
 
public string updateTAC(string errorMsg) {
           try {
            list < String > productIDs = new list < string > ();
            list < Id > produc_code = new list < Id > ();
            list < String > produc_c = new list < String > ();
            map < Id, Terms_and_Conditions_Quote__c > tacToInsert = new map < Id, Terms_and_Conditions_Quote__c > ();

            for (integer index = 0; index < quoteLineItems.size(); index++) {
                productIDs.add(quoteLineItems[index].productCode);
            }
            for (Product2 Pcode: [select id from Product2 where ProductCode in : productIDs]) {
                produc_code.add(Pcode.id);
            }

            for (Terms_and_Conditions_Product__c tac: [SELECT CreatedById, CreatedDate, Terms_and_Conditions__c, CurrencyIsoCode, Id, IsDeleted, LastModifiedById, LastModifiedDate, Name, OwnerId, Product__c
                    FROM Terms_and_Conditions_Product__c where Product__c in : produc_code
                ])
                tacToInsert.put(tac.Terms_and_Conditions__c, new Terms_and_Conditions_Quote__c(Quote__c = quoteID, Terms_and_Conditions__c = tac.Terms_and_Conditions__c));

            if (!tacToInsert.IsEmpty()) { //now we need to compare to avoid duplicats           
                map < Id, Terms_and_Conditions_Quote__c > TACToCompare = new map < Id, Terms_and_Conditions_Quote__c > ([select id, Description__c, Terms_and_Conditions__c
                    from Terms_and_Conditions_Quote__c where quote__c = : quoteID
                ]);

                for (Terms_and_Conditions_Quote__c tempTAc: tacToInsert.values()) {
                    for (Terms_and_Conditions_Quote__c OldTact: TACToCompare.values()) {
                        if (OldTact.Terms_and_Conditions__c == tempTAc.Terms_and_Conditions__c) {
                            //strForTestingissuesMsg += tempTAc.Terms_and_Conditions__c;
                            tacToInsert.remove(tempTAc.Terms_and_Conditions__c);
                            break;
                        }
                    }
                }

                insert tacToInsert.values();
            }

        } catch (Exception e) {
            errorMsg = e.getMessage();
        } 
        return errorMsg; 
    }
Thanks,
GR
 
Hello Everyone,

I have a VF page and controller residing on Opportunity Pagelayout. Whenever a field "Check" (Checkbox) is checked on the Opportunity page, the main page url replace with this VF page url. The controller grabs the attachment in the sent email and saves it Notes & Attachment section. But sometimes I'm getting "Failed to load resource: the server responded with a status of 500 (Server Error). Salesforce" error. Could someone help me out, please?
 
<apex:page standardController="Opportunity" rendered="true">
<script src="/soap/ajax/27.0/connection.js" type="text/javascript"></script>
 <script type="text/javascript">

if({!Opportunity.Check__c == True})
 {
 
 var p = new sforce.SObject("Opportunity");
 p.Id = "{!Opportunity.Id}";

var URL = "/apex/AttachmentUploadController?id={!Opportunity.Id}";

parent.window.location.href = URL; 

p.Check__c = false; 
result = sforce.connection.update([p]); 

}
 
 </script>
</apex:page>
public class CopyAttachmentToOpptyController {
 
    // Constructor - this only really matters if the autoRun function doesn't work right
    private final Opportunity o;
    public CopyAttachmentToOpptyController(ApexPages.StandardController stdController) {
        this.o = (Opportunity)stdController.getRecord();
    }
    
     
    // Code we will invoke on page load.
    public PageReference autoRun() {
    
        List<Attachment> attachmentsToInsert = new List<Attachment>(); 
        String theId = ApexPages.currentPage().getParameters().get('id');
 
        if (theId == null) {
            // Display the Visualforce page's content if no Id is passed over
            return null;
        }      
        
        Set<ID> emailMsgID = new Set<ID>();
        List<EmailMessage> ems = [SELECT Id, ToAddress, ParentId, relatedtoid FROM EmailMessage where relatedtoid =:theId AND HasAttachment  = true ];
        for (EmailMessage em : ems) {
            emailMsgID.add(em.Id);
        }
        system.debug('emailMsgID-->'+emailMsgID);
        
        
        List<Attachment> attachmentList = [SELECT Id, ParentId, name, OwnerId, body from Attachment where ParentId IN: emailMsgID];
        List<Attachment> alreadyAttached = [SELECT Id, ParentId, name, OwnerId, body from Attachment where ParentId =: theId];
        
        system.debug('attachmentList -->'+attachmentList);
        system.debug('alreadyAttached -->'+alreadyAttached);
               
        Set<ID> skipAttachment = new Set<ID>();
     /*  for (Attachment a : attachmentList){
            for(Attachment al :alreadyAttached){  
                if(a.name == al.name){      
                    skipAttachment.add(a.Id);
                }
            } 
        } */
        
        for (Attachment a : attachmentList){  
            if(!skipAttachment.contains(a.Id)){      
                Attachment att = new Attachment(ParentId = theId, Name = a.name, Body = a.body);
                attachmentsToInsert.add(att);
            }
        }
        
        system.debug('attachmentsToInsert-->'+attachmentsToInsert);
        
        if (attachmentsToInsert.size() > 0) {
            insert attachmentsToInsert;
        }        
         
          
        // Redirect the user back to the original page
       /* PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
        pageRef.setRedirect(true);
        return pageRef; */
        
        return new PageReference('/' + theId);
 
    }
 
}
Thanks,
GR

 
Hello Everyone,

We have a button "Send Email" at the Opportunity level. Upon on clicking it a field at the opportunity will automatically checked and the page would re-direct to standard "Send Email" page. After sending the email with attachments the page re-directs to the Opportunity main page and a VF page with controler runs/replace the main page url to save the attachments to the Notes & Attachment section. But sometimes it take ages to reload and even throws time limit exceeded error. Could someone help me out on this, please?

Below is the Visualforce page and it's controller to save the Attachments in the Send an Email to the Opportunity's Notes & Attachments section.
 
<apex:page standardController="Opportunity" extensions="CopyAttachmentToOpptyController" action="{!autoRun}">
  <apex:sectionHeader title="Auto-Running Apex Code"/>
  <apex:outputPanel >
      You tried calling Apex Code from a button.  If you see this page, something went wrong.  You should have 
      been redirected back to the record you clicked the button from.
  </apex:outputPanel>
</apex:page>
public class CopyAttachmentToOpptyController {
 
    // Constructor - this only really matters if the autoRun function doesn't work right
    private final Opportunity o;
    public CopyAttachmentToOpptyController(ApexPages.StandardController stdController) {
        this.o = (Opportunity)stdController.getRecord();
    }
     
    // Code we will invoke on page load.
    public PageReference autoRun() {
    
        List<Attachment> attachmentsToInsert = new List<Attachment>(); 
        String theId = ApexPages.currentPage().getParameters().get('id');
 
        if (theId == null) {
            // Display the Visualforce page's content if no Id is passed over
            return null;
        }      
        
        Set<ID> emailMsgID = new Set<ID>();
        for (EmailMessage em:[SELECT Id, ParentId, relatedtoid FROM EmailMessage where relatedtoid =:theId ]) {
            emailMsgID.add(em.Id);
        }
        system.debug('emailMsgID-->'+emailMsgID);
        
        List<Attachment> attachmentList = [SELECT Id, ParentId, name, body from Attachment where ParentId IN: emailMsgID];
        List<Attachment> alreadyAttached = [SELECT Id, ParentId, name, body from Attachment where ParentId =: theId];
        
        system.debug('attachmentList -->'+attachmentList);
        system.debug('alreadyAttached -->'+alreadyAttached);
               
        Set<ID> skipAttachment = new Set<ID>();
      /*  for (Attachment a : attachmentList){
            for(Attachment al :alreadyAttached){  
                if(a.name == al.name){      
                    skipAttachment.add(a.Id);
                }
            }
        } */
        
        for (Attachment a : attachmentList){  
            if(!skipAttachment.contains(a.Id)){      
                Attachment att = new Attachment(ParentId = theId, Name = a.name, Body = a.body);
                attachmentsToInsert.add(att);
            }
        }
        
        system.debug('attachmentsToInsert-->'+attachmentsToInsert);
        
        if (attachmentsToInsert.size() > 0) {
            insert attachmentsToInsert;
        }        
         
          
        // Redirect the user back to the original page
       /* PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
        pageRef.setRedirect(true);
        return pageRef; */
        
        return new PageReference('/' + theId);
 
    }




 
Hello,

Can anyone help how to add Upload / attach button in VF page. On clicking it it should allow uploading documents from local computer.

thanks,
Girish
Hello,

I need help on saving the manually attached document at the send email page to the Opportunity's Notes & Attachment section. Is it possible?User-added image
Hello,
I need a help on having a conga custom button on Opportunity that would grab only quotelineitems from PRIMARY quote and put them in a pdf. I have query to pull the quote line items but need help on writing that soql query in the button.

Thanks,
GR
Hello,
I need a help on having a conga custom button on Opportunity that would grab only quotelineitems from PRIMARY quote.

Thanks,
GR
Hi,

Could someone help me on this soql 101 queries error issue. I'm hitting the error for this query "oldCRList=[Select Id from OpportunityContactRole where ContactId in : ContactId  and OpportunityId in : OppId];" . I know querying inside the for loop is the root cause for this issue but could someone help me on this, please.
 
trigger OpportunityPrimaryContactRole on Opportunity (after insert, after update) { 
    if(CheckRecursive.executeOpportunityPrimaryContactRoleTrigger == false){return;}
    
    
    List<Opportunity> NewOpptyLst = new List<Opportunity> ();
    Map<id,Opportunity> OpptyOldMap = new Map<id,Opportunity>();
    NewOpptyLst = Trigger.new;
    OpptyOldMap = Trigger.OldMap;
    
    
    List<OpportunityContactRole> newCRList = new List<OpportunityContactRole>();
    List<OpportunityContactRole> oldCRList = new List<OpportunityContactRole>();
    
    
    Set<Id> OppId = new Set<Id>();
    Set<Id> ContactId = new Set<Id>();     

    List<OpportunityContactRole> CRList = [ Select Id from OpportunityContactRole where ContactId in : ContactId  and OpportunityId in : OppId];
    
    
    for(Opportunity o: NewOpptyLst)
    {//Checks if the Opportunity is being inserted
        if(Trigger.isInsert)
        {    
            if(o.Buyer_Name__c != null)
            {   //Creates the new OCR       
                newCRList.add(new OpportunityContactRole (ContactId=o.Buyer_Name__c, OpportunityId=o.Id, Role='Decision Maker',IsPrimary=TRUE));                        
            } 
        }
        else 
        {
       
            if(o.Buyer_Name__c != null && OpptyOldMap.get(o.Id).Buyer_Name__c != null)
                { //Gets the Contact and Opportunity Id from the prior values and adds to this set         
                    try
                    {
                        Opportunity oldOppObj=OpptyOldMap.get(o.Id);
                        OppId.add(OldoppObj.id);
                        ContactId.add(oldOppObj.Buyer_Name__c); 
                        System.debug('Opp Size:' + OppId.size());
                        if (OppId.size()>0) 
                        oldCRList=[Select Id from OpportunityContactRole where ContactId in : ContactId  and OpportunityId in : OppId]; 
                        
                        
                        
                        if(oldOppObj.Buyer_Name__c != o.Buyer_Name__c)
                        {
                            if (oldCRList.size()>0)                         
                            delete oldCRList;                            
                            newCRList.add(new OpportunityContactRole (ContactId=o.Buyer_Name__c, OpportunityId=o.Id, Role='Decision Maker',IsPrimary=True));                                                

                        }
                        else
                        {  
                            if (oldCRList.size()==0)
                            {    System.debug('- Update during no single contact role and having buyer name');                         
                            newCRList.add(new OpportunityContactRole (ContactId=o.Buyer_Name__c, OpportunityId=o.Id, Role='Decision Maker',IsPrimary=True));                            
                            }
                            else
                            {   System.debug('- Update during no primary contact role and having buyer name');                        
                                if (oldCRList.size()==1) 
                                {
                                  for (OpportunityContactRole old:oldCRList)
                                   {
                                   old.Role = 'Decision Maker';
                                   old.IsPrimary=True;
                                   update oldCRList;
                                   }
                                }
                            }
                            
                        }
                    } 
                    catch(Exception e)
                    {  System.debug(e);
                    } 
                }   
        }
    }
    try
    { 
        if(newCRList.size()>0) insert newCRList;
    }   
   catch(Exception e)
    {        trigger.new[0].addError('A technical error has occurred creating the Opportunity Contact Role.');
    }

}

 
Hi,

I trying to do roll up summary on Opportunity amount but I need to exclude the duplicate records.

We have this custom obj and Opportunity (Master detail relation) Custom obj is master and opp is detail object. We add Opp records to Cust Obj record via related list. We want to have a roll up summary on opportunity records amount but need to exclude the duplicates Opportunities if there are any. Any help is appreciated
For instance, we have "Custom Object A" and "Custom Object B" (Master-detail relationship). And Custom Object A has Record Type 'A' & 'B', Custom Object B has Record Types 'A1' & 'B1'. So, whenever I create a custom object 'A' record with record type 'A' and try to create a child object (Cus. Object B) through related list of Cus. Object A, it should automatically select record type 'A1' of Cus. object 'B' and same with record type 'B1' of cus. object B.

If (Custom Object A's record RT is A ---> Then Custom Object B's record RT should 'A1')
If (Custom Object A's record RT is B ---> Then Custom Object B's record RT should 'B1')

I've tried PB, WF, VR... but doesn't meet my requirement cuz i need the logic to be applied while creating the records of Cus. Object B, not after creating the record (needed to be in ligtning). There's coding solution for this requirement (below is the link) but it doesn't work if we click "Cancel" or "Save & New" button. I really appreciate if anyone could help.
https://force201.wordpress.com/2011/05/21/automatically-setting-the-record-type-of-a-detail-object-based-on-the-record-type-of-its-master-object/ 
 
Hello,

I have a requirement where I need to access Campaign Influence records in the Opportunity related list by SOQL query. Basically, I need to access it because I have custom object looking up to CAMPAIGN. And I want to show all opportunities in that custom object related list "Opportunities" upon on adding the Campaign in the custom object.

Thanks,
GR
Heya mates,

I'm trying to create multiple child records with the help of apex, when the parent record is created. My issue is there is picklist field on Child object with 20 values and when we create a parent record, the apex should create 20 different child records based on the picklist value on child object.

OBJECTS: CustomObjA, CustomObjB [Masterdetail]

I know below code is very ametuer, which explains my range in apex coding. Also, the code should be builkfied.
 
trigger CreateBuyingInfluence on CustomObjA (after insert)

 {
    List<CustomObjB> Childs = new List<CustomObjB>();

    for(CustomObjA a : trigger.new)
    {
       CustomObjB Child = new CustomObjB ();
       Child.SCOP__c = a.id;
       Child.Name = 'testName'; 

       Childs.add(Child);      
    }

    insert Childs;
}

 
When creating an Opportunity I'm trying to setup an opportunity record type/page layout that will automatically be applied based on the Account record type chosen. My users already choose from a drop down with creating an account, so I don't want them to have to do it again when creating an opportunity. it should just be assigned based off the account record type choosen dynamically.

Tried Workflows, PB ... didn't work! Can't use URL hack because of lightning. 
For instance, we have "Custom Object A" and "Custom Object B" (Master-detail relationship). And Custom Object A has Record Type 'A' & 'B', Custom Object B has Record Types 'A1' & 'B1'. So, whenever I create a custom object 'A' record with record type 'A' and try to create a child object (Cus. Object B) through related list of Cus. Object A, it should automatically select record type 'A1' of Cus. object 'B' and same with record type 'B1' of cus. object B.

If (Custom Object A's record RT is A ---> Then Custom Object B's record RT should 'A1')
If (Custom Object A's record RT is B ---> Then Custom Object B's record RT should 'B1')

I've tried PB, WF, VR... but doesn't meet my requirement cuz i need the logic to be applied while creating the records of Cus. Object B, not after creating the record (needed to be in ligtning). There's coding solution for this requirement (below is the link) but it doesn't work if we click "Cancel" or "Save & New" button. I really appreciate if anyone could help.
https://force201.wordpress.com/2011/05/21/automatically-setting-the-record-type-of-a-detail-object-based-on-the-record-type-of-its-master-object/ 
 
Hi all,

I have an email about Code changes required for Apex compiler. In that, one of the scenario is binding SCHEMA to objectname in the code.

Should I have to add/ modify map<Id, OpportunityLineItem> TO map<Id, Schema.OpportunityLineItem> in all codes??

I appreciate your help.



User-added image
Thanks
GR
Hello,

I'm getting javascript error when entering a text with line break in a field, which is mentioned in the javascript code. Is there a way to skip that error from a line break. I used JSENCODE but it's working for special characters only and not for line breaks. Below is the way I have defined the field in Javascript.
 
var field = '{!JSENCODE(Opportunity.Closing_instructions__c)}';
field = field.replace(/(/\r?\n|\r/),"");
Thanks,
GR
 
Hello,

Can anyone help how to add Upload / attach button in VF page. On clicking it it should allow uploading documents from local computer.

thanks,
Girish
Hello,
I need a help on having a conga custom button on Opportunity that would grab only quotelineitems from PRIMARY quote and put them in a pdf. I have query to pull the quote line items but need help on writing that soql query in the button.

Thanks,
GR

Hi All, this is a Lightning question.

I am wondering how to prepopulate / preset field values in a standard page layout using standard "New" functionality. Use case:

I have a Parent Object and a Child Object. The Child object should derive it's record type dynamically from the parent object.

    E.g. a picklist on the Parent has the values Type A, Type B, Type C

When a new child record is created from the parent, I would like to dynamically set the record type of the child to A, B, C.

The page layouts are different for each A, B and C. I would like to use the standard functionality of "New Child" to create these records. 

Quick Actions: do not allow dynamic binding of record type. They also do not have the capability to use standard page layouts. So having a unique button per record type is unacceptable. 

URL Hacks: Work great in classic - unsupported in LEX. 

Thanks in advance. 

Hello,

I have a requirement where I need to access Campaign Influence records in the Opportunity related list by SOQL query. Basically, I need to access it because I have custom object looking up to CAMPAIGN. And I want to show all opportunities in that custom object related list "Opportunities" upon on adding the Campaign in the custom object.

Thanks,
GR
Hello,

I have a requirement where we have Subscription products and in that some should be sold for definite time period [3 months] and the rest of the products from the similar category can be sold for any time period. For this I have created a CUSTOM SETTING for the products which should be sold for definite time period [3 months] but seems my logic is incorrect and throwing the same second error [see below in the code] for the products which are in CUSTOM SETTING. They do have different error.
 
Set<String> ExcludeSubProdIds = new Map<String, Product2> ([Select Name,ProductCode from Product2 WHERE  ProductCode IN: SubscriptionProducts__c.getAll().keySet()]).keySet();

for(Quotelineitem qli:QLIList){
if(qli.Product_Code__c.contains('SUB')) {
             if(ExcludeSubProdIds.contains(qli.Product_Code__c) && (qli.Number_of_Terms__c !=3 || decimavalue!=0) ){
             qli.adderror('Error. Please check dates');
             }  else if(!ExcludeSubProdIds.contains(qli.Product_Code__c) && (qli.Number_of_Terms__c==  0 ||decimavalue!=0))  {
             qli.adderror('Term Periods must be in whole months (for SUB products) and whole years  products.');
         }
             }
             }

 
Hi,

New bee.

I need to copy a custom field [formula field] at QuoteLineItem level to custom field [currency] at OpportunityLineItem level.

I tried to write the below trigger. It saved but not displaying any results.

I need to copy Total price with Total discount & Var at quotelineitem level to "total price discount" at OpportunityLineItem level.

trigger TotalPriceDiscount on QuoteLineItem  (after insert, after update) {

try {

List<OpportunityLineitem> OppItem = new List<OpportunityLineitem>();
Set<Id> ids = new Set<Id>();

    for(QuoteLineItem qItem: Trigger.new) {
    
    if(qItem.Product2 != null) {
    
    Ids.add(qItem.Product2Id);
    }
    }
     Map<id, OpportunityLineItem> OppliMap = new Map<id, OpportunityLineItem>([Select id, Total_Price_Discount__c from OpportunityLineItem Where Id in :Ids]);     
    
    for(QuoteLineItem qli : Trigger.new) { 
   // for(OpportunityLineItem Oppli : Trigger.new) {
  //  QuoteLineItem qli = qliMap.get(Oppli.Product2Id);
      OpportunityLineItem Oppli = OppliMap.get(qli.Product2Id);
    
   Oppli.Total_Price_Discount__c =   qli.Total_Price_with_Total_Discount_VAR__c;
    OppItem.add(Oppli);
    }
    update OppItem;
    }
    catch(Exception e){
   System.debug('ERROR: '+ e);
 }
}

Note: there can be multiple quotelineitems and same number at opportunity products.

 Appreciate quick help

Thanks,
G
Hi Everyone,

I have requirement based on the below conditions.

3 objects [Case, Contact, CustomObj]

Contact and CustomObj have lookup relationship.... and case is created based on contact.

My requirement is CustomObj appears as a related list in CONTACT record... I need bring that same CustomOBJ related list to CASE records whenever that particular CONTACT is added or CASE created on that CONTACT.... How can I achieve this.. I tried to edit layout but no luck it is not showing as related list instead appear in Extended lookup area...

Hi,

 I am new in Salesforce...I want to design a pop up window. The window will appear after save button is hit which will show the values those an user has entered as input. After the pop up comes out then the user will click the ok in pop up and the page will be redirected to the object view page.

 

Now how can I implement it throgh java script or any other possible way.

Can u pls provide some sample coding for it.

 

Thanks in advance,

  • September 28, 2011
  • Like
  • 0

hi guys,

how to attach a pdf file to 'notes & attachments' part of an object?

i was able to generate a pdf file using the visualforce with a custom controller.

then they ask to automatically generate and Attach the pdf file to the 'notes & attachment' as well when you press the custom 'buttons and links'.

all i can find is how to attach it to email.

can anyone help? thanks in advance.