• SFDCIronMan
  • NEWBIE
  • 50 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 12
    Questions
  • 11
    Replies
Hey ,

I'm trying to create a validation from trigger i.e, if Stage is Proposal And Primary Contact Role Email is Null 
Apex trigger:-
trigger OpportunityTrigger on Opportunity(After update) 
{        OpportunityHandler.AfterUpdate(Trigger.newMap,Trigger.new);
}



Apex Class:-
public class OpportunityHandler 
{
    public static void AfterUpdate(Map<Id,Opportunity> oppMapRecords,List<Opportunity> oppListRecords)
    { 
        Set<Id> SetID = new Set<Id>();
        for(Opportunity opp : oppListRecords)
        {
            if(opp.StageName == 'Proposal' && opp.Account.IsPersonAccount == False && opp.ContactId != null)
            {
                SetId.add(opp.Id);
                System.debug(SetId);
            }
        }   
        
        List<Opportunity> oppList = [Select Id, Account.IsPersonAccount, StageName,(Select Id, Contact.Email From OpportunityContactRoles Where IsPrimary = true And OpportunityId IN: SetId ) From Opportunity Where Id IN: SetId];
        System.debug(oppList); 
        
        Map<Id,OpportunityContactRole> conRoleMap = new Map<Id,OpportunityContactRole>([Select Id, IsPrimary , OpportunityId, Contact.Email from OpportunityContactRole Where OpportunityId IN: SetID And IsPrimary = true]);
        System.debug(conRoleMap);
       
        For(Opportunity valOpp : oppList)
        {
            System.debug(valOpp);         
            System.debug(conRoleMap.containsKey(valOpp.Id));
            
            if(conRoleMap.containsKey(valOpp.Id))
            {
                if(conRoleMap.get(valOpp.Id).Contact.Email == Null)
                {
                    
                    Opportunity oppError = oppMapRecords.get(valOpp.Id);  
                    System.debug(oppError);
                    
                    oppError.addError('Please Enter Primary Contact Role "Email" Before Changing Stage To "Proposal"');
                }                
            }
        }
    }
}
in this the map is getting null values in the filter and i cant figure out why please help me with my case 

Thanks in advance 
Himanshu
 
public class Opportunity_Clone_Handler 
{
    
