• Aman Malik
  • SMARTIE
  • 531 Points
  • Member since 2017

  • Chatter
    Feed
  • 16
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 128
    Replies
Hi,

I need help on the below lines to cover in my test class , its not entering the if conditiona nd the coverage is 60%

 if(!allLinksMap.isEmpty()){
            labelList.addAll(allLinksMap.keySet());
            
            for(String labelLink : labelList){
                Custom_Links_For_Lightning__c myCustomSetting = allLinksMap.get(labelLink);
                mapLabelLink.put(myCustomSetting.Home_page_Header_Section__c+'_'+myCustomSetting.Label_for_Custom_Link__c,myCustomSetting.Links_for_Home_Page__c);
            }​

 
MY APEX CLASS :

public with sharing class BAU_CustomLinkForLightning {
    
    public static Map<String,String> mapLabelLink = new Map<String,String>();	
    
    @AuraEnabled
    public static Map<String,String> getCustomLinks(){
        system.debug('inside code***');
        Map<String, Custom_Links_For_Lightning__c> allLinksMap = Custom_Links_For_Lightning__c.getAll();
        List<String> labelList = new List<String>();
        
        if(!allLinksMap.isEmpty()){
            labelList.addAll(allLinksMap.keySet());
            
            for(String labelLink : labelList){
                Custom_Links_For_Lightning__c myCustomSetting = allLinksMap.get(labelLink);
                mapLabelLink.put(myCustomSetting.Home_page_Header_Section__c+'_'+myCustomSetting.Label_for_Custom_Link__c,myCustomSetting.Links_for_Home_Page__c);
            }
            system.debug('ALL LABEL LINK VALUES***'+mapLabelLink);
        }
        return mapLabelLink;
    }
    
}
 
MY TEST CLASS

@isTest
public class BAU_CustomLinkForLightningTest {
    @testsetup
    static void createData(){
        List<QantasConfigData__c> lstConfigData = new List<QantasConfigData__c>();
        lstConfigData.add(TestUtilityDataClassQantas.createQantasConfigData('Log Exception Logs Rec Type','Exception Logs'));
        insert lstConfigData;

        TestUtilityDataClassQantas.createQantasConfigDataAccRecType();
    }
     public static testmethod void getCustomLinkstest() {
        system.debug('*****insidemethod*******');
        //TestUtilityDataClassQantas.enableTriggers();
        BAU_CustomLinkForLightning bau = new BAU_CustomLinkForLightning();
        BAU_CustomLinkForLightning.getCustomLinks();
        List<Custom_Links_For_Lightning__c> custlinklightning= new List<Custom_Links_For_Lightning__c>();
        custlinklightning.add(new Custom_Links_For_Lightning__c(Name='A380 Cabin Update Fact sheet',Home_page_Header_Section__c='Essential Reading',Label_for_Custom_Link__c='A380 CA380 Cabin Update Fact sheet',Links_for_Home_Page__c='https://www.qantasnewsroom.com.au/wp-content/uploads/2017/08/A380-Cabin-Update-Fact-Sheet.pdf'));
        system.debug('*****custlinklightning******'+custlinklightning);
        insert custlinklightning;
     }          
 }

Pls help me , thanks
 
Hello all,

I am having some trouble with an Apex Trigger test class I'm writing. I am using a developer sandbox and am getting the following error:
System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: a0D6A0000015UKi: []

What I am trying to do is update a Lookup field that looks up to a Rate Sheet based on certain criteria. (Rate_Sheet__c = API Name)

I wrote the trigger and had no errors that I could see but when writing the test class it kept giving me the Insufficient Access error. Not really sure what the problem is. Under sharing settings, my org wide defaults gives public read/write access to all objects needed.

Please see the following Apex Trigger and Test Class code:
trigger UpdateRatesheetLookup on Quote (before insert, before update) {

    for (Quote quo : Trigger.new) {
       
        if (quo.TotalPrice < 3000 && quo.Buyout_Type__c == 'FMV') {
            // Sets Rate Sheet Lookup
            quo.Rate_Sheet__c = 'a0D6A0000015UKi';
            
        } else if (quo.TotalPrice < 10000 && quo.Buyout_Type__c == 'FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKj';
            
        } else if (quo.TotalPrice >= 10000 && quo.Buyout_Type__c == 'FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKk';
            
        } else if (quo.TotalPrice < 3000 && quo.Buyout_Type__c == 'Promo FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKl';
            
        } else if (quo.TotalPrice < 10000 && quo.Buyout_Type__c == 'Promo FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKm';
            
        } else if (quo.TotalPrice >= 10000 && quo.Buyout_Type__c == 'Promo FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKn';
            
        } else if (quo.TotalPrice < 3000 && quo.Buyout_Type__c == '$1-out') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKo';
            
        } else if (quo.TotalPrice < 10000 && quo.Buyout_Type__c == '$1-out') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKp';
            
        } else if (quo.TotalPrice >= 10000 && quo.Buyout_Type__c == '$1-out') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKq';
            
        } else {
            quo.Rate_Sheet__c = Null;
        }
    }
}

// Problem is happening at insertion of the myQuote instance.
@isTest
private class UpdateRateSheetLookupTest {
    
    @isTest static void updateQuote() {
        
        // Create an Account & Set Required Fields
        Account myAccount = new Account();
        myAccount.Name    = 'Sample Account';
        insert myAccount;
        
        // Create an Opportunity on the Account & Set Required Fields
        Opportunity myOpportunity = new Opportunity();
        myOpportunity.Name        = 'Sample Opportunity';
        myOpportunity.CloseDate   = Date.today();
        myOpportunity.StageName   = 'Proposal';
        myOpportunity.AccountId   = myAccount.Id; // Relates to id of account above.
        insert myOpportunity;
            
        // Fire the UpdateRatesheetLookup Trigger
        // Create a Quote associated with Opportunity & Set Required Fields
        Quote myQuote          = new Quote();
        myQuote.Name           = 'Sample';
        myQuote.OpportunityId  = myOpportunity.Id; // Relates to id of opportunity above.
        //myQuote.TotalPrice   = 2500;
        myQuote.Buyout_Type__c = 'FMV';
       	insert myQuote; // FLAG: PROBLEM HERE
        
        // Update the Quote
        myQuote.Description = 'Test';
       	update myQuote;
    }
}

