• Bhaswanthnaga vivek vutukuri
  • NEWBIE
  • 327 Points
  • Member since 2014

  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 178
    Replies
Hi,

We recently made the change to work from contacts instead of leads in Salesforce. We get all our contacts from our marketing generation tool without an Account. The company name of these contacts is stored in a field called "Company__c". I wrote a code that looks if the contact is from our existing customer (Zlien_User_ID__c) and associates with the same Salesforce Account(User_ID__c), if not it will look for the matching Account name and associates with it, and if not finally it will create an account and associate with it. The following code works fine when one contact is created by the lead gen tool at a time. Sometimes, we may have to bulk upload contacts using dataloader which is when I encounter the error message: System.LimitException: Too many query rows: 50001. 

Please find the Code below:

public class assignAccount
{
    public static void assignAccounts(Set<Id> contactIds) 
    {

        Map<String,Account> matchUserIdMap = new Map<String,Account>();
        Map<String,Account> matchCompanyMap = new Map<String,Account>();
        
        for(Account acc : [Select User_ID__c, name, Id from Account])
        {
            if(acc.User_ID__c != null)
            {
                // Contact map when Zlien user id is not null.
                matchUserIdMap.put(acc.User_ID__c, acc);
            }
            else
            {
                // Contact map when Zlien user id is null.
                matchCompanyMap.put(acc.name, acc);
            }
            
        }
       
        for(Contact con : [Select Zlien_User_ID__c, Company__c, accountId, ownerId from Contact where Id IN :contactIds])
        {
            if(con.Zlien_User_ID__c != null)
            {
                if(matchUserIdMap.containsKey(con.Zlien_User_ID__c))
                {
                   con.accountId = matchUserIdMap.get(con.Zlien_User_ID__c).Id;
                }
                
                else if(matchCompanyMap.containsKey(con.Company__c))
                {
                    con.accountId = matchCompanyMap.get(con.Company__c).Id;
                }
                
                else
                {
                    Account A = new Account(name = con.Company__c, ownerId = con.ownerId);
                    insert A;
                    con.accountId = A.Id;
                }
            }
            else if(con.Company__c != null)
            {
                if(matchCompanyMap.containsKey(con.Company__c))
                {
                    con.accountId = matchCompanyMap.get(con.Company__c).Id;
                }
                
                else
                {
                    Account A = new Account(name = con.Company__c, ownerId = con.ownerId);
                    insert A;
                    con.accountId = A.Id;
                }
            }
            
            update con;          
        }
         
    }
    
}

Thanks in Advance,
Teja
Hi,
I need your help.
On Opportunity page, there is a "Contact" lookup field.
Based on Contact person, we want a Text "A" field to be populated.

Text "A" field is displayed as a Text field on the opportunity and "PickList" on the Contact Page.

Since there is a relationship between Contact and Opportunity record on "A" field, I would like to have this field duplicated.

How do you do this?

 
  • August 28, 2016
  • Like
  • 0