    public static void AfterUpdateCloneOpportunity(List<Opportunity> newReacords, Map<Id, Opportunity> oldRecords)
    {   
        //For  List of Clone Opportunity 
        List<Opportunity> oppsToInsert = new List<Opportunity>();
        
        //For Mapping IDs from Opportunity to OpportunityLineItem 
        Map<Id,List<OpportunityLineItem>> oplitemsMap = new  Map<Id,List<OpportunityLineItem>>();
        
        //For Fetching Inserted Or Old list To Clone
        List<OpportunityLineItem> oppitemlist = new List<OpportunityLineItem>();
        
        //For Fetching Inserted IDs Or Old IDs To Clone Opportunity
        Set<Id> OldID = new Set<Id>();
        
        //For Fetching Newly Inserted Ids for OpportunityLineitem
        Set<Id> parentOppIds = new set<Id>();
        
        Set<Id> OldOppIds = new Set<Id>();
        
        Set<Id> ChildOppIds = new Set<Id>();
        
        //For Preventing Recursion
        if(OpportunityRecursive_Trigger_Handler.isFirstTime)
        {
            //Resursion Handler Class
            OpportunityRecursive_Trigger_Handler.isFirstTime = false;
            
            //Fetching Insert and Old Opportunit Ids
            for(opportunity opp: newReacords)
            {
                OldID.add(opp.id);
            }//End oF 'for'
            
            //Checking the ids
            List<Opportunity> ListOpp = [Select id, Name, AccountId, Product_Type__c, CloseDate, StageName, Payment_Frequency__c, Most_Recent_Invoice_Date__c, Billing_Start_Date__c, Interval__c, Parent_Opportunity__c, Create_Child_Opportunities_Invoice__c, Cancelation_Date__c, Service_End_Date__c from Opportunity where id IN:OldID];
            // List<Opportunity> ListOpp = [Select id, Name, AccountId, CloseDate, StageName from Opportunity where id IN:SetID];
            
            //for Updated new Opportunity
            for(Opportunity parentopp : ListOpp)
            { 
                //checking Old ids checkbox
                if(oldRecords.get(parentopp.Id).Create_Child_Opportunities_Invoice__c != parentopp.Create_Child_Opportunities_Invoice__c && parentopp.Create_Child_Opportunities_Invoice__c && parentopp.StageName == 'Closed Won' && parentopp.Product_Type__c == 'Subscription' && parentopp.Payment_Frequency__c != Null && parentopp.Interval__c != Null)
                {
                    Integer Interval = Integer.valueOf(parentopp.Interval__c);
                    Integer Count;
                    Date closedate;
                    For(Count=1; Count<=Interval; Count++)
                    {
                        parentOppIds.add(parentopp.Id);
                        Opportunity childopp = new Opportunity();
                        childopp.Name = parentopp.Name +'_'+childopp.CloseDate;
                        childopp.AccountId = parentopp.AccountId;
                        childopp.Type = 'Invoice';
                        childopp.Product_Type__c = parentopp.Product_Type__c;
                        
                        If(parentopp.Billing_Start_Date__c != Null && Count == 1)
                        {
                            If(parentopp.Payment_Frequency__c == 'Monthly')
                            {
                                childopp.CloseDate = parentopp.Billing_Start_Date__c.toStartOfMonth();
                                closeDate = childopp.CloseDate;
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Quarterly')
                            {
                                childopp.CloseDate = parentopp.Billing_Start_Date__c.toStartOfMonth();
                                closeDate = childopp.CloseDate;
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Half Yearly')
                            {
                                childopp.CloseDate = parentopp.Billing_Start_Date__c.toStartOfMonth();
                                closeDate = childopp.CloseDate;
                            }
                            else
                            {    
                                childopp.CloseDate = parentopp.CloseDate.toStartOfMonth();
                                closeDate = childopp.CloseDate;
                            }
                        }
                        
                        else if(parentopp.Billing_Start_Date__c != Null && Count != 1)
                        { 
                            
                            If(parentopp.Payment_Frequency__c == 'Monthly')
                            {
                                childopp.CloseDate = closeDate.addMonths(1);
                                closeDate = childopp.CloseDate.toStartOfMonth();
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Quarterly')
                            {
                                childopp.CloseDate = closeDate.addMonths(3);
                                closeDate = childopp.CloseDate.toStartOfMonth();
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Half Yearly')
                            {
                                childopp.CloseDate = closeDate.addMonths(6);
                                closeDate = childopp.CloseDate.toStartOfMonth();
                            }
                            else
                            {    
                                childopp.CloseDate = closeDate;
                                closeDate = childopp.CloseDate.toStartOfMonth();
                            }  
                            
                        }                        
                        childopp.StageName = 'Closed Won';
                        childopp.Parent_Opportunity__c = parentopp.Id;
                        
                        oppsToInsert.add(childopp);
                        
                    }//End Of for
                    
                }//End of If Checkbox
                
            }//End of for 
            
            //Iterating OpportunityLineitems For Opportunity to update related OpportunityLineItem if Present
            for(OpportunityLineitem opl : [SELECT Id, Product2Id, Quantity, UnitPrice, Pricebookentryid, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : parentoppIds])
            {
                //Mapping Inserted or Old opportunityIds to Clone the related OpportunityLineItem
                if(!oplitemsMap.containsKey(opl.OpportunityId))
                {
                    oplitemsMap.put(opl.OpportunityId, new List<OpportunityLineitem>{opl});
                }//End of IF Old IDs
                
                else
                {
                    oplitemsMap.get(opl.OpportunityId).add(opl);
                }//end of else
                
            }//End Of for iteration oppoopportunityLineItem
            
            //If Opportunity is Not Empty 
            if(!oppsToInsert.IsEmpty())
            {
                //Cloning Inserted Or Updated Opportunity  
                upsert oppsToInsert;
                
                //Iterating Cloned Inserted Or Updated Opportunity for OpportunityLineItem 
                for(Opportunity op : oppsToInsert)
                {
                    //for inserted Or updated Opportunity if Parent_opportunity__c is equals Opportunity
                    if(oplitemsMap.containsKey(op.Parent_Opportunity__c))
                    {
                        //Iterating OpportunityLineitem From Parent Opportunity For Cloning Its OpportunityLineItem
                        for(OpportunityLineitem ol : oplitemsMap.get(op.Parent_Opportunity__c))
                        {
                            OpportunityLineItem oli = new OpportunityLineitem();
                            oli.OpportunityId = op.Id;
                            oli.Product2Id = ol.Product2Id;
                            oli.Quantity = ol.Quantity;
                            oli.UnitPrice = ol.UnitPrice;
                            oli.pricebookentryid=ol.pricebookentryid;
                            oppitemlist.add(oli);
                        }//End of for
                        
                    }//End of If
                    
                }//End Of For
                
                //Cloning OpportunityLineItem From Parent Opportunity OpportunityLineItem 
                if(!oppitemlist.isEmpty())
                {
                    insert oppitemlist;
                }//End Of if
                
                
            }//End of If for "Cloning OpportunityLineItem"
            
            for(Opportunity parentOppty : ListOpp)
            { 
                if(parentOppty.Cancelation_Date__c != Null || parentOppty.Service_End_Date__c != Null)
                {
                    OldOppIds.add(parentOppty.Id);
                }
            }
                        
            for(Opportunity childOppty : [Select Id, CloseDate, Parent_Opportunity__c From Opportunity Where Parent_Opportunity__c IN : OldOppIds])
            {
                for(Opportunity parentOppty : ListOpp)
                { 
                    if(parentOppty.Cancelation_Date__c != Null && childOppty.CloseDate > parentOppty.Cancelation_Date__c || parentOppty.Service_End_Date__c != Null && childOppty.CloseDate > parentOppty.Service_End_Date__c)
                    {
                        ChildOppIds.add(childOppty.Id);
                    }
                }
            }
                       
            
            List<Opportunity> oppsToDelete = [Select Id, CloseDate, Parent_Opportunity__c From Opportunity Where Id IN : ChildOppIds];
            
            if(!oppsToDelete.IsEmpty())
            {
                delete oppsToDelete;
            }
            
            
        }//End Of Recursion 
        
    }//End of after Update
   
}
help me solve im new noob here
i wanted to Create a button when click pass the The Id of Opportunity to the Visual Force page then to the Controller and then to another Apex Class.
help me create apex class from this Batch Class 
this Batch Class is for handling bulk record I want to create this code for handling single record with Apex Class With Opportunity ID


/* Batch class to Synch Opportunies to AccountRight
 * Makes API calls to accountRight
 * 1. Checks if Opportunity Account exists in AccountRight
 * 2. If not creates an Account(Card Type) inAccount right.
 * 3. Create Sales Order in Account Right.
 * 4. Update Account and Oppotunity with error/success messages.
 * @changes: 2018-10-06 - CI - Add error handling in accountMap update
 */ 

global class SynchOrderToAccountRightBatch implements Database.Batchable < sObject >, Database.Stateful, Database.AllowsCallouts {
    
    //collections to work with
    Map<id, OpportunityLineItem> oppLineMap = new Map<id, OpportunityLineItem>();
    //Map<id, Opportunity> oppMap = new Map<id, Opportunity>();
    Map<id, Account> accountMap = new Map<id, Account>();
    List<User> salesUser = new List<User>();
    String gstTaxCode;
    
    Map<String,MyobRegionUID__c> regionUIDMap;
    
    //Lineitems does not work when batch runs, so have to query line items in execute method
    String sqlStr = 'SELECT id, Ownerid , CloseDate, AccountId, Freight_exc__c, Account.Name, Owner.Name,owner.MYOB_Employee_UID__c, Opportunity_Number__c, Purchase_Order__c, MYOB_Order_Number__c, Region__c, AFQ_Company__c, StageName, owner.firstname,owner.lastname ' + 
                                        //', (SELECT Quantity, Discount, UnitPrice, Description, TotalPrice, PricebookEntry.Name, PricebookEntry.Product2.Name, PricebookEntry.Product2.Family, PricebookEntry.Product2.ProductCode FROM OpportunityLineItems) '+
                                        ',  (select id,External_Comments__c,IsSyncing from Quotes ) ' +                                                     
                                        'from Opportunity where MYOB_Order_Number__c = Null and AFQ_Company__c = \'Australia\' and MYOB_Synch_Status__c != \'Success\' and closedate >= 2017-05-01 and StageName = \'Closed Won\'';
    //we are picking opportunities closed from 1st May 2017
    // Start Method
    global Database.QueryLocator start(Database.BatchableContext BC) 
    {
        AccountRightAPI apiAccRight = new AccountRightAPI();
        gstTaxCode = apiAccRight.taxCode;
        regionUIDMap = apiAccRight.regionUIDMap;
        return Database.getQueryLocator(sqlStr);
        //return null;
    }

    // Execute Logic
    global void execute(Database.BatchableContext BC, List <SObject> scope) {
        //Contrainer for opportunities to work with
        Map<id, Opportunity> oppMap = new Map<id, Opportunity>();
        system.debug('entry point product execute method ' + scope);
        AccountRightAPI apiAccRight = new AccountRightAPI();
        // exit if there are no records returns from API return
        if(scope == null)
            return;
        List<Opportunity> oppList = (List<Opportunity>)scope;
        Set<id> accntId = new Set<id>();
        //loop through the scope and prepare data to work with
        //Consider Opportunity which are closed won, AFQ is Australia and Myob order is NULL
        for(Opportunity thisOpp : oppList){
            if(thisOpp.StageName.equalsIgnoreCase('Closed Won') 
                && thisOpp.AFQ_Company__c.equalsIgnoreCase('Australia')
                && thisOpp.MYOB_Order_Number__c == NULL){
                 oppMap.put(thisOpp.Id, thisOpp); 
                 system.debug('thisOpp ' +thisOpp);   
                 system.debug('thisOpp ' +thisOpp.OpportunityLineitems);
                 accntId.add(thisOpp.AccountId);   
            }
        }
        // get opportunity line items
        for(OpportunityLineItem thisLine :[Select OpportunityId, ProductCode, PricebookEntry.Product2.MYOB_Product_UID__c,
                                             Product2.Name, Quantity, UnitPrice, 
                                             Description, Discount 
                                             from OpportunityLineItem 
                                             where OpportunityId in:oppMap.keySet()]) {
            oppLineMap.put(thisLine.Id, thisLine);
        }

        
        //get the accounts associated with Opportunities, 
        //we need to verify if these accounts exist in AccountRight
        //If does not exist in AccountRight - Create and in AccountRight and update in Salesforce
       // Map<Id, Account> accListToCreatedInMyob = new Map<Id, Account> ();
        for(Account thisAcc : [Select Id, Name, MYOB_Card_ID__c, MYOB_Account__c, BillingCity, BillingStreet, Invoice_Email__c,
                                    BillingState, BillingPostalCode, BillingCountry, Phone, Fax, Company_Email__c, 
                                    ShippingStreet, ShippingState, ShippingPostalCode, ShippingCountry, ShippingCity,MYOB_Account_UID__c, 
                                    Parent.MYOB_Account_UID__c,ParentId, Parent.MYOB_Card_ID__c, Parent.Name, Parent.BillingCity, Parent.MYOB_Account__c, 
                                    Parent.BillingStreet, Parent.BillingState, Parent.BillingPostalCode, Parent.BillingCountry, 
                                    Parent.Phone, Parent.Fax, Parent.Invoice_Email__c, Parent.ShippingStreet,Parent.ShippingState, 
                                    Parent.ShippingPostalCode, shippingAddress, billingAddress, Parent.shippingAddress, Parent.billingAddress, 
                                    Parent.ShippingCountry, Parent.ShippingCity 
                                    from Account
                                    where Id IN: accntId]) {
            accountMap.put(thisAcc.Id, thisAcc);
        }
        
        system.debug('accountMap  ' + accountMap);
        try{
            //loop through opps and synch to Myob one at a time
            for(Opportunity thisOpp : oppMap.values()){
                try{
                    synchOppToMyob(thisOpp, accountMap.get(thisOpp.AccountId),apiAccRight);
                }catch(Exception exp){
                    system.debug('in ctach  block exception ' + exp.getMessage());
                    thisOpp.Myob_Synch_Status__c = 'Failed'; thisOpp.Myob_Synch_Message__c = exp.getMessage();
                    continue;
                }
            }      

            //create Invoices for the synched Orders/opportunitie
            List<Invoice__c> invList = new List<Invoice__c>();
            for(Opportunity thisOpp : oppMap.values()){
                if(thisOpp.MYOB_Synch_Status__c.equalsIgnorecase('Success')){
                    //make api call to get order values to be populated to invoice
                    AccountRightSaleAPI api = new AccountRightSaleAPI('/Sale/Order');
                    List<AccountRightAPI.SaleOrder> orderRes = api.find(new AccountRightAPI.FilterOperator('Number', 'eq', thisOpp.Opportunity_Number__c));
                    AccountRightAPI.SaleOrder thisAcOrder = orderRes.get(0);//there should be only one order in Account right
                    Invoice__c inv = new Invoice__c();
                    inv.Name = thisOpp.Opportunity_Number__c; inv.Opportunity__c = thisOpp.Id; inv.Account__c = thisOpp.AccountId; inv.Subtotal__c = thisAcOrder.Subtotal;
                    inv.Freight__c = thisAcOrder.Freight; inv.Total_Amount__c = thisAcOrder.TotalAmount; inv.Date__c = getDate(thisAcOrder.DateString); inv.Status__c = 'Order'; inv.Balance_Due__c = thisAcOrder.BalanceDueAmount;
                    invList.add(inv);
                }
            }
            
            //update MYOB flag for the created account
            if(oppMap.size() > 0){
                update oppMap.values();
            }

            List<Account> failedAccountUpdatesList = new List<Account>();
            if(accountMap.size() > 0){
                List<Database.SaveResult> results = Database.update(accountMap.values(), false);
                for (Database.SaveResult sr : results) {
                    if (!sr.isSuccess()) {
                        for(Database.Error err : sr.getErrors()) {
                            Account newAcc = new Account();
                            newAcc.Id = sr.getId(); newAcc.MYOB_Sync_Message__c = err.getMessage();
                            failedAccountUpdatesList.add(newAcc);
                        }
                    }
                }
            }

            if(!failedAccountUpdatesList.isEmpty()){
                update failedAccountUpdatesList;
            }

            //insert invoices
            if(invList.size() > 0)
                insert invList;
            
            //update user
            if(salesUser.size() > 0)
                update salesUser;
        }catch(Exception exp){
            system.debug('exception while inserting records ' + exp.getMessage());
        }
    }
Create a custom checkbox field on Opportunity and name it ‘Add Products?’
Create a multi-select picklist field on Opportunity that shows list of products one can auto-select.
Create a picklist field on Opportunity as Pricebook.
Each time an opportunity record is saved with Ádd Products’ selected as true following should happen
Throw validation error if pricebook and products are not selected.
Once opportunity is saved auto insert opportunity products on basis of selection made on pricebook and products.
Code should be able to handle bulk data; meaning multiple opportunity records can be inserted together using Import Wizard or Data loader
Code should adhere to programming best practices like
Standardized Naming conventions
Apt utilization of collection elements
Follow of Trigger pattern
Follow Trigger deactivation mechanism
Avoiding Trigger recurrence on same object
Proper Code comments
Keeping Salesforce Governor limits into consideration
Create test class to ensure developed code can be deployed; adhere to best practices of testing framework
//this is the code Ive made
public class OpportunityProductAndPriceBook_Handler 
{
    public static void AfterInsertOpportunity(List<Opportunity> records)
    {
        List<OpportunityLineItem> lineItem = new List<OpportunityLineItem>();
        
        List<Pricebook2> priceBook = new List<Pricebook2>();
        
        if(RecursiveTriggerHandler.isFirstTime)
        {
            RecursiveTriggerHandler.isFirstTime = false;
            for(Opportunity opp : records)
            {
                if(opp.Add_Products__c)
                {
                    OpportunityLineItem oli = new OpportunityLineItem();
                    oli.OpportunityId = opp.id;
                    oli.Product2Id = opp.Select_Product__c;
                    oli.Quantity = opp.Product_Quantity__c;
                    lineItem.add(oli);
                    
                    Pricebook2 pb = new Pricebook2();
                    pb.Id = opp.Pricebook2Id;
                    pb.Name = opp.Price_Book__c;
                    priceBook.add(pb);
                }
            }
            if(!lineItem.IsEmpty() && !priceBook.IsEmpty())
            {
                insert lineItem;
                insert priceBook;
            }
        }
    }
}


and this the error im getting from the code please help me 

OpportunityProductAndPriceBook_Trigger: execution of AfterInsert caused by: System.StringException: Invalid id: GenWatt Diesel 1000kW Class.OpportunityProductAndPriceBook_Handler.AfterInsertOpportunity: line 18, column 1 Trigger.OpportunityProductAndPriceBook_Trigger: line 5, column 1


Regards
SFDCIronMan
**SOQL Query for comparing Parent Opportunity Cancelation_Date__C with Child Opportunity CloseDate for Deleteing Child Opportunities where Parent Opportunity Cancelation_Date__c Is less then Child Opportunity CloseDate**

//Please Help solve this
for(Opportunity childOppty : oppsToInsert)
            {
                for(Opportunity parentOppty : ListOpp)
                {
                    if(parentOppty.Cancelation_Date__c != Null && childOppty.CloseDate > parentOppty.Cancelation_Date__c ||parentOppty.Service_End_Date__c != Null && childOppty.CloseDate > parentOppty.Service_End_Date__c)
                    {
                        childOppIds.add(childOppty.Id);
                        parentDate = parentOppty.Cancelation_Date__c;
                    }
                }
            }
            
            List<Opportunity> oppsToDelete = [Select Id, CloseDate, Parent_Opportunity__c From Opportunity Where Id IN : childOppIds];
            
            if(!oppsToDelete.isEmpty())
            {
                delete oppsToDelete;
            }
//

Thanks in Advance 
public class Opportunity_CloneHandler2 
{
    
    public static void OpportunityCloneData(List<Opportunity> records)
    {
        //Holds list Of Opportunity 
        List<Opportunity> ListOpp = new List<Opportunity>(); 
        //holds list of OpportunityLineItem 
        List<OpportunityLineItem> ListOppItem  = new List<OpportunityLineItem>(); 
        //final list for insertion
        SObject[] sobjList = new List<SObject>(); 
        
        Set<id> parentOppIds = new set<Id>();
        
        Set<Id> childOppIds = new Set<Id>();
        
        Map<Id,List<OpportunityLineItem>> oplitemsMap = new  Map<Id,List<OpportunityLineItem>>();
        
        //hold OpportunityId and ExternalId in Map
        Map<String,String> OpportunityOpportunityLineItemMap = new Map<String,String>();
        
        //For Preventing Recursion
        if(OpportunityRecursive_Trigger_Handler.isFirstTime)
        {
            //Resursion Handler Class
            OpportunityRecursive_Trigger_Handler.isFirstTime = false;
            
            //Cloning Opportunity 
            for(Opportunity parentopp : records)
            { 
                //If Paramters
                if(parentopp.Create_Child_Opportunities_Invoice__c && parentopp.StageName == 'Closed Won' && parentopp.Product_Type__c == 'Subscription' && parentopp.Payment_Frequency__c != Null && parentopp.Interval__c != Null && parentopp.Interval__c != Null)
                {
                    Integer Interval = Integer.valueOf(parentopp.Interval__c);
                    For(Integer Count=1;Count<=Interval;Count++)
                    {
                        parentoppIds.add(parentopp.Id);
                        
                        Opportunity newopp = new Opportunity();
                        
                        newopp.External_Id__c = String.valueOf(Integer.valueOf(math.rint(math.random()*100000)));
                        newopp.Name = parentopp.Name;
                        newopp.AccountId = parentopp.AccountId;
                        newopp.Type = 'Invoice';
                        newopp.StageName = 'Closed Won';
                        newopp.Product_Type__c = parentopp.Product_Type__c;
                        If(parentopp.Billing_Start_Date__c != Null)
                        {
                            If(parentopp.Payment_Frequency__c == 'Monthly')
                            {
                                newopp.CloseDate = parentopp.Billing_Start_Date__c.addMonths(1);
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Quarterly')
                            {
                                newopp.CloseDate = parentopp.Billing_Start_Date__c.addMonths(3);
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Half Yearly')
                            {
                                newopp.CloseDate = parentopp.Billing_Start_Date__c.addMonths(6);
                            }
                        }
                        else
                        {    
                            newopp.CloseDate = parentopp.CloseDate;
                        }    
                        newopp.Payment_Frequency__c = parentopp.Payment_Frequency__c;
                        newopp.Interval__c = parentopp.Interval__c;
                        newopp.Billing_Start_Date__c = newopp.CloseDate;
                        newopp.Parent_Opportunity__c = parentopp.Id;
                        newopp.Cancelation_Date__c = parentopp.Cancelation_Date__c;
                        newopp.Service_End_Date__c = parentopp.Service_End_Date__c;
                        OpportunityOpportunityLineItemMap.put(newopp.Name,newopp.External_Id__c);
                        
                        childOppIds.add(newopp.Id);
                        //Final List
                        ListOpp.add(newopp);
                        If(parentopp.Cancelation_Date__c != Null && newopp.CloseDate > newopp.Cancelation_Date__c || parentopp.Service_End_Date__c != Null && newopp.CloseDate > newopp.Cancelation_Date__c)
                        {
                            for(Opportunity delOpp : [Select Id, Name, AccountId, Type, StageName, Product_Type__C, CloseDate, Billing_Start_Date__c From Opportunity Where Type = 'Invoice' And StageName = 'Closed Won' And Id IN : childOppIds] )
                            {
                                ListOpp.add(delOpp);
                            }
                            delete ListOpp;
                        }
                        
                    }//End of if Checkbox
                    
                }//End of for
                
            }
            
            //Fetching OpportunityLineitems For Opportunity to update related OpportunityLineItem if Present
            for(OpportunityLineitem opl : [SELECT Id, Product2Id, Quantity, UnitPrice,pricebookentryid, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : parentOppIds])
            {
                //Mapping Inserted or Old opportunityIds to Clone the related OpportunityLineItem
                if(!oplitemsMap.containsKey(opl.OpportunityId))
                {
                    oplitemsMap.put(opl.OpportunityId, new List<OpportunityLineitem>{opl});
                }//End of IF Old IDs
                
                else
                {
                    oplitemsMap.get(opl.OpportunityId).add(opl);
                }//end of else
                
            }//End Of for iteration oppoopportunityLineItem
            
            for(Opportunity op : ListOpp)
            {
                //Iterating OpportunityLineitem From Parent Opportunity For Cloning Its OpportunityLineItem
                for(OpportunityLineitem ol : oplitemsMap.get(op.Parent_Opportunity__c))
                {
                    OpportunityLineItem oli = new OpportunityLineitem();
                    oli.OpportunityId = op.Id;
                    oli.Product2Id = ol.Product2Id;
                    oli.Quantity = ol.Quantity;
                    oli.UnitPrice = ol.UnitPrice;
                    oli.pricebookentryid=ol.pricebookentryid;
                    
                    if(OpportunityOpportunityLineItemMap.containsKey(op.Name))
                    {
                        Opportunity lineItemRef = new Opportunity(External_Id__c = OpportunityOpportunityLineItemMap.get(op.Name));
                        oli.Opportunity = lineItemRef;
                    }
                    
                    ListOppItem.add(oli);
                }//End of for
            }
            
            //add Opportunity And OpportunityLineItem List  
            sobjList.addAll(ListOpp);
            sObjList.addAll(ListOppItem);
            
            Database.SaveResult[] results = Database.insert(sobjList);
        }//End of If for Cloning
        
    }//End Of Preventing Recursion
}
Create two record types on account - Partner, Supplier.
- Attached is Account & Contact Data to be loaded.
- You are free to make any changes in the salesforce data schema to ensure that Contacts are connected to their respective Accounts on the basis of Account Unique Id of the external system.
Use Case:-
ABC firms want to view Contact from their child orgs.
 Business Process
- ABC firm has two salesforce org (Parent and Child).
- In the Parent org they want a Visualforce Tab 'Insert Child Contact'.
- Once someone clicks on this Tab, establish real time integration with the child salesforce org.
- Insert all the contacts along with accounts into the Parent Salesforce Org.
trigger OpportunityCloneTrigger on Opportunity (After insert,After update) 
{   
    //For  List of Clone Opportunity 
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    //For Mapping IDs from Opportunity to OpportunityLineItem 
    Map<Id,List<OpportunityLineItem>> oplitemsMap = new  Map<Id,List<OpportunityLineItem>>();
    
    //For Fetching Inserted Or Old list To Clone
    List<OpportunityLineItem> oppitemlist = new List<OpportunityLineItem>();
    
    //For Fetching Inserted IDs Or Old IDs To Clone Opportunity
    Set<Id> SetID = new Set<Id>();
    
    //For Fetching Newly Inserted Ids for OpportunityLineitem
    Set<id> oppIds = new set<Id>();
    
    //For Preventing Recursion
    if(OpportunityRecursiveTriggerHandler.isFirstTime)
    {
        //Resursion Handler Class
        OpportunityRecursiveTriggerHandler.isFirstTime = false;
        
        //Fetching Insert and Old Opportunit Ids
        for(opportunity opp:Trigger.new)
        {
            SetID.add(opp.id);
        }//End oF 'for'
        
        //Checking the ids
        List<Opportunity> ListOpp = [Select id, Name, AccountId, Product_Type__c, CloseDate, StageName, Payment_Frequency__c, Most_Recent_Invoice_Date__c, Billing_Start_Date__c, Interval__c, Parent_Opportunity__c, Clone_Opportunity__c from Opportunity where id IN:SetID];
        
        //For Newly Inserted Opportunity
        if(Trigger.IsInsert)
        {
            //Cloning Opportunity 
            for(Opportunity opp : ListOpp)
            { 
                //If CheckBox Clone_Opportunity__c is checked
                if(opp.Clone_Opportunity__c)
                {
                    //IF StageName is Closed Won
                    if(opp.StageName == 'Closed Won')
                    {
                        //If Product Type is Subscription
                        if(opp.Product_Type__C == 'Subscription')
                        {
                            //if Payment Frequency is not Empty 
                            if(opp.Payment_Frequency__c != Null)
                            {
                                //If Next Invoice Date is Today
                                if(opp.Next_Invoice_Date__c == system.today())
                                {
                                    //If Parent Opportunity is Empty
                                    if(opp.Parent_Opportunity__c == Null)
                                    {
                                        
                                        oppIds.add(opp.Id);
                                        Opportunity newopp = new Opportunity(); 
                                        newopp.Name = opp.Name + ' Clone';
                                        newopp.AccountId = opp.AccountId;
                                        newopp.Product_Type__c = opp.Product_Type__c;
                                        newopp.CloseDate = opp.CloseDate;
                                        newopp.StageName = opp.StageName;
                                        newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
                                        newopp.Most_Recent_Invoice_Date__c  = opp.Most_Recent_Invoice_Date__c;
                                        newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
                                        newopp.Interval__c = opp.Interval__c;
                                        newopp.Parent_Opportunity__c = opp.Id;
                                        oppsToUpdate.add(newopp);
                                        
                                    }//End of If Parent Opportunity
                                
                                }//End of if Next Invoice date 
                                
                            }//End of If Payment Frequency
                            
                        }//End Of If Product Type
                        
                    }//End of If StageName
                    
                }//End of if Checkbox
                
            }//End of for 
            
        }//End of if IsInsert
        
        //if old Opportunity is Updated
        else if(Trigger.IsUpdate)
        {
            //for Updated new Opportunity 
            for(Opportunity opp : ListOpp)
            { 
                //checking Old ids checkbox
                if(Trigger.oldMap.get(opp.Id).Clone_Opportunity__c != opp.Clone_Opportunity__c && opp.Clone_Opportunity__c)
                {
                    //IF StageName is Closed Won
                    if(opp.StageName == 'Closed Won')
                    {
                        //If Product Type is Subscription
                        if(opp.Product_Type__C == 'Subscription')
                        {
                            //if Payment Frequency is not Empty 
                            if(opp.Payment_Frequency__c != Null)
                            {
                                //If Next Invoice Date is Today
                                if(opp.Next_Invoice_Date__c == system.today())
                                {
                                    //If Parent Opportunity is Empty
                                    if(opp.Parent_Opportunity__c == Null)
                                    {
                                        
                                        oppIds.add(opp.Id);
                                        Opportunity newopp = new Opportunity(); 
                                        newopp.Name = opp.Name + ' Clone';
                                        newopp.AccountId = opp.AccountId;
                                        newopp.Product_Type__c = opp.Product_Type__c;
                                        newopp.CloseDate = opp.CloseDate;
                                        newopp.StageName = opp.StageName;
                                        newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
                                        newopp.Most_Recent_Invoice_Date__c  = opp.Most_Recent_Invoice_Date__c;
                                        newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
                                        newopp.Interval__c = opp.Interval__c;
                                        newopp.Parent_Opportunity__c = opp.Id;
                                        oppsToUpdate.add(newopp);
                                        
                                    }//End of If Parent Opportunity
                                
                                }//End of if Next Invoice date 
                                
                            }//End of If Payment Frequency
                            
                        }//End Of If Product Type
                        
                    }//End of If StageName
                    
                }//End of If Checkbox
                
            }//End of for   
            
        }//End of If IsUpdate
        
        //Iterating OpportunityLineitems For Opportunity to update related OpportunityLineItem if Present
        for(OpportunityLineitem opl : [SELECT Id, Product2Id, Quantity, UnitPrice,pricebookentryid, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : oppIds])
        {
            //Mapping Inserted or Old opportunityIds to Clone the related OpportunityLineItem
            if(!oplitemsMap.containsKey(opl.OpportunityId))
            {
                oplitemsMap.put(opl.OpportunityId, new List<OpportunityLineitem>{opl});
            }//End of IF Old IDs
            
            else
            {
                oplitemsMap.get(opl.OpportunityId).add(opl);
            }//end of else
            
        }//End Of for iteration oppoopportunityLineItem
        
        //If Opportunity is Not Empty 
        if(!oppsToUpdate.IsEmpty())
        {
            //Cloning Inserted Or Updated Opportunity  
            insert oppsToUpdate;
            
            //Iterating Cloned Inserted Or Updated Opportunity for OpportunityLineItem 
            for(Opportunity op : oppsToUpdate)
            {
                //system.debug(' Id --> ' + op.Id);
                //system.debug(' Parent Id --> ' + op.Parent_Opportunity__c);
                
                //for inserted Or updated Opportunity if Parent_opportunity__c is equals Opportunity
                if(oplitemsMap.containsKey(op.Parent_Opportunity__c))
                {
                    //Iterating OpportunityLineitem From Parent Opportunity For Cloning Its OpportunityLineItem
                    for(OpportunityLineitem ol : oplitemsMap.get(op.Parent_Opportunity__c))
                    {
                        OpportunityLineItem oli = new OpportunityLineitem();
                        oli.OpportunityId = op.Id;
                        oli.Product2Id = ol.Product2Id;
                        oli.Quantity = ol.Quantity;
                        oli.UnitPrice = ol.UnitPrice;
                        oli.pricebookentryid=ol.pricebookentryid;
                        oppitemlist.add(oli);
                    }//End of for
                    
                }//End of If
                
            }//End Of For
            
            //Cloning OpportunityLineItem From Parent Opportunity OpportunityLineItem 
            if(!oppitemlist.isEmpty())
            {
                insert oppitemlist;
            }//End Of if
            
        }//End of If for Cloning
        
    }//End Of Preventing Recursion
    
}//End Of trigger
Help me Create a Trigger for CheckBox to clone Opportunity and OpportunityLineItem
//This is what i have coded please help resolve this
trigger CloneParentOpportunityTrigger on Opportunity (After insert,After update) 
{
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    Map<Id,Opportunity> OldOppId = new Map<Id,Opportunity>();
    Opportunity newopp = new Opportunity(); 
    if(Trigger.IsAfter)
    {
        if(Trigger.IsInsert || Trigger.IsUpdate)
        {
            if(newopp.Clone_Opportunity__c)
            {
                for(Opportunity opp : Trigger.new)
                { 
                    //opportunity list item
                    newopp.Name = opp.Name;
                    newopp.AccountId = opp.AccountId;
                    newopp.Product_Type__c = opp.Product_Type__c;
                    newopp.CloseDate = opp.CloseDate;
                    newopp.StageName = opp.StageName;
                    newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
                    newopp.Most_Recent_Invoice_Date__c  = opp.Most_Recent_Invoice_Date__c;
                    newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
                    newopp.Parent_Opportunity__c = opp.Id;
                    oppsToUpdate.add(newopp);
                    OldOppId.put(opp.id,opp);
                }
                
                insert oppsToUpdate;
                
                Map<Id,Opportunity> NewOppId = new Map<Id,Opportunity>();
                for(Opportunity opp1 : oppsToUpdate)
                {
                    NewOppId.put(opp1.Id, opp1);
                }
                
                List<OpportunityLineItem> oppitemList = new List<OpportunityLineItem>([SELECT Id, Product2Id, Quantity, UnitPrice, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : OldOppId.keyset()]);
                for(OpportunityLineItem oppitem : oppitemList)
                {
                    OpportunityLineItem oli = new OpportunityLineitem();
                    oli.OpportunityId = NewOppId.get(oppitem.OpportunityId).Id;
                    oli.Product2Id = oppitem.Product2Id;
                    oli.Quantity = oppitem.Quantity;
                    oli.UnitPrice = oppitem.UnitPrice;
                    oppitemlist.add(oli);
                }
                insert oppitemList;
            }
        }   
    }
}
Help me Create a Trigger for CheckBox to clone Opportunity and OpportunityLineItem
//This is what i have coded please help resolve this
trigger CloneParentOpportunityTrigger on Opportunity (After insert,After update) 
{
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    Map<Id,Opportunity> OldOppId = new Map<Id,Opportunity>();
    Opportunity newopp = new Opportunity(); 
    if(Trigger.IsAfter)
    {
        if(Trigger.IsInsert || Trigger.IsUpdate)
        {
            if(newopp.Clone_Opportunity__c)
            {
                for(Opportunity opp : Trigger.new)
                { 
                    //opportunity list item
                    newopp.Name = opp.Name;
                    newopp.AccountId = opp.AccountId;
                    newopp.Product_Type__c = opp.Product_Type__c;
                    newopp.CloseDate = opp.CloseDate;
                    newopp.StageName = opp.StageName;
                    newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
                    newopp.Most_Recent_Invoice_Date__c  = opp.Most_Recent_Invoice_Date__c;
                    newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
                    newopp.Parent_Opportunity__c = opp.Id;
                    oppsToUpdate.add(newopp);
                    OldOppId.put(opp.id,opp);
                }
                
                insert oppsToUpdate;
                
                Map<Id,Opportunity> NewOppId = new Map<Id,Opportunity>();
                for(Opportunity opp1 : oppsToUpdate)
                {
                    NewOppId.put(opp1.Id, opp1);
                }
                
                List<OpportunityLineItem> oppitemList = new List<OpportunityLineItem>([SELECT Id, Product2Id, Quantity, UnitPrice, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : OldOppId.keyset()]);
                for(OpportunityLineItem oppitem : oppitemList)
                {
                    OpportunityLineItem oli = new OpportunityLineitem();
                    oli.OpportunityId = NewOppId.get(oppitem.OpportunityId).Id;
                    oli.Product2Id = oppitem.Product2Id;
                    oli.Quantity = oppitem.Quantity;
                    oli.UnitPrice = oppitem.UnitPrice;
                    oppitemlist.add(oli);
                }
                insert oppitemList;
            }
        }   
    }
}
Hey ,

I'm trying to create a validation from trigger i.e, if Stage is Proposal And Primary Contact Role Email is Null 
Apex trigger:-
trigger OpportunityTrigger on Opportunity(After update) 
{        OpportunityHandler.AfterUpdate(Trigger.newMap,Trigger.new);
}



Apex Class:-
public class OpportunityHandler 
{
    public static void AfterUpdate(Map<Id,Opportunity> oppMapRecords,List<Opportunity> oppListRecords)
    { 
        Set<Id> SetID = new Set<Id>();
        for(Opportunity opp : oppListRecords)
        {
            if(opp.StageName == 'Proposal' && opp.Account.IsPersonAccount == False && opp.ContactId != null)
            {
                SetId.add(opp.Id);
                System.debug(SetId);
            }
        }   
        
        List<Opportunity> oppList = [Select Id, Account.IsPersonAccount, StageName,(Select Id, Contact.Email From OpportunityContactRoles Where IsPrimary = true And OpportunityId IN: SetId ) From Opportunity Where Id IN: SetId];
        System.debug(oppList); 
        
        Map<Id,OpportunityContactRole> conRoleMap = new Map<Id,OpportunityContactRole>([Select Id, IsPrimary , OpportunityId, Contact.Email from OpportunityContactRole Where OpportunityId IN: SetID And IsPrimary = true]);
        System.debug(conRoleMap);
       
        For(Opportunity valOpp : oppList)
        {
            System.debug(valOpp);         
            System.debug(conRoleMap.containsKey(valOpp.Id));
            
            if(conRoleMap.containsKey(valOpp.Id))
            {
                if(conRoleMap.get(valOpp.Id).Contact.Email == Null)
                {
                    
                    Opportunity oppError = oppMapRecords.get(valOpp.Id);  
                    System.debug(oppError);
                    
                    oppError.addError('Please Enter Primary Contact Role "Email" Before Changing Stage To "Proposal"');
                }                
            }
        }
    }
}
in this the map is getting null values in the filter and i cant figure out why please help me with my case 

Thanks in advance 
Himanshu
 
public class Opportunity_CloneHandler2 
{
    
    public static void OpportunityCloneData(List<Opportunity> records)
    {
        //Holds list Of Opportunity 
        List<Opportunity> ListOpp = new List<Opportunity>(); 
        //holds list of OpportunityLineItem 
        List<OpportunityLineItem> ListOppItem  = new List<OpportunityLineItem>(); 
        //final list for insertion
        SObject[] sobjList = new List<SObject>(); 
        
        Set<id> parentOppIds = new set<Id>();
        
        Set<Id> childOppIds = new Set<Id>();
        
        Map<Id,List<OpportunityLineItem>> oplitemsMap = new  Map<Id,List<OpportunityLineItem>>();
        
        //hold OpportunityId and ExternalId in Map
        Map<String,String> OpportunityOpportunityLineItemMap = new Map<String,String>();
        
        //For Preventing Recursion
        if(OpportunityRecursive_Trigger_Handler.isFirstTime)
        {
            //Resursion Handler Class
            OpportunityRecursive_Trigger_Handler.isFirstTime = false;
            
            //Cloning Opportunity 
            for(Opportunity parentopp : records)
            { 
                //If Paramters
                if(parentopp.Create_Child_Opportunities_Invoice__c && parentopp.StageName == 'Closed Won' && parentopp.Product_Type__c == 'Subscription' && parentopp.Payment_Frequency__c != Null && parentopp.Interval__c != Null && parentopp.Interval__c != Null)
                {
                    Integer Interval = Integer.valueOf(parentopp.Interval__c);
                    For(Integer Count=1;Count<=Interval;Count++)
                    {
                        parentoppIds.add(parentopp.Id);
                        
                        Opportunity newopp = new Opportunity();
                        
                        newopp.External_Id__c = String.valueOf(Integer.valueOf(math.rint(math.random()*100000)));
                        newopp.Name = parentopp.Name;
                        newopp.AccountId = parentopp.AccountId;
                        newopp.Type = 'Invoice';
                        newopp.StageName = 'Closed Won';
                        newopp.Product_Type__c = parentopp.Product_Type__c;
                        If(parentopp.Billing_Start_Date__c != Null)
                        {
                            If(parentopp.Payment_Frequency__c == 'Monthly')
                            {
                                newopp.CloseDate = parentopp.Billing_Start_Date__c.addMonths(1);
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Quarterly')
                            {
                                newopp.CloseDate = parentopp.Billing_Start_Date__c.addMonths(3);
                            }
                            else 
                                If(parentopp.Payment_Frequency__c == 'Half Yearly')
                            {
                                newopp.CloseDate = parentopp.Billing_Start_Date__c.addMonths(6);
                            }
                        }
                        else
                        {    
                            newopp.CloseDate = parentopp.CloseDate;
                        }    
                        newopp.Payment_Frequency__c = parentopp.Payment_Frequency__c;
                        newopp.Interval__c = parentopp.Interval__c;
                        newopp.Billing_Start_Date__c = newopp.CloseDate;
                        newopp.Parent_Opportunity__c = parentopp.Id;
                        newopp.Cancelation_Date__c = parentopp.Cancelation_Date__c;
                        newopp.Service_End_Date__c = parentopp.Service_End_Date__c;
                        OpportunityOpportunityLineItemMap.put(newopp.Name,newopp.External_Id__c);
                        
                        childOppIds.add(newopp.Id);
                        //Final List
                        ListOpp.add(newopp);
                        If(parentopp.Cancelation_Date__c != Null && newopp.CloseDate > newopp.Cancelation_Date__c || parentopp.Service_End_Date__c != Null && newopp.CloseDate > newopp.Cancelation_Date__c)
                        {
                            for(Opportunity delOpp : [Select Id, Name, AccountId, Type, StageName, Product_Type__C, CloseDate, Billing_Start_Date__c From Opportunity Where Type = 'Invoice' And StageName = 'Closed Won' And Id IN : childOppIds] )
                            {
                                ListOpp.add(delOpp);
                            }
                            delete ListOpp;
                        }
                        
                    }//End of if Checkbox
                    
                }//End of for
                
            }
            
            //Fetching OpportunityLineitems For Opportunity to update related OpportunityLineItem if Present
            for(OpportunityLineitem opl : [SELECT Id, Product2Id, Quantity, UnitPrice,pricebookentryid, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : parentOppIds])
            {
                //Mapping Inserted or Old opportunityIds to Clone the related OpportunityLineItem
                if(!oplitemsMap.containsKey(opl.OpportunityId))
                {
                    oplitemsMap.put(opl.OpportunityId, new List<OpportunityLineitem>{opl});
                }//End of IF Old IDs
                
                else
                {
                    oplitemsMap.get(opl.OpportunityId).add(opl);
                }//end of else
                
            }//End Of for iteration oppoopportunityLineItem
            
            for(Opportunity op : ListOpp)
            {
                //Iterating OpportunityLineitem From Parent Opportunity For Cloning Its OpportunityLineItem
                for(OpportunityLineitem ol : oplitemsMap.get(op.Parent_Opportunity__c))
                {
                    OpportunityLineItem oli = new OpportunityLineitem();
                    oli.OpportunityId = op.Id;
                    oli.Product2Id = ol.Product2Id;
                    oli.Quantity = ol.Quantity;
                    oli.UnitPrice = ol.UnitPrice;
                    oli.pricebookentryid=ol.pricebookentryid;
                    
                    if(OpportunityOpportunityLineItemMap.containsKey(op.Name))
                    {
                        Opportunity lineItemRef = new Opportunity(External_Id__c = OpportunityOpportunityLineItemMap.get(op.Name));
                        oli.Opportunity = lineItemRef;
                    }
                    
                    ListOppItem.add(oli);
                }//End of for
            }
            
            //add Opportunity And OpportunityLineItem List  
            sobjList.addAll(ListOpp);
            sObjList.addAll(ListOppItem);
            
            Database.SaveResult[] results = Database.insert(sobjList);
        }//End of If for Cloning
        
    }//End Of Preventing Recursion
}
Use Case:-
ABC firms want to view Contact from their child orgs.
 Business Process
- ABC firm has two salesforce org (Parent and Child).
- In the Parent org they want a Visualforce Tab 'Insert Child Contact'.
- Once someone clicks on this Tab, establish real time integration with the child salesforce org.
- Insert all the contacts along with accounts into the Parent Salesforce Org.
Help me Create a Trigger for CheckBox to clone Opportunity and OpportunityLineItem
//This is what i have coded please help resolve this
trigger CloneParentOpportunityTrigger on Opportunity (After insert,After update) 
{
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    Map<Id,Opportunity> OldOppId = new Map<Id,Opportunity>();
    Opportunity newopp = new Opportunity(); 
    if(Trigger.IsAfter)
    {
        if(Trigger.IsInsert || Trigger.IsUpdate)
        {
            if(newopp.Clone_Opportunity__c)
            {
                for(Opportunity opp : Trigger.new)
                { 
                    //opportunity list item
                    newopp.Name = opp.Name;
                    newopp.AccountId = opp.AccountId;
                    newopp.Product_Type__c = opp.Product_Type__c;
                    newopp.CloseDate = opp.CloseDate;
                    newopp.StageName = opp.StageName;
                    newopp.Payment_Frequency__c = opp.Payment_Frequency__c;
                    newopp.Most_Recent_Invoice_Date__c  = opp.Most_Recent_Invoice_Date__c;
                    newopp.Billing_Start_Date__c = opp.Billing_Start_Date__c;
                    newopp.Parent_Opportunity__c = opp.Id;
                    oppsToUpdate.add(newopp);
                    OldOppId.put(opp.id,opp);
                }
                
                insert oppsToUpdate;
                
                Map<Id,Opportunity> NewOppId = new Map<Id,Opportunity>();
                for(Opportunity opp1 : oppsToUpdate)
                {
                    NewOppId.put(opp1.Id, opp1);
                }
                
                List<OpportunityLineItem> oppitemList = new List<OpportunityLineItem>([SELECT Id, Product2Id, Quantity, UnitPrice, OpportunityId FROM OpportunityLineItem Where OpportunityId IN : OldOppId.keyset()]);
                for(OpportunityLineItem oppitem : oppitemList)
                {
                    OpportunityLineItem oli = new OpportunityLineitem();
                    oli.OpportunityId = NewOppId.get(oppitem.OpportunityId).Id;
                    oli.Product2Id = oppitem.Product2Id;
                    oli.Quantity = oppitem.Quantity;
                    oli.UnitPrice = oppitem.UnitPrice;
                    oppitemlist.add(oli);
                }
                insert oppitemList;
            }
        }   
    }
}
Hi  all,
I am having an issue with calling a component from another. There are other parts to my component but I am posting a part of my code.
The first component is calling the second component on a button click which calls the function callSaveComp: I am trying to pass the record id of the current record since the first component is on the Account page. So using "v.recordId" in the controller. I can see that v.recordId has the value of the account record but it doesn't get passed to the next component on button click.
<aura:component controller="PartnerAffiliates" implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction,force:appHostable" access="global" >

other code.....
        <lightning:button variant="neutral" label="New" onclick="{!c.callSaveComp}"/>

</aua:component>


controller for first component:
callSaveComp : function(component, event, helper){
        var evt = $A.get("e.force:navigateToComponent");
        console.log('Event '+evt);
        var accountFromId = component.get("v.recordId");
        evt.setParams({
            componentDef  : "c:AffiliateSaveForm" ,
            componentAttribute : {
                accId : accountFromId
            }
        

        });
      
        evt.fire();
}

Second component:
<aura:component access="global" controller="PartnerAffiliates" implements="force:appHostable">
     <aura:attribute name="accId" type="String" access="global"/>
    Other stuff....
</aura:component>

Is it possible to do something like this? or do I have to use lightning Events?


Thank you

This is the class that I use to create first the opportunity header and then specific line items,  PROBLEM,,,,  For some reason it only takes the first of the line items and adds it to the new renewal opportunity.  Please help I will give major kudos.

 

Heres the code:

public with sharing class RenewalOpportunityCreation {

    public static void CreateRenewalOpportunity(Map<Id,Opportunity> oldMap, Map<Id,Opportunity> newMap)
    {

        List<Opportunity> opptsToInsert = new List<Opportunity>();
        Opportunity newOppt = new Opportunity();

        List<Id> OpptyIds = new List<Id>();

        for (Opportunity o : newMap.Values())
        {   
            OpptyIds.add(o.id);
        }

        for(Opportunity oppt : [Select RecordTypeId, Name, Contact__c, AccountId, id, (Select PriceBookEntry.Name, unitprice, 
                                Quantity, Classification__c, Is_Price_book_Entry_Active__c,Is_Product_Active__c  From OpportunityLineItems 
                                Where (Classification__c= 'Software'  OR Classification__c= 'Bundle (SW w/ HW)' OR Classification__c= 'Annual Maintenance' 
                                OR Classification__c = 'Annual Maintenance - 2nd Year & Beyond'))             
                                From Opportunity where Id in :OpptyIds])
        {
            newOppt.Name =  oppt.Name + ' Renewal Opportunity';
            newOppt.AccountId = oppt.AccountId;
            newOppt.Contact__c = oppt.Contact__c;
            newOppt.RecordTypeId =  ServiceClass.getRecordTypesNameMap('Opportunity').get('Renewal Opportunity').Id;                                                        
            newOppt.CloseDate = Date.Today()+30;
            newOppt.StageName = 'Renewal Opportunity';                  
            newOppt.Type = 'Add-On Business';
            newOppt.NextStep = 'Send a invoice for maintenance renewal';
            newOppt.Payment_Terms__c = 'Net 30';
            newOppt.ForecastCategoryName = 'Omitted';
            newOppt.Owner_Location__c = 'FL';
            newOppt.Original_Opportunity__c = oppt.Id;
            newOppt.OwnerId = '00570000001MRuL';
            
            newOppt.Renewal_Software__c = '';
            
            for (OpportunityLineItem lineItem :oppt.OpportunityLineItems) 
            {
                newOppt.Renewal_Software__c = newOppt.Renewal_Software__c + LineItem.PriceBookEntry.Name + '\n';
            }
            
            if(newOppt.Renewal_Software__c <> Null)
            {
                opptsToInsert.add(newOppt);
            }
          
        }
    
        if(opptsToInsert.size() > 0)
        {
            insert(opptsToInsert);
            
            List<OpportunityLineItem> opptLineItemsToInsert = new List<OpportunityLineItem>();
            
            List<Opportunity> OpptIdToInsert = new List<Opportunity>();
            Opportunity newOpptId = new Opportunity();
  
            for(Opportunity opptInsertedIDs : [Select Id, Description from Opportunity where Id in :opptsToInsert])
            {   
                newOpptId.ID = opptInsertedIDs.id;
 
                OpportunityLineItem newOpptLineItem = new OpportunityLineItem();   
                       
           
            
                for(Opportunity opptInserted : [Select RecordTypeId, Name, Contact__c, AccountId, id, Description, (Select PricebookEntry.Name,PricebookEntryid, 
                                                UnitPrice, Quantity, TotalPrice, Classification__c, Is_Price_book_Entry_Active__c,Is_Product_Active__c  
                                                From OpportunityLineItems Where (Classification__c = 'Software'  OR Classification__c= 'Bundle (SW w/ HW)' 
                                                OR Classification__c= 'Annual Maintenance' OR Classification__c = 'Annual Maintenance - 2nd Year & Beyond')) 
                                                From Opportunity where Id in :OpptyIds])
                {       
                    for (OpportunityLineItem lineItem2 :opptInserted.OpportunityLineItems) {
                    newOpptLineItem.Quantity = lineItem2.Quantity;
                    newOpptLineItem.UnitPrice = lineItem2.UnitPrice;
                    newOpptLineItem.PricebookEntryId = lineitem2.PricebookEntry.id;
                }
              
                newOpptLineItem.OpportunityID = newOpptId.ID;
                
                
                opptLineItemsToInsert.add(newOpptLineItem);                 
                
            }
            if(opptLineItemsToInsert.size() > 0)
            {
                insert(opptLineItemsToInsert);
            }
        }}
    }
}

 Thank you,

 Steve Laycock