Any help with this would be greatly appreciated. 
Thanks in advance!
 
I'm getting errors with the component not being able to see the controller action.

error:

Uncaught Unknown controller action 'getLogEntry'
Callback failed: serviceComponent://ui.flexipage.components.page.FlexipageControllerV2/ACTION$getPage


Compnent code
<aura:component controller="CaseLogController" 
                implements="force:appHostable,flexipage:availableForAllPageTypes"
                access="global">

    <!--Include the css from static resource-->
    <ltng:require styles="{!$Resource.SLDS +
             '/assets/styles/salesforce-lightning-design-system-ltng.css'}"  afterScriptsLoaded="{!c.doScriptLoad}"/>

    <aura:attribute name="start" type="String"/>
    <aura:attribute name="stop" type="String"/>
    <aura:attribute name="sObj" type="String"/>
    <aura:attribute name="field" type="String"/>
    <aura:attribute name="stopwatch" type="Object"/>
    <aura:attribute name="LogEntry" type="Case_Log__c[]"/>
    
    <!-- Handle component initialization in a client-side controller -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <div class="slds-clearfix slds-card">
		<div class="slds-text-heading_medium slds-align_absolute-center">
            <div aura:id="time">
                Time: 00:00:00
            </div>
        </div>
        <div class="slds-button-group slds-align_absolute-center" role="group">
                <button id="start" class="slds-button slds-button_success" onclick="{!c.onClick}">Start</button>
                <button id="stop" class="slds-button slds-button_brand" onclick="{!c.onClick}">Pause</button>
                <button id="reset" class="slds-button slds-button_destructive" onclick="{!c.onClick}">Finish</button>
        </div>
        
           <ul>
      <aura:iteration items="{!v.LogEntry}" var="log">
         <li type="dice">Entry Name : {!log.Name}</li>
         <hr/>
      </aura:iteration>
   </ul>
    </div>
</aura:component>

controller code
({
     doInit: function(component, event, helper) {
     //call apex class method
      var action = component.get("c.getLogEntry");
      action.setCallback(this, function(response) {
       //store state of response
       var state = response.getState();
       if (state === "SUCCESS") {
        //set response value in LogEntry attribute on component.
        component.set('v.LogEntry', response.getReturnValue());
       }
      });
      $A.enqueueAction(action);
     },
    doScriptLoad : function(component, event, helper) {

	},

    onClick : function(component, event, helper) {
        var div = component.find("time").getElement();
        var id = event.target.id;
        var	clsStopwatch = function() {
            // Private vars
            var	startAt	= startAt || 0;	// Time of last start / resume. (0 if not running)
            var	lapTime	= lapTime || 0;	// Time on the clock when last stopped in milliseconds

            var	now	= function() {
                return (new Date()).getTime();
            };

            // Public methods
            // Start or resume
            this.start = function() {
                
    
                startAt	= startAt ? startAt : now();
            };

            // Stop or pause
            this.stop = function() {
                // If running, update elapsed time otherwise keep it
                lapTime	= startAt ? lapTime + now() - startAt : lapTime;
                startAt	= 0; // Paused
            };

            // Reset
            this.reset = function() {
                lapTime = startAt = 0;
            };

            // Duration
            this.time = function() {
                return lapTime + (startAt ? now() - startAt : 0);
            };
        };

        var stopwatch = component.get("v.stopwatch");
        var x = stopwatch || new clsStopwatch();
        if(!stopwatch){
        	component.set("v.stopwatch", x);
        }

        function pad(num, size) {
            var s = "0000" + num;
            return s.substr(s.length - size);
        }

        function formatTime(time) {
            var h = 0;
            var m = 0;
            var s = 0;
            var newTime = '';

            h = Math.floor( time / (60 * 60 * 1000) );
            time = time % (60 * 60 * 1000);
            m = Math.floor( time / (60 * 1000) );
            time = time % (60 * 1000);
            s = Math.floor( time / 1000 );

            newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2); 
            return newTime;
        }

        function update() {
            div.innerHTML = "Time: " + formatTime(x.time());
        }

   		switch(id){
            case "start":
                
                setInterval(update, 1000);
                x.start();
                break;
            case "stop":
                x.stop();
                update();
                break;
            case "reset":
                x.stop();
                x.reset();
                update();
                break;
            default:
                stop();
                break;
        }
        

	}
})

Apex class code
 
public with sharing class CaseLogController {

    public static List<Case_log__c> getLogEntry() {
        list<Case_Log__c> l = [SELECT Id, Case__c, Name, In_Progress__c, Length__c, Time__c 
                             		FROM Case_Log__c WHERE In_Progress__c = true LIMIT 1];
        
        if (l.size() == 0) {
            Case_log__c newlog = new Case_log__c();
            l.add(newlog);
            insert l;
        }
        return l;
    }
    
}

 
I am new to Apex Programming and I am trying to get through this error message. 
Below is the code that I am working on
trigger DeDupe on Lead (before insert) {
         for(Lead myLead : Trigger.new)
         {
             //Searching for matching contacts.Assigning them to the list by using bind variable. By using : with Apex Variable myLead
             List<contact> matchingContacts = [SELECT Id FROM Contact
                                              WHERE Email = :myLead.Email];
              System.debug(matchingContacts.size() + 'contact(s) found.'); 
              if(!matchingContact.isEmpty())    
              {
                  //Assign the lead to the data quslity queue
                  Group dataQualityGroup = [SELECT ID FROM Group
                                            WHERE DeveloperName ='Data_Quality'
                                            LIMIT 1];
                  myLead.OwnerID = dataQualityGroup.Id;
                 
                  //Add the dupe contact IDS into the Lead description
                  String ContactMessage = 'Duplicate Contacts Found:\n';
                  for(Contact c = matchingContacts)
                  {
                        ContactMessage += c.FirstName + ' '
                                          + c.LastName + ' '
                                          + c.Account.Name + '('       
                                          + c.Id + ;
                  }
                  myLead.Description = ContactMessage +'\n' + myLead.Description;
                }
             }
}

And I am getting following error messsage:
Error: Compile Error: Invalid identifier '        '. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. 
Hello! how to run skript only if checkbox Project__c.check__c is checked
 