global class EvergreenOppoRevenueScheduleBatch implements Database.Batchable<sObject> {
String query;
id firstId = null;    
global Database.QueryLocator start(Database.BatchableContext BC) {
    /*This SOQL gets all the records (Evergreen Opportunities) on the sObject (OpportunityLineItemSchedule)
    WHERE OpportunityLineItem.Opportunity.StageName = 'Contract Executed' 
    and OpportunityLineItem.Opportunity.TFBA__c =  True 
    and OpportunityLineItem.Opportunity.Contract_Status__c <> 'Cancelled' 
    and OpportunityLineItem.Opportunity.Contract_Status__c <> 'Renewed'  
    and OpportunityLineItem.Cancellation_Date__c = null  
    and  OpportunityLineItem.HasRevenueSchedule = True 
    and  OpportunityLineItem.PricebookEntry.Product2.Media__r.Automatic_Revenue_Schedule__c  = True 
    This query can get up to 50,000,000 records 
     */
     
return Database.getQueryLocator([SELECT OpportunityLineItemId, ScheduleDate, OpportunityLineItem.Number_of_Billings__c, OpportunityLineItem.Discounted_Rate__c  From OpportunityLineItemSchedule Where OpportunityLineItem.Opportunity.StageName = 'Contract Executed' and OpportunityLineItem.Opportunity.TFBA__c =  True and OpportunityLineItem.Opportunity.Contract_Status__c <> 'Cancelled' and OpportunityLineItem.Opportunity.Contract_Status__c <> 'Renewed'  and OpportunityLineItem.Cancellation_Date__c = null  and  OpportunityLineItem.HasRevenueSchedule = True and  OpportunityLineItem.PricebookEntry.Product2.Media__r.Automatic_Revenue_Schedule__c  = True Order By OpportunityLineItemId DESC]);
}
 
List<OpportunityLineItemSchedule> addrecs = new List<OpportunityLineItemSchedule>();   
    
/*This is the Loop for the Query scope*/    
global void execute(Database.BatchableContext BC, List<OpportunityLineItemSchedule> scope) {

/*Creating a unique ID Set of the all Opportunities*/
Set<ID> oppProductId = new Set<ID>();
  For (OpportunityLineItemSchedule recuni : scope)  {
     oppProductId.add(recuni.OpportunityLineItemId );   
 }

/*Creating a list of all Max Date for each opportunity line item Ids product from the OpportunityLineItemSchedule sObject using the unique list */    
AggregateResult[] groupedResults = [SELECT Max(ScheduleDate) MaxDate, OpportunityLineItemId oppid FROM OpportunityLineItemSchedule Where OpportunityLineItemId in :oppProductId Group By OpportunityLineItemId Order By OpportunityLineItemId];

   
/*Looping through all the unique Ids to get the Discounted Rate and Number of  Billings */
For (OpportunityLineItem opprec : [Select id , Discounted_Rate__c, Number_of_Billings__c From OpportunityLineItem where id in :oppProductId Order By Id]) {   
       Date maxDatevar;
       String stridLineItem;
       Id idLineItem;
   
 /*For each record now go throught the following loop find the Max Date. When the Max Date is found get out to the loop */
       For (AggregateResult ar :groupedResults) {
           
            stridLineItem = String.ValueOf(ar.get('oppid'));
            idLineItem = Id.ValueOf(stridLineItem);
            If (opprec.Id ==  idLineItem) {
            maxDatevar = Date.valueOf(ar.get('MaxDate'));
                      
            if (date.today() >=  MaxDatevar){
                Integer Days = 0;
                Date oldServiDate = MaxDatevar;
                Days =  Date.daysInMonth(oldServiDate.year(), oldServiDate.month());
                oldServiDate = oldServiDate + Days;

                for (Integer countBillings = 1 ; countBillings <= opprec.Number_of_Billings__c; countBillings++  ){
                OpportunityLineItemSchedule oppS = new OpportunityLineItemSchedule();
                oppS.OpportunityLineItemId = idLineItem;
                oppS.Type = 'Revenue';
                oppS.ScheduleDate = oldServiDate;
                oppS.Revenue = opprec.Discounted_Rate__c;
                Days =  Date.daysInMonth(oldServiDate.year(), oldServiDate.month());
                oldServiDate = oldServiDate + Days;
                addrecs.add(oppS);
                }  
            }
          break; /*Exit the loop after the record is found.*/
              
          }
           
        }
}
 

  Insert addrecs; /*Insert all the records on the OpportunityLineItemSchedule*/

}
    

global void finish(Database.BatchableContext BC) {
}
}
I think problem is my nested loop, base on the info that I found online. Any ideas how to fix this issue?
Thanks.
Hi, Apex noob here. I'm trying to create a trigger that calls the method logTransaction in my "Blockchain" class. It's failing with the message "Error: Compile Error: Method does not exist or incorrect signature: Blockchain.logTransaction(String, String, String, String) at line 3 column 21
 
trigger OpportunityInsertTrigger on Opportunity (before insert) {
    System.debug('Triggered on insert of opportunity. Updating blockchain...');
    String result = Blockchain.logTransaction('123456789', 'DNB', 'Salesforce', 'Opportunity');
}

The method signatures do seem to match. I've tried implementing this as both an instance method and static method and I get the same message when I try to invoke either.

My class:
public class Blockchain {

    public static String logTransaction(String duns, String fromEntity, String toEntity, String state) {
		Map<String,String> arguments = new Map<String,String>();
	    arguments.put('from', fromEntity);
        arguments.put('to', toEntity);
        arguments.put('duns', duns);
        arguments.put('state', state);
        return makeRequest(arguments);
    }
    