<script>
        var int=self.setInterval(function(){callActionFunction()},200);
        function callActionFunction(){
            ActionFunctionName();
        }

</script>

 
Global class TmsEmailDemo 
{
public static void sendEmail() 
{
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
// Who you are sending the email to
   List<String> sendTo = new List<String>();
    sendTo.add('xyz@gmail.com');
    sendTo.add('abc@gmail.com');
	mail.setToAddresses(sendTo);
    System.debug(sendTo);

  mail.setTargetObjectId('0037F00000FWFGo');

   // The email template ID used for the email
   mail.setTemplateId('00X7F000000pTjc');
    				   
   //mail.setWhatId(candidate);    
   mail.setBccSender(false);
   mail.setUseSignature(false);
   mail.setReplyTo('cvb@gmail.com');
   mail.setSenderDisplayName('Ajay');
   mail.setSaveAsActivity(false);  
 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }  
}
HI can anyone help me on how to Automate Email So that every day at 10 AM the email should be delivered.
Thanks in advance
 
I have created a form in the Salesforce Support console that updates knowledge fields when you push the save button. This all works perfectly. However after you hit save the visualforce page changes to the Case Record in the small area the form was. I would like it to stay on the form and not change after the save button is push. I am not sure how I do this.

<apex:page showHeader="false" standardStylesheets="false" standardController="Case" pageStyle="Left"> <style> p.small { line-height: 0.5; } </style> <font face = "Arial" align="left" style="font-size:11px" color="454545"> <table style="width:100%"> <apex:form > <apex:pageBlock > <apex:pageBlockSection columns="1"> <apex:commandButton action="{!save}" value="Save" id="theButton"/> <apex:inputField value="{!Case.Steps__c}"/> <apex:inputField value="{!Case.Environment__c}"/> <apex:inputField value="{!Case.Additional_Information__c}"/> <apex:inputField value="{!Case.Answer__c}"/> </apex:pageblocksection> </apex:pageBlock> </apex:form> </table> </font> </apex:page>
 
Hi there, 

I am currently working through:-

https://developer.salesforce.com/docs/atlas.en-us.eclipse.meta/eclipse/eclipse_quickstart.htm

I have gotten all the way down to the bottom all fine and am doing Step 3. add the tests.

I get everything set up correctly as per the instructions - see screenshot ( there are no test suites that appear but I understand that the Test suites need to be created)

I then hit test and then I get an error asking about the classId and className either missing or null - second screenshotFirst screenshot

Second screenshot

I am running on Eclipse Oxygen with the latest JDK ( Mars and Nova didn't seem to work at all on my machine despite many attempts at aiming eclipse to the Java/bin on my Mac)

 
Hi All,
While writing  triggers, i am getting below error

Error: Compile Error: Variable does not exist: First_Name at line 5 column 3    
Code:

trigger HelloWorld on Lead (before Update)
 {
for(lead l: Trigger.New)
{
l.FirstName ='Hello';
l.LastName  ='World';
}
}
I'm trying to create a visualforce page from the following javascript but I keep getting multiple error messages.
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}

sforce.connection.sessionId = "{!$Api.Session_ID}";

var E = new sforce.SObject("Lead");
E.id = '{!Lead.Id}';

// Replace below with your field.
E.To_Be_Set_Up__c=true;

// Replace below with your field.
E.Status = 'Converted';

// save the change
sforce.connection.update([E]);

//refresh the page
window.location.reload();
Hello,

I have a Master-detail relationship between Train-Ticket.
Using a SOQL query on Ticket I need to obtain a field value of the associated train.
This is the query I'm using : 
 public static void ticketInfo(ID ticketId){
        Ticket__c ticket = [SELECT ID,Name,PAX_Type__c, Train__r.FPU_Train_Category__c
                            FROM Ticket__c 
                            WHERE ID =: ticketID];
        system.debug(ticket);
    }

The issue is that instead of the desired field (FPU_Train_Category__c) it returns the Train's ID. I tried Train__r.Name and it still returned the ID.

Thanks a lot for explaining this to me!
Have a nice day

 

Hi ,

I am getting below Error when i am trying to update a "Contact Name" in Case Object (In After Insert). 

Error  : PrimaryAssociateType: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 5001F000000w4LpQAI; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.PrimaryAssociateType: line 60, column 1

My Trigger

trigger PrimaryAssociateType on Case_Associate__c (Before Insert, After Insert) {
    
    Set<Id> caseId = New Set<Id>();
    set<Id> caseId1 = New Set<Id>();
    List<case> updtCon = New List<case>();
    Map<Id,Case_Associate__c> casMap  = New Map<Id,Case_Associate__c>(); 
    
    if(Trigger.isBefore && Trigger.isInsert){
        For(Case_Associate__c  ca : Trigger.New){
            If(ca.Case_Number__c != Null){
                CaseId.add(ca.Case_Number__c);
                System.debug('Case Number | ' + CaseId);
            }
        }
        
        IF(CaseId.size() > 0){
            List<Case_Associate__c> cas = [Select id,name,Case_Number__c,Associate_Type__c from Case_Associate__c Where Case_Number__c =:CaseId AND Associate_Type__c = 'Primary'];
            System.debug('Case Associate Type With Primary |' + cas);
            System.debug('Size Of Primary | ' + cas.Size());
            Case_Associate__c cast1 = New Case_Associate__c();
            String curPage = ApexPages.currentPage().getUrl();
            IF(cas.Size() > 0 && curPage.contains('Primary')){
                System.debug('Primary is Already Created');
                for(Case_Associate__c  cas1 : Trigger.New){
                    cas1.addError('Primary Associate Type was Already Created. So Please Choose "Secondary" or "Other" ');
                } 
            } else {
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Case Associate Created Successfully'));
                System.debug('Secondary || Other');
            }
        }
    }
    
    if(Trigger.isAfter && Trigger.isInsert){  
        For(Case_Associate__c ca1 : Trigger.New){
            IF(ca1.Case_Number__c != Null && ca1.Entity_Type__c == 'Provider' && ca1.Associate_Type__c == 'Primary'){
                caseId1.add(ca1.Case_Number__c);
                casMap.put(ca1.Case_Number__c,ca1);
                System.debug('Case Number 1 | ' + caseId1);
            }
        } 
        
        System.debug('caseId1.size() | ' + caseId1.size());
        IF(caseId1.size() > 0){
            for(string irow : casMap.keyset()){
                Case c = New Case(id=irow);
                System.debug('&&&&&&& irow |'+ irow);
                c.ContactId = casMap.get(irow).Entity1__c;
                system.debug('Contact Id |' + c.ContactId);
                updtCon.add(c);
            }
            System.debug('&&&&&&&&&  Size Of updtCon |' + updtCon.size());
            If(updtCon.size() > 0){
                Insert updtcon;
            }
        }
    }
}
Regards,
Soundar.
How to Cover the test class for Loop?
 

User-added image
@istest

Private class dummy_email_testclass{
     static testMethod void dummy_email_testclassa(){
         Contact con=new Contact();
         
         COn.Lastname='test';
         con.Email='test@gmail.com';
         
         insert con;
         update con;
         
     }
}



Hi,

I am trying to get a list of field names, sizes types and lengths by using the url
https://eu9.salesforce.com/services/data/v37.0/sobjects/Account/describe

but I only get a lot of data like
{"activateable":false,"childRelationships":[{"cascadeDelete":false,"childSObject":"Account","deprecatedAndHidden":false,"field":"ParentId","relationshipName":"ChildAccounts","restrictedDelete":false},

..yet no field list

What am I doing wrong? Please help
Hello all,

I'm trying to create a VFP with Opportunity as the Standard controller and an extension controller.

I'd like to get the fields values from the current Opportunity.
I've tried many codes but I get error messages 

Here is one code:
// Visualforce //
<apex:page standardcontroller="Opportunity" extensions="MyController">
etc ...

// Controller //
public Opportunity opt { get; set; }
public MyController(ApexPages.StandardController sc) {
     theId = ApexPages.currentPage().getParameters().get('id');
     opt = (Opportunity) sc.getRecord(); 
     }

Unfortunately for this line opt = (Opportunity) sc.getRecord();  I get the error message "Incompatible types since an instance of SObject is never an instance of Opportunity" 
From this controller, I want to reach the current fields values and the fields values from the related objects.
Any idea, please?
Many thanks
Nuno.
I am opening a Lightning App on a button Click (via URL). The App updates Description field on Contact Object. Below is my code -
ConApp
<aura:application >
    <aura:attribute name="id" type="String"/>
	hi {!v.id}
    <c:ConAppCmp conid="{!v.id}" />
</aura:application>

conAppCmp
<aura:component controller="MyControl">
    <aura:attribute name="conObj" type="Contact" />
    <aura:attribute name="conid" type="String"/>
    <p>hi {!v.conid}</p>
    <aura:attribute name="replaceProducts" type="List" default="['red','blue']"/>
    <ui:inputSelect aura:id="levels" label="Available Replacements">
        <aura:iteration items="{!v.replaceProducts}" var="level">
             <ui:inputSelectOption text="{!level}"  value="{!v.conObj.Description}" label="{!level}"/>
        </aura:iteration>
    </ui:inputSelect>
    <lightning:button variant="brand" label="Submit" onclick="{! c.handleClick }" />
</aura:component>

conAppCmpController.js
({
	handleClick : function(component, event, helper) {
		var newAcc = component.get("v.conObj");
        var action = component.get("c.saveRecord");
        action.setParams({ 
        "acc": newAcc
            });
        action.setCallback(this, function(a) {
           var state = a.getState();
            if (state === "SUCCESS") {
                var name = a.getReturnValue();
               alert("hello from here"+name);
            }
        });
         $A.enqueueAction(action)

	}
})

myControl
public with sharing class MyControl {
@AuraEnabled
    public static Contact saveRecord(Contact acc) {
        upsert acc;
        return acc;
    }
}
Button Contains this URL - 
/c/ConApp.app?id={!Contact.Id}

I don't know what is causing the problem.
 
I reached at this trailhead for sending SMS through Twilio. But I am Getting These Errors while saving the Controller. 
  1. Invalid type: TwilioRestClient
  2. Invalid type: TwilioSMS
  3. Variable does not exist: sms
Hi All,

I'm unable to deserialize a string even when the value is not null. Here is my code snippet.

​public static List<ObjectA> processSelected(String constr) {
        system.debug('constr===>'+constr);  //getting value in this
        List<dupeContact> conList = (List<dupeContact>)JSON.deserialize(constr, List<dupeContact>.class);
        system.debug('dupeContact====>'+conList);     
        List<ObjectA> selectedContacts = new List<ObjectA>();
        if (conList != null && conList.size() >0) { 
            for (dupeContact  cCon : conList) {
                if (cCon.selected == true) {
                    selectedContacts.add(cCon.con);
                }
            }
        }

Thanks in Advance  :)
Hi,
As i am new to salesforce, i need some help in writing test calss. The following is the trigger code.

trigger HoldingEmailPhoneMobileUpdate on Contact (before insert, before update) {
 if(trigger.isInsert||trigger.isUpdate){
              for(Contact con:trigger.new){
                if(con.Holding_Email_Valid__c== True){
                  con.Email=con.Holding_Email__c;
                  }
                if(con.Holding_Phone_Valid__c==True){
                 con.Phone=con.Holding_Phone__c;
                
                 }
                if(con.Holding_Mobile_Valid__c==True){
                 con.MobilePhone=con.Holding_Mobile__c;
                } 
               }
           }
        }

Can you Please provide me the test code for the above trigger.

Thanks,
Balaji A
@isTest(seeAllData=true)
private class Test_OpportunityLineItemCheck 
{
  static testMethod void Checkduplicate() 
  { 
       Test.startTest();                       
        Account accP = new Account(Name = 'Partner1', Account_Type__c = 'VAR - MANAGED', RecordTypeId='01280000000Ln6i', Business_Unit__c = 'CBU');

        insert accP;
        
        PricebookEntry[] pbes = [Select Id, UnitPrice, CurrencyIsoCode, Pricebook2Id from PricebookEntry where IsActive = true AND UnitPrice > 0 
            AND CurrencyIsoCode = 'USD' AND Name like 'UK%'];
            
            Opportunity opp4 = new Opportunity(Name= 'Opp31',Pricebook2Id = pbes[0].Pricebook2Id,RecordTypeId = '01280000000Lnks');

        insert opp4;
                        
        OpportunityLineItem oli4 = new OpportunityLineItem(OpportunityId = opp4.Id, PricebookEntryId = pbes.get(0).Id, Quantity = 1, SBA_Price__c=20, GovEd__c=0, Partner_Discount__c=0, Promo_Discount__c=0, Deal_Reg_Discount__c=0);
        
        OpportunityLineItem[] olilist=new OpportunityLineItem[]{oli4};
      
        insert olilist;
        
        OpportunityLineItemCheckOperations.OppWrapper empW = new OpportunityLineItemCheckOperations.OppWrapper();
         empW.compareTo(empW);  
       Test.stopTest();
  }    
 }

I have created the Test class mentioned in the code sample it's having only 69% of code coverage , plz suggest me how to increase code coverage. 
Trigger is as below:
trigger CMbeforeUpdate on CM__c (before Update) {
    List<CM__c> listCMUpdate = new List<CM__c>();
    for(CM__c cm : trigger.new) {
        if(cm.CM_Reason__c != trigger.oldMap.get(cm.id).CM__c 
            || cm.Location__c != trigger.oldMap.get(cm.id).Location__c
            
            || cm.Credit_LOB__c != trigger.oldMap.get(cm.id).Credit_LOB__c) {
            listCMUpdate.add(cm);
        }
    }
    if( listCMUpdate.size() > 0)
    { 
        CM_Handler.updateReasonCategoryCode(listCMUpdate);
        CM_Handler.CMapproverdetails(listCMUpdate);
    }    
}
The test class is:
@isTest
public class CMbeforeUpdatetest {
static testMethod void testCheck() {
   CM__c cm= new CM__c();
    cm.name = 'test';
    cm.CM_Reason__c = 'test';
    cm.Location__c = 'test';
 
  
    insert cm; 
    
    cm.Location__c = 'test123';
    
    update cm;
   
  }
}
the coverage is 70%. Need to cover " listCMUpdate.add(cm);" part, How to do that?
Hi,

I need help on the below lines to cover in my test class , its not entering the if conditiona nd the coverage is 60%

 if(!allLinksMap.isEmpty()){
            labelList.addAll(allLinksMap.keySet());
            
            for(String labelLink : labelList){
                Custom_Links_For_Lightning__c myCustomSetting = allLinksMap.get(labelLink);
                mapLabelLink.put(myCustomSetting.Home_page_Header_Section__c+'_'+myCustomSetting.Label_for_Custom_Link__c,myCustomSetting.Links_for_Home_Page__c);
            }​

 
MY APEX CLASS :

public with sharing class BAU_CustomLinkForLightning {
    
    public static Map<String,String> mapLabelLink = new Map<String,String>();	
    
    @AuraEnabled
    public static Map<String,String> getCustomLinks(){
        system.debug('inside code***');
        Map<String, Custom_Links_For_Lightning__c> allLinksMap = Custom_Links_For_Lightning__c.getAll();
        List<String> labelList = new List<String>();
        
        if(!allLinksMap.isEmpty()){
            labelList.addAll(allLinksMap.keySet());
            
            for(String labelLink : labelList){
                Custom_Links_For_Lightning__c myCustomSetting = allLinksMap.get(labelLink);
                mapLabelLink.put(myCustomSetting.Home_page_Header_Section__c+'_'+myCustomSetting.Label_for_Custom_Link__c,myCustomSetting.Links_for_Home_Page__c);
            }
            system.debug('ALL LABEL LINK VALUES***'+mapLabelLink);
        }
        return mapLabelLink;
    }
    
}
 
MY TEST CLASS

@isTest
public class BAU_CustomLinkForLightningTest {
    @testsetup
    static void createData(){
        List<QantasConfigData__c> lstConfigData = new List<QantasConfigData__c>();
        lstConfigData.add(TestUtilityDataClassQantas.createQantasConfigData('Log Exception Logs Rec Type','Exception Logs'));
        insert lstConfigData;

        TestUtilityDataClassQantas.createQantasConfigDataAccRecType();
    }
     public static testmethod void getCustomLinkstest() {
        system.debug('*****insidemethod*******');
        //TestUtilityDataClassQantas.enableTriggers();
        BAU_CustomLinkForLightning bau = new BAU_CustomLinkForLightning();
        BAU_CustomLinkForLightning.getCustomLinks();
        List<Custom_Links_For_Lightning__c> custlinklightning= new List<Custom_Links_For_Lightning__c>();
        custlinklightning.add(new Custom_Links_For_Lightning__c(Name='A380 Cabin Update Fact sheet',Home_page_Header_Section__c='Essential Reading',Label_for_Custom_Link__c='A380 CA380 Cabin Update Fact sheet',Links_for_Home_Page__c='https://www.qantasnewsroom.com.au/wp-content/uploads/2017/08/A380-Cabin-Update-Fact-Sheet.pdf'));
        system.debug('*****custlinklightning******'+custlinklightning);
        insert custlinklightning;
     }          
 }

Pls help me , thanks
 
Hi all,

I want to retrieve the contacts related notes using rest api. I was new to api calls.
Can anyone help me over here.

Thanks in advance.

Regards,
naga.
Hi everyone,

I'm trying to create my first mail Template visualforce page , and in this page i have to put a related list associated on the Objects "contracts" , the relate list is called "Machines under Warranty" (ass you can see in pic):
User-added image

The primary objective is to create an email template wich contain the Machine in Warranty according to the actual contract of the client.

Here is my visualforce templace (sorry if its really bad because i don't have the time to train on this and i have an urgent asking from my Customer service):

<messaging:emailTemplate subject="PellencST Warranty test" recipientType="Contact" relatedToType="Contract">
<messaging:htmlEmailBody > 
<html>
 
        <body>
 
        <STYLE type="text/css">
 
            TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center }
 
            TD  {font-size: 11px; font-face: verdana }
 
            TABLE {border: solid #CCCCCC; border-width: 1}
 
            TR {border: solid #CCCCCC; border-width: 1}
 
         </STYLE>
      <font face="arial" size="2">
     
<p>Bonjour,</p>
<p>Nous vous informons que la garantie de vos trieurs optique PellencST arrive à échéance.</p>
 
<p>En effet votre contrat de garantie a débuté le {!relatedTo.StartDate} et se termine le {!relatedTo.EndDate} pour les machines suivantes:</p>
 
 
 
<p>Vous trouverez ci-dessous un tableau récapitulatif des différentes options de contrats de services auxquelles vous pouvez souscrire afin de garder un service adapté pour un fonctionnement optimum de vos équipements:</p>
 
<table border="0" >
    <tr >
        <th>Machine Name</th>
    </tr>
    <apex:repeat var="cx" value="{!relatedTo.Machine__c}">
        <tr>
            <td>{!cx.Machine_Name__c}</td>
        </tr>
    </apex:repeat>                
</table>
<p />
 
<p>Désormais votre dossier est suivi par notre Service Client ainsi pour tous conseils dans ces démarches vous pouvez contacter notre service au 04.90.09.47.94 ou par mail au sav@pellenct.com.</p>
 
 
<p>Le service client PellencST</p>
 
<p>sav@pellencst.com</p>
<p>+334 90 09 47 94</p>
<p>PELLENC ST</p>
 
<p>Pellenc ST | 125, rue François Gernelle | 84120 Pertuis | France | pellencst.com | +33 4 90 09 47 94</p>
 
 
<p>This email transmission is confidential and intended solely for the person or organization to who it is addressed. If you are not the intended recipient, you must not take any action in reliance of it.</p>
<p>Ce message et les pièces jointes sont confidentiels et établis à l’intention exclusive de ses destinataires. Toute utilisation de ce message non conforme à sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse.</p>
            </font>
        </body>
    </html>
</messaging:htmlEmailBody > 
 
</messaging:emailTemplate>

The thing is i got a problem with this part i think:

<table border="0" >
    <tr >
        <th>Machine Name</th>
    </tr>
    <apex:repeat var="cx" value="{!relatedTo.Machine__c}">
        <tr>
            <td>{!cx.Machine_Name__c}</td>
        </tr>
    </apex:repeat>                
</table>
<p />

Salesforce keep repeating me "Error: Unknown property 'String.Machine_Name__c'

Can someone help me with this, or maybe with the full template as i think, i have made many mistake.

Thanks !!
1) Make two DateTime fields on contact object.

LastTaskCreatedTime

LastEmailSentTime


2) Whenever a task is created on Contact LastTaskCreatedTime field should be updated.


3) Whenever you send an email LastEmailSentTime field should be updated.

4) Make trigger as bulk
I am trying to check to see if a field has only numbers in it. It can also be left blank. The regex formula that I have written accepts both letters and numbers and I cannot figure out what I am doing wrong. I am new to regex so please be kind.

The validation rule is:
AND( 
ISBLANK(Checking_Account_Number__c), 
NOT (REGEX(Checking_Account_Number__c, "(//[0-9]+)")) 
)

Thanks for any help.
On my visualforce page I have this.
<apex:inputTextarea value="{!emp.Job_description__c}" styleClass="form-control"/>

In my controller I have this
if (String.isBlank(emp.Job_description__c)) {
                    emp.Job_description__c.addError(System.Label.ValidationEmploymentDescription);
                    doNotsubmit = true;
                }
This works for other fields on my visualforce page except for this one. 
I have a pageMessage on my page and it has the error message above in a box but not under the field.
The message should be displayed under the field and also above in the pageMessage.
  • November 16, 2017
  • Like
  • 0
Hello all,

I am having some trouble with an Apex Trigger test class I'm writing. I am using a developer sandbox and am getting the following error:
System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: a0D6A0000015UKi: []

What I am trying to do is update a Lookup field that looks up to a Rate Sheet based on certain criteria. (Rate_Sheet__c = API Name)

I wrote the trigger and had no errors that I could see but when writing the test class it kept giving me the Insufficient Access error. Not really sure what the problem is. Under sharing settings, my org wide defaults gives public read/write access to all objects needed.

Please see the following Apex Trigger and Test Class code:
trigger UpdateRatesheetLookup on Quote (before insert, before update) {

    for (Quote quo : Trigger.new) {
       
        if (quo.TotalPrice < 3000 && quo.Buyout_Type__c == 'FMV') {
            // Sets Rate Sheet Lookup
            quo.Rate_Sheet__c = 'a0D6A0000015UKi';
            
        } else if (quo.TotalPrice < 10000 && quo.Buyout_Type__c == 'FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKj';
            
        } else if (quo.TotalPrice >= 10000 && quo.Buyout_Type__c == 'FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKk';
            
        } else if (quo.TotalPrice < 3000 && quo.Buyout_Type__c == 'Promo FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKl';
            
        } else if (quo.TotalPrice < 10000 && quo.Buyout_Type__c == 'Promo FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKm';
            
        } else if (quo.TotalPrice >= 10000 && quo.Buyout_Type__c == 'Promo FMV') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKn';
            
        } else if (quo.TotalPrice < 3000 && quo.Buyout_Type__c == '$1-out') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKo';
            
        } else if (quo.TotalPrice < 10000 && quo.Buyout_Type__c == '$1-out') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKp';
            
        } else if (quo.TotalPrice >= 10000 && quo.Buyout_Type__c == '$1-out') {
            quo.Rate_Sheet__c = 'a0D6A0000015UKq';
            
        } else {
            quo.Rate_Sheet__c = Null;
        }
    }
}