    public static String makeRequest(Map<String,String> arguments) {
        Payload payload = new Payload();
		payload.argumentMap = arguments;        
				        
        String url = '';
        Httprequest request = new HttpRequest();
        request.setMethod('POST');
        request.setEndpoint(url);
        request.setBody(payload.toJSONString());
 
        Http http = new Http();
        HttpResponse response = http.send(request);
        
        System.debug('Response status code: ' + response.getStatusCode());
        System.debug('Response: ' + response.getBody());        
        
        return 'OK';
    }

}

 
I'm trying to get the values of certain attributes from a list into a map. The first bit of code below is not my actual code, I'm just trying to explain what I'm trying to do so I can find out if it's actually possible in APEX.

Assuming the list has more than one field in it (in my example below there are four: ID, Name, MyValue, and OwnerId ), is there a way to reference the ID and MyValue fields so I can insert them into a map rather than inserting the whole sObject? In the real code, my list is passed in from another class and I'd like to put it into a map with just the ID and one field.
List<MyObject__c> l = [SELECT ID, Name, MyValue, OwnerId FROM MyObject__c]; 

// I can do this...
Map<ID, MyObject__c> m = New Map<ID, MyObject__c>(l);  

// What I want to do is this...
Map<ID, String> m = New Map<ID, String>(l.ID, l.MyValue); 

As I know someone will ask for it, here's the actual code I'm trying to replace:
Map<ID, String> BenStatusMap = new Map<ID, String>();
        for(Commitment__c CurrRec: lstNewRecords) {
            BenStatusMap.put(CurrRec.Fund_Id__c, CurrRec.Status__c);
        }

First it creates the map, then it iterates through the list to populate the map. This seems very wasteful to me, and I can't help but think there must be a way to do this with less code. That's my goal, to do the same thing with less code.

Can anyone help me?
Hi all,

I need to change the rendering of a page so that only a system administrator or the person who created the entry can access the entry. I am thinking that I should be able to insert something like:

    <apex:PageBlock rendered="{!$User.id==!icustom_object__c.CreatedByID}" >            

However this seems not to work because: Error: Incorrect parameter type for function 'not()'. Expected Boolean, received Text

Which I do not fully understand, Can someone please let me know?






 
Hi ,

I have written a javascript button to create a record on salesforce .when the user clicks once on the button the record is created .but he clicks again on the button another record is created.

I just dont want the user to click the button again and create a duplicate record.Is there any other way to disable the button after the user clicks once or else if the record is already created .he needs to be prompted  that  the record is already exixts.
 
{!requireScript("/soap/ajax/26.0/connection.js")} 

var req = new sforce.SObject("Candidate__c"); 
req.Id = "{!Candidate__c.Id}"; 
req.Job_Application__c="True"; 
req.Recruiting_Status__c="Possible Candidate" 
var aResult = sforce.connection.update([req]); 
if (aResult[0].getBoolean("success")) { 
console.log("Candidate Update Successful"); 
} 
var newJob = new sforce.SObject("Job_Application__c"); 
newJob.Candidate__c= "{!Candidate__c.Id}"; 
newJob.Position__c= "{!Candidate__c.PositionId__c}"; 
newJob.Status__c="open"; 

var cResult = sforce.connection.create([newJob]); 
if ( cResult[0].getBoolean( "success" ) ) 
{ 
alert("Candidate Created Sucessfully "); 
window.location.reload(); 
} 

else 
{ 
alert( cResult[0].errors.message); 
}

 
Hi

When I run a query on attachments to pull their parent id, it works fine for eg Accounts:

Select id, parent.id from Attachment
where parent.type = 'Account'

However for Tasks I get only a 'null parent' return:

select id, parent.id from attachment
where parent.type = 'Task'

Does anyone have the answer to this or a workaround?

Cheers, 

Andy
Everyone, I have the most basic trigger and am getting a silly testing error that I can't shake.  Ironically, when I manually fire this trigger, it works perfectly.  But when I test it, I receive this error: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, SetAccountField: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0  Trigger.SetAccountField: line 6, column 1: []"  

This trigger simply looks at a "location_ID" field on my Monthly Outreach object, which coorelates to a "location_ID" field on my Account object, then associates the Account ID to my Monthly Outreach record.  I continue to get the dreaded List Out of Bounds error.  After much research, it appears that I'm supposed to be checking to see if my account variable is null.  I thought I was doing that by adding:"if(account != null)".  Can anyone tell me what I'm doing wrong?