// Problem is happening at insertion of the myQuote instance.
@isTest
private class UpdateRateSheetLookupTest {
    
    @isTest static void updateQuote() {
        
        // Create an Account & Set Required Fields
        Account myAccount = new Account();
        myAccount.Name    = 'Sample Account';
        insert myAccount;
        
        // Create an Opportunity on the Account & Set Required Fields
        Opportunity myOpportunity = new Opportunity();
        myOpportunity.Name        = 'Sample Opportunity';
        myOpportunity.CloseDate   = Date.today();
        myOpportunity.StageName   = 'Proposal';
        myOpportunity.AccountId   = myAccount.Id; // Relates to id of account above.
        insert myOpportunity;
            
        // Fire the UpdateRatesheetLookup Trigger
        // Create a Quote associated with Opportunity & Set Required Fields
        Quote myQuote          = new Quote();
        myQuote.Name           = 'Sample';
        myQuote.OpportunityId  = myOpportunity.Id; // Relates to id of opportunity above.
        //myQuote.TotalPrice   = 2500;
        myQuote.Buyout_Type__c = 'FMV';
       	insert myQuote; // FLAG: PROBLEM HERE
        
        // Update the Quote
        myQuote.Description = 'Test';
       	update myQuote;
    }
}

Any help with this would be greatly appreciated. 
Thanks in advance!
 
Running into the following error via the Debug Console when running a flow:
System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

The flow essentially takes a unique identifier on a custom object and attempts to find a lead or contact with that same unique ID. Worked fine in a sandbox, but when pushing into our full copy it no longer works if it has to look for a lead. My guess is it's because there are so many leads. Any thoughts on how to get around this limit via flow? Not a developer by trade. Current flow below, its called via process builder when the custom object is inserted.

User-added image

Hello, 

We have 200 email alerts, some are immediate and some are time dependent. We have 20 locations that require about 30-40 of those email alerts to trigger at different time intervals or have different email templates. Therefoer only about 160 alerts are consistent across the 20 locations. We need to design a way to build these email alerts in a way that is scalable. We add locations each month and need to find a way to implement the consistent alerts and be able to create the ones that differ. 

We had them setup as workflows but we reached the limit quite fast. We then started using process builder but the system is super slow and it was really hard to recreate 200 workflows and then trouble shoot them,. Each time something conflicted it stopped our entire system. 

Any ideas on how to build a system that is scalable? Do we need to go the apex code route? 
 

Thanks, 
 

I am getting the following error in step 7. 
User-added image

Here is the corresponding code:
    <aura:attribute name="boat" type="Boat__c" />
    <aura:attribute name="boatReview" type="BoatReview__c" access="private"/>
    <aura:attribute name="boatReviewRecord" type="BoatReview__c" />
    <aura:attribute name="recordError" type="String" access="private"/>