My trigger:
trigger SetAccountField on Monthly_Outreaches__c (before insert, before update) {
    for (Monthly_Outreaches__c mo : Trigger.new) {
        String accid = mo.Location_ID__c;
        List<Account> account = [SELECT Id FROM Account WHERE Location_ID__c = :accid];
        if(account != null){
            account[0].Id = mo.Account__c;} else {
            }
    }
}

Here is my test class.  Again, very basic:
 
@isTest 
private class AddMonthlyOutreachesTestClass {
    static testMethod void validateMonthlyOutreaches() {
        Monthly_Outreaches__c m = new Monthly_Outreaches__c(
            LOCATION_ID__C='001', 
            Submitter_Email__c='rick.allen@xxx.com',
            MEDIA_INTERVIEWS_ARTICLES__C=100         
        );
        // Insert Monthly Outreaches
        insert m;
        
        ApexPages.StandardController sc = new ApexPages.standardController(m);
        MonthlyOutreachesRedirect e = new MonthlyOutreachesRedirect(sc);
        String nextPage = e.saveAndCongrat().getURL();
        
        // Verify that the Congratulations page displays
        System.assertEquals('/apex/congratulations', nextPage);
    }
}
Hello team, 

How can I convert all my leads to contacts without creating new opportunity?
Can somebody give me some example?

Thanks in advance. 
Hi, I was trying to get fiscal Period values in wave (Fiscal Year, Fiscal Week, Fiscal Month), I have followed every thing mentioned in documentation but didn't work, anyone please help me to sort out this. https://resources.docs.salesforce.com/204/latest/en-us/sfdc/pdf/bi_admin_guide_data_integration_guide.pdf
Hi, I would want to do call outs to more than 3 endpoints, I want to display data on visualforce page with less loading time, I would to want to use 2 different continutaions so that I can display 1st continuations response before I run 2nd continuation that gives good experience for end users.

Hi, I am building a force.com and I currently loading content from richtext area to VF page but I didn't find option to edit the font size in rih text area.

My client want to customize the font size of the content of the website, whats is alternative please suggest me.

Hi,

I am trying write test class for a wrapper class, but my concern is I couldn't  cover one line. I am posting wrapper class and test class please help me its very urgent :( .........

 

Class :-

public class wrapperClassController {


   
    public List<cContact> contactList {get; set;}

   
    public List<cContact> getContacts() {
        if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c: [select Id, Name, Email, Phone from Contact limit 10]) {
              
                contactList.add(new cContact(c));
            }
        }
        return contactList;
    }


    public PageReference processSelected() {

               
        List<Contact> selectedContacts = new List<Contact>();

      
        for(cContact cCon: getContacts()) {
            if(cCon.selected == true) {
//********************------------------------- The following is not covered  plese find attachment-------------------------------****************************************
                selectedContacts.add(cCon.con);

            }
        }
      System.debug('These are the selected Contacts...');
        for(Contact con: selectedContacts) {
            system.debug(con);
        }
        contactList=null;
        return null;
    }
    public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
        public cContact(Contact c) {
            con = c;
            selected = false;
        }
    }
}

Test class :-
@isTest(seeAllData=true)
private class wrapperClassController_Test
{
  private static testmethod void addUser_Test()
  {
     Contact c =new Contact();
     c.LastName='RRRR';
    
     insert c;
    
      ApexPages.StandardController sc =new ApexPages.StandardController(c);  
      wrapperClassController ad=new wrapperClassController();
      wrapperClassController.cContact cw=new wrapperClassController.cContact(c);
      ad.getContacts();
      ad.processSelected();

 
  }
}

The following line  is uncovered in the class
User-added image
Hi,

can any one help us....

we need to print multiple duplicate account names(with hyperlinks), but it displaying error for only one account


trigger DuplicateAccountNameCountryCheck1 on Account (before insert, before update)
{
    For(Account a:Trigger.New)
    {
        List<Account> acc=[SELECT Id, Name FROM Account WHERE BillingCountry=:a.BillingCountry];
      
        if(acc.size()>0)
        {
        for(Account at:acc){
      
          
           a.addError(' <font color="blue"> im an html error with a  </br></br>this is</br> </br> false</font><a href="/'+at.id+'">'+at.Name+'</a>', FALSE);
          
        } }
    }
}
Hi,
I need to disable the developement mode for the particular VisualForce page, is it possible lo disable only for particular page ???

Hello, 