<force:recordData aura:id="service"
                      fields="Id,Name,Comment__c,Boat__c"
                      targetRecord="{!v.boatReviewRecord}"
                      targetFields="{!v.boatReview}"
                      targetError="{!v.recordError}"
                      recordUpdated="{!c.onRecordUpdated}"
                      />
        
    <div class="slds-p-around_x-small">        
        <div class="slds-form slds-form_stacked">
            <div class="slds-form-element">
                <lightning:input label="Title" name="reviewTitle" value="{!v.boatReview.Name}" />
            </div>
            <div class="slds-form-element">
                <label class="slds-form-element__label" for="input-id-02">Description</label>
                <lightning:inputRichText title="Description" value="{!v.boatReview.Comment__c}" disabledCategories="FORMAT_FONT"/>
            </div>
            <div class="slds-form-element">
                <div class="slds-align_absolute-center">
                    <lightning:button label="Submit" onclick='{!c.onSave}' iconName="utility:save"/>
                </div>
            </div>
        </div>    
    </div>
Can someone point me what I am doing wrong here? 

Regards,
Subbu

 
I'm getting errors with the component not being able to see the controller action.

error:

Uncaught Unknown controller action 'getLogEntry'
Callback failed: serviceComponent://ui.flexipage.components.page.FlexipageControllerV2/ACTION$getPage


Compnent code
<aura:component controller="CaseLogController" 
                implements="force:appHostable,flexipage:availableForAllPageTypes"
                access="global">

    <!--Include the css from static resource-->
    <ltng:require styles="{!$Resource.SLDS +
             '/assets/styles/salesforce-lightning-design-system-ltng.css'}"  afterScriptsLoaded="{!c.doScriptLoad}"/>

    <aura:attribute name="start" type="String"/>
    <aura:attribute name="stop" type="String"/>
    <aura:attribute name="sObj" type="String"/>
    <aura:attribute name="field" type="String"/>
    <aura:attribute name="stopwatch" type="Object"/>
    <aura:attribute name="LogEntry" type="Case_Log__c[]"/>
    
    <!-- Handle component initialization in a client-side controller -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <div class="slds-clearfix slds-card">
		<div class="slds-text-heading_medium slds-align_absolute-center">
            <div aura:id="time">
                Time: 00:00:00
            </div>
        </div>
        <div class="slds-button-group slds-align_absolute-center" role="group">
                <button id="start" class="slds-button slds-button_success" onclick="{!c.onClick}">Start</button>
                <button id="stop" class="slds-button slds-button_brand" onclick="{!c.onClick}">Pause</button>
                <button id="reset" class="slds-button slds-button_destructive" onclick="{!c.onClick}">Finish</button>
        </div>
        
           <ul>
      <aura:iteration items="{!v.LogEntry}" var="log">
         <li type="dice">Entry Name : {!log.Name}</li>
         <hr/>
      </aura:iteration>
   </ul>
    </div>
</aura:component>

controller code
({
     doInit: function(component, event, helper) {
     //call apex class method
      var action = component.get("c.getLogEntry");
      action.setCallback(this, function(response) {
       //store state of response
       var state = response.getState();
       if (state === "SUCCESS") {
        //set response value in LogEntry attribute on component.
        component.set('v.LogEntry', response.getReturnValue());
       }
      });
      $A.enqueueAction(action);
     },
    doScriptLoad : function(component, event, helper) {

	},

    onClick : function(component, event, helper) {
        var div = component.find("time").getElement();
        var id = event.target.id;
        var	clsStopwatch = function() {
            // Private vars
            var	startAt	= startAt || 0;	// Time of last start / resume. (0 if not running)
            var	lapTime	= lapTime || 0;	// Time on the clock when last stopped in milliseconds

            var	now	= function() {
                return (new Date()).getTime();
            };

            // Public methods
            // Start or resume
            this.start = function() {
                
    
                startAt	= startAt ? startAt : now();
            };

            // Stop or pause
            this.stop = function() {
                // If running, update elapsed time otherwise keep it
                lapTime	= startAt ? lapTime + now() - startAt : lapTime;
                startAt	= 0; // Paused
            };

            // Reset
            this.reset = function() {
                lapTime = startAt = 0;
            };

            // Duration
            this.time = function() {
                return lapTime + (startAt ? now() - startAt : 0);
            };
        };

        var stopwatch = component.get("v.stopwatch");
        var x = stopwatch || new clsStopwatch();
        if(!stopwatch){
        	component.set("v.stopwatch", x);
        }

        function pad(num, size) {
            var s = "0000" + num;
            return s.substr(s.length - size);
        }

        function formatTime(time) {
            var h = 0;
            var m = 0;
            var s = 0;
            var newTime = '';

            h = Math.floor( time / (60 * 60 * 1000) );
            time = time % (60 * 60 * 1000);
            m = Math.floor( time / (60 * 1000) );
            time = time % (60 * 1000);
            s = Math.floor( time / 1000 );

            newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2); 
            return newTime;
        }

        function update() {
            div.innerHTML = "Time: " + formatTime(x.time());
        }

   		switch(id){
            case "start":
                
                setInterval(update, 1000);
                x.start();
                break;
            case "stop":
                x.stop();
                update();
                break;
            case "reset":
                x.stop();
                x.reset();
                update();
                break;
            default:
                stop();
                break;
        }
        

	}
})