Can anyone please help me in validating URL format ?

I used the following Regular expression but it is working good, its showing even valid URL's as Invalid 

^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$ 

HI, We'r integrating our APP with PHP web app using Rest and SOAP API services...

In build Org every thing is working good,  but in enterprise org it is showing error like 'Invalid sessionID and session key missing' when  we try to access the functionalities used SOAP services. we took WSDL for SOAP services class from build org, but connected APPs present in MY  Enterpise org .. is it a prblm ???

note: When we tried to connect with demo PHP webapp with Enterprise ediction is is working, not working when tried to connect with live webapp

Hi Team,

1. What does the salesforce.com sharing model determines? (select all that apply)
 a) who has access to records
 b) which tabs that can access records through
 c) what level of access to records
 d) why they have access to records

2) A log of the last 20 changes will be kept when a custom objects 'Track field history' checkbox is checked?
 a) True
 b) False

3) You want to configure your app to handle your company's warranty policy. which kind of custom metadata type most closely fits this scenario?
 a) Business ruels
 b) Master data
 c) Mapping
 d) This solution is not a good application for custom metadata types

4) Which statements are true about modifiable system fields? (Select all tthat apply)
 a ) works for all custom objects
 b) only available for users with the standard system admin profile
 c) only accessble through api
 d) modifiable systemfields setting can be turned on and off by administrator
 e) read-only for existing records.

5) Field types for history tracking? (select all that apply)
 a) text (encrypted)
 b) lookup relation ship
 c) text area (long)
 d) text area (rich)
 e) picklist (multi select)

Please give me the answers for above questions?

Regards
Lakshmi

 
my vf page is very slow , what could be the reason, is it due to view state? , please suggest me 
thanks
ab
  • November 21, 2017
  • Like
  • 0
Hello All,
I have the following code that only allows a single Primary Contact per Account.  But what I would like to do is set the newly created Contact as Primary(Primary__c==True) if one does not exist.  Can I utilize my existing Class or do I have to create a new one
Thank you for your time and help.
M
public without sharing class ContactTrgHandler 
{
  public static void onBeforeInsert(List<Contact> trgNew)
  {
    Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
    for(Contact c : trgNew)
    {
      if(String.isNotEmpty(c.AccountId) && c.Primary__c)
      {
        if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
          accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
        accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
      }      
    }
    if(!accountIdToNewContactRtMap.isEmpty())
    {
      Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
      {
        existingContactRtMap.put(a.Id,new Set<Id>());
        for(Contact c : a.Contacts)
          existingContactRtMap.get(a.Id).add(c.RecordTypeId);
      }
      for(Contact c : trgNew)
      {
        if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
          c.addError('There is already a primary contact for this record type.');
      }
    }
  }
  public static void onBeforeUpdate(List<Contact> trgNew,Map<Id,Contact> oldMap)
  {
    Map<Id,Set<Id>> accountIdToNewContactRtMap = new Map<Id,Set<Id>>();
    for(Contact c : trgNew)
    {
      if(String.isNotEmpty(c.AccountId) && c.Primary__c && !oldMap.get(c.Id).Primary__c)
      {
        if(!accountIdToNewContactRtMap.containsKey(c.AccountId))
          accountIdToNewContactRtMap.put(c.AccountId,new Set<Id>());
        accountIdToNewContactRtMap.get(c.AccountId).add(c.RecordTypeId);
      }
    }
    if(!accountIdToNewContactRtMap.isEmpty())
    {
      Map<Id,Set<Id>> existingContactRtMap = new Map<Id,Set<Id>>();
      for(Account a : [SELECT Id,(SELECT RecordTypeId FROM Contacts WHERE Primary__c=true) FROM Account WHERE Id in :accountIdToNewContactRtMap.keySet()])
      {
        existingContactRtMap.put(a.Id,new Set<Id>());
        for(Contact c : a.Contacts)
          existingContactRtMap.get(a.Id).add(c.RecordTypeId);
      }
      for(Contact c : trgNew)
      {
        if(existingContactRtMap.containsKey(c.AccountId) && existingContactRtMap.get(c.AccountId).contains(c.RecordTypeId))
          c.addError('There is already a primary contact for this record type.');
      }
    }
  }
}

 
hello
plz help me in this trigger code