Apex class code
 
public with sharing class CaseLogController {

    public static List<Case_log__c> getLogEntry() {
        list<Case_Log__c> l = [SELECT Id, Case__c, Name, In_Progress__c, Length__c, Time__c 
                             		FROM Case_Log__c WHERE In_Progress__c = true LIMIT 1];
        
        if (l.size() == 0) {
            Case_log__c newlog = new Case_log__c();
            l.add(newlog);
            insert l;
        }
        return l;
    }
    
}

 
Midway through this module the following Client Controller code is introduced.  Is the Reduce function documented anywhere else so I can understand it better.  The Trailhead explanation doesn't work for me, very stuck

({
    clickCreate: function(component, event, helper) {
        var validExpense = component.find('expenseform').reduce(function (validSoFar, inputCmp) {
            // Displays error messages for invalid fields
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);
        // If we pass error checking, do some real work
        if(validExpense){
            // Create the new expense
            var newExpense = component.get("v.newExpense");
            console.log("Create expense: " + JSON.stringify(newExpense));
            helper.createExpense(component, newExpense);
        }
    }
})


 
I am new to Apex Programming and I am trying to get through this error message. 
Below is the code that I am working on
trigger DeDupe on Lead (before insert) {
         for(Lead myLead : Trigger.new)
         {
             //Searching for matching contacts.Assigning them to the list by using bind variable. By using : with Apex Variable myLead
             List<contact> matchingContacts = [SELECT Id FROM Contact
                                              WHERE Email = :myLead.Email];
              System.debug(matchingContacts.size() + 'contact(s) found.'); 
              if(!matchingContact.isEmpty())    
              {
                  //Assign the lead to the data quslity queue
                  Group dataQualityGroup = [SELECT ID FROM Group
                                            WHERE DeveloperName ='Data_Quality'
                                            LIMIT 1];
                  myLead.OwnerID = dataQualityGroup.Id;
                 
                  //Add the dupe contact IDS into the Lead description
                  String ContactMessage = 'Duplicate Contacts Found:\n';
                  for(Contact c = matchingContacts)
                  {
                        ContactMessage += c.FirstName + ' '
                                          + c.LastName + ' '
                                          + c.Account.Name + '('       
                                          + c.Id + ;
                  }
                  myLead.Description = ContactMessage +'\n' + myLead.Description;
                }
             }
}

And I am getting following error messsage:
Error: Compile Error: Invalid identifier '        '. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. 
Please find my trigger and test class in code sample and suggest me how to improve code coverage for helper class.
Apex Trigger :

 trigger OpportunityLineItemCheck on OpportunityLineItem (before insert) 
  {
    opportunityLineItemCheckOperations.checkOnOpportunityLineItems(trigger.new);
  }

Helper class :

public class OpportunityLineItemCheckOperations {

    public static void checkOnOpportunityLineItems(List<OpportunityLineItem> opportunityProductList){
        
        List<OppWrapper> lstOpps = new List<OppWrapper>();
        Set<String> oppIds = new Set<String>();
        Set<String> productcodeids = new Set<String>();
        
        for (OpportunityLineItem oppline : opportunityProductList){
             productcodeids.add(oppline.productcode);
             oppIds.add(oppline.OpportunityId);
        }
        
        List<Opportunity> lstOppos = [SELECT Id, (SELECT Id, opportunityid, productcode , Product2Id FROM OpportunityLineItems WHERE productcode in :productcodeids)
                                            FROM Opportunity WHERE Id in :oppIds ];
        
        
        for (Opportunity oppor : lstOppos){
        
            for (OpportunityLineItem oppline : oppor.OpportunityLineItems){
                OppWrapper oppo = new OppWrapper();         
                oppo.OppID = oppor.Id;
                oppo.productcode = oppline.productcode;
                //oppo.ProductID = oppline.Product2Id;
                lstOpps.add(oppo);
            }
        }
        
        lstOpps.sort();
        
        for (OpportunityLineItem oppline: opportunityProductList){
            
            for(OppWrapper oppwrap :lstOpps){
                if (oppline.OpportunityId == oppwrap.OppID && oppline.productcode == oppwrap.productcode)
                    oppline.addError('This product is already added to this opportunity.You cannot add the same product again.');
                /*else if (oppline.OpportunityId == oppwrap.OppID && oppline.Product2Id > oppwrap.ProductID)
                    break;
                else if (oppline.OpportunityId > oppwrap.OppID)
                    break;*/
            }
            
        }
        
        
    }
    
    public class OppWrapper implements Comparable{
        String OppID;
        String ProductID;
        String productcode;
        
        public Integer compareTo(Object compareTo){
            OppWrapper compareToCopy = (OppWrapper) compareTo;
            
            Integer returnValue = 0;
            
            if (this.OppID > compareToCopy.OppID)
                returnValue = 1;
                
            else if (this.OppID < compareToCopy.OppID)
                returnValue = -1;
                
            else if (this.OppID == compareToCopy.OppID){
                if (this.ProductID > compareToCopy.ProductID)
                    returnValue = 1;
                    
                else if (this.ProductID < compareToCopy.ProductID)
                    returnValue = -1;
            }
            
            return returnValue;     
        
        }
    
    }

}