If owner of an Account has gone on leave for more than 90 days then type field should be updated with "Former Client".
If owner of an Account has gone on leave for more than 180 days and if the owner has a delegated user then the delegated user should be updated as Owner.
If owner of an Account has gone on leave for more than 180 days and if the owner has no delegated user then type field should be updated with "Deactivated".
Hi All

I have created 5 custom object(Quote,QuoteLineItem,QuoteProductLineItem,Product,ProductLineItem) and created relationship.I have created a custom button in quote  which will add prodcut with select option in quoteLineItem and its working fine .Prodcut have child object ProductLineItem.Need to fecth child record of product in QuoteProductLine Item which is child of QuoteLineItem when I click add button to click.

 
Not a duplicate question guys. Different aspect of the code.

Goal of the code:
Auto add product B once product A is added to the opportunity

Issue:
Adding product B to a different opportunity and not to the opportunity that product A is being added to.

Any idea why? or what part of the code that I should focus on to test different solutions?

Code:
trigger NOVEMBER1 on OpportunityLineItem (after insert, after update)
    {
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    
        List<String> lstProductCodes = new List<String>();
     
        for(OpportunityLineItem optLineItem: Trigger.new)
        {
            if(optLineItem.ProductCode == '00002a')
            {
                lstProductCodes.add(optLineItem.ProductCode);
            }
        }
     
        if(lstProductCodes.size()>0)
        {
            System.debug('lstProductCodes=' + lstProductCodes);
     
            //retrieve the values based on Product list
            List<OpportunityLineItem> lstOpptyLineItems = [SELECT Opportunity.Pricebook2Id, Name, ProductCode , PricebookEntryId, Quantity, UnitPrice
                                                            FROM    OpportunityLineItem
                                                            WHERE ProductCode IN:lstProductCodes];
     
            //create a map which contains Product Name and OpportunityLineItem
            Map<String, OpportunityLineItem> mapOpptyLineItem = new Map<String, OpportunityLineItem>();
            for(OpportunityLineItem item:lstOpptyLineItems)
            {
                mapOpptyLineItem.put(item.ProductCode, item);
            }
     
     
            Id pbkId = lstOpptyLineItems[0].Opportunity.Pricebook2Id;
     
            //retrieve PriceBookEntry of the Product B, this is most important
            PricebookEntry pbeProduct2 = [SELECT Id, Pricebook2Id, UnitPrice, Name, Fee_Percentage_Entry__c 
                                            FROM PricebookEntry
                                            WHERE Name ='Car Oil Fee'
                                            AND Pricebook2Id  IN (SELECT Id FROM PriceBook2 WHERE Id ='01sA00000004lbRIAQ')
                                            LIMIT 1];
     
     
            //retrieve Product A item from the map.        
            OpportunityLineItem itemProductA = mapOpptyLineItem.get('00002a');
            System.debug('itemProductA= ' + itemProductA);
     
            if(itemProductA != null)
            {
                if(Trigger.isInsert)
                {
                //now assign Product A items as required, you can retrieve the amount from Product A
                oliList.add(new OpportunityLineItem(
                    OpportunityId = itemProductA.OpportunityId,
                    PricebookEntryId = pbeProduct2.Id,
                    Quantity = itemProductA.Quantity,
                    UnitPrice = itemProductA.UnitPrice * pbeProduct2.Fee_Percentage_Entry__c * 0.01 )
                  );
                System.debug('oliList=' + oliList);
                insert oliList;
            }
            else if (Trigger.isUpdate)
                {
                    //if you need to update PriceBookEntry of Product B
                    pbeProduct2.UnitPrice = itemProductA.UnitPrice * pbeProduct2.Fee_Percentage_Entry__c * 0.01 ;
                    update pbeProduct2;
     
                    //if you need to update OpportunityLineItem of Product B
                    OpportunityLineItem optLIProductB = [SELECT OpportunityId, Opportunity.Pricebook2Id,
                                                            Name, ProductCode , PricebookEntryId,
                                                            Quantity, UnitPrice
                                                            FROM    OpportunityLineItem
                                                            WHERE ProductCode = '00002b'];
     
                    optLIProductB.Quantity = mapOpptyLineItem.get('00002a').Quantity;
                    optLIProductB.UnitPrice = mapOpptyLineItem.get('00002a').UnitPrice * pbeProduct2.Fee_Percentage_Entry__c * 0.01 ;
     
                    update optLIProductB;
                }
        }
    }
    }

 
  • November 14, 2017
  • Like
  • 0