• HTANIRS
  • NEWBIE
  • 200 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 34
    Questions
  • 38
    Replies
Hi Experts,

I have the below requirement and I need to know how can I proceed.
I have a custom field in Account Obj as Status "Active and Inactive" which is a picklist.
When an account is Inactive, I should not allow the user to edit the record. But I need to allow them to enter or edit Tasks, Events, Relatedlists on that record.

I have created the Validation Rule but it is not allowing any changes on the account when Inactive.

Kindly need your inputs to complete.

Thanks in Advance.
Hi Experts,

Need help in code coverage for Trigger Test Class.
Test Class not covering in Custom Metadata part which was mentioned in Bold.
 
Trigger:

trigger updateMembershipPrice on OpportunityLineItem (after insert) {
    Set<Id> oppsIds = new Set<Id>();    
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    List<OpportunityLineItem> updateOliList = new List<OpportunityLineItem>();
    Map<String, String> mapOpp = new Map<String, String>();
                
    for(OpportunityLineItem oli : Trigger.new) {
        oppsIds.add(oli.OpportunityId);
        System.debug('--- Opps Id ---' + oli.OpportunityId);
    }
    
    Map<String, Decimal> mapcustomProRate = new Map<String, Decimal>();
    
    for(MembershipPrice__mdt customMetadata : [SELECT Membership_Type__c, Month__c, Pro_Rate_Price__c FROM MembershipPrice__mdt]) {
        mapcustomProRate.put(customMetadata.Month__c +'' + customMetadata.Membership_Type__c, customMetadata.Pro_Rate_Price__c);        
    }
         
    Map<Id, Date> mapDateApproved = new Map<Id, Date>();
    
    for(OpportunityLineItem olit : [SELECT Id, OpportunityId, Opportunity.Date_Approved__c, Product2.Name FROM OpportunityLineItem WHERE OpportunityId IN: oppsIds]) {
        if(olit.Opportunity.Date_Approved__c != NULL && olit.Product2Id != NULL) {
            Datetime dt = (Datetime)olit.Opportunity.Date_Approved__c;
            String monthname = dt.format('MMMM');
            if(mapcustomProRate.containsKey(monthname +''+ olit.Product2.Name)) {
                OpportunityLineItem oli = new OpportunityLineItem();
                oli.Id = olit.Id;
                oli.UnitPrice = mapcustomProRate.get(monthname +''+ olit.Product2.Name);
                updateOliList.add(oli);
            }   
        }
    }    

    if(updateOliList.size() > 0) {
        update updateOliList;
    }   
    
}
 
Test Class:

@isTest
private class updateMembershipPrice_Test {
    static testMethod void updateMembershipPrice_Test () {
        //create Account
        Account acc = new Account(Name = 'Test Account');
        insert acc;
        
        //create Contact
        Contact con = new Contact(LastName = 'Test', AccountId = acc.Id, FirstName = 'Contact', Email = 'Test@sf.com', MailingStreet = '123', OtherStreet = '213');
        insert con;        

        //get standard pricebook
        Id pricebookId = Test.getStandardPricebookId();

        //add product
        Product2 prd1 = new Product2 (Name='Test Product Entry 1',Description='Test Product Entry 1',productCode = 'ABC', isActive = true);
        insert prd1;
        
        //add pricebookentry for standard pricebook
        PricebookEntry pbe1 = new PricebookEntry (Product2ID = prd1.id, Pricebook2ID = pricebookId, UnitPrice = 50, isActive = true);
        insert pbe1;
        
        //add opportunity
        Opportunity opp = new Opportunity (Name = 'Opp', Date_Approved__c = Date.today(), StageName = 'Qualification', CloseDate = Date.today(), Pricebook2Id = pbe1.Pricebook2Id, AccountId = acc.id);
        insert opp;
        
        //add opportunity line item
        OpportunityLineItem lineItem = new OpportunityLineItem (OpportunityID = opp.id, PriceBookEntryID = pbe1.id, quantity = 1, totalprice = 200);
        insert lineItem;
        
        lineItem.quantity = 2;
        lineItem.UnitPrice = 400;
        update lineItem;        
    }
}

Kindly suggest the changes need to be done.

Thanks.
  • September 20, 2020
  • Like
  • 0
Hi Experts,

I need assistance in completing the below trigger.
I have a custom object where it has lookup to Order object. I have a custom fields ProductName, Quantity.
Product Name, Quantity will be with more values sometimes single value which is separated by commas.
Ex: ProductName: SampleProduct,SampleProduct1
      Quantity: 5,2
I want to insert multiple Order Item with respect to that Order like ProductName: SampleProduct, Quantity: 5 as 1 record and another record as ProductName: SampleProduct1, Quantity: 2  where ProductName should be matched from Pricebookentry and insert in orderitem.
 
trigger insertOrderItem on OrderItem__c (after insert) {
    // Custom Order Item Collections
    Set<Id> orderitemIds = new Set<Id>();
    List<OrderItem__c> oiList = new List<OrderItem__c>();
    List<OrderItem__c> deloiList = new List<OrderItem__c>();
    
    // order collections
    List<order> ordList = new List<Order>();
    Map<Id, Order> ordMap = new Map<Id, Order>();
    
    // pricebookentry collections
    Map<String, List<pricebookentry>> pricebookMap = new Map<String, List<pricebookentry>>();
    List<Pricebookentry> pbeList = new List<Pricebookentry>();
    
    // orderitem collections
    List<OrderItem> oitList = new List<OrderItem>();
    
    for(OrderItem__c oi : Trigger.New) {
        orderitemIds.add(oi.Order__c);
        System.debug('--- Order Id in Custom Oi Obj ---' + oi.Order__c);        
    }
    
    if(!orderitemIds.isEmpty()) {
        pbeList = [SELECT Id, Name, Pricebook2Id, Pricebook2.Name, Product2Id, IsActive
                      FROM Pricebookentry
                      WHERE IsActive = true AND Pricebook2.Name = 'Standard Price Book' AND Pricebook2.Name IN: orderitemIds];
        
        for(Order ord : [SELECT Id FROM Order WHERE Id IN: orderitemIds]) {
            ordMap.put(ord.Id, ord);
        }
        
        for(Pricebookentry pbe : pbeList) {
            if(!pricebookMap.containsKey(pbe.Product2.Name)) {
                pricebookMap.put(pbe.Product2.Name, new List<Pricebookentry> {pbe});
            }
            else {
                List<Pricebookentry> pbeLists = pricebookMap.get(pbe.Product2.Name);
                pbeLists.add(pbe);
                pricebookMap.put(pbe.Product2.Name, pbeLists);
            }
        }
    }
    
    for(OrderItem__c oi : Trigger.New) {
/* Need to insert Order Item*/ 
     
   List<String> Name = oi.ProductName__c.split(',');
        List<String> Qty = oi.Quantity__c.split(',');
        List<String> UnitPrice = oi.UnitPrice__c.split(',');
        
        System.debug('--- Name ---' + Name);
        System.debug('--- Qty ---' + Qty);
        System.debug('--- UnitPrice ---' + UnitPrice);
        
        Map<Id, Product2> proIdMap = new Map<Id, Product2>([SELECT Id FROM Product2 WHERE Name IN: Name]);
        
        OrderItem oit = new OrderItem();
        oit.OrderId = oi.Order__c;
        oit.Quantity = // Split Quantity Value.
        oit.UnitPrice = // Split UnitPrice Value.
        oit.PricebookEntryId = // Split ProductName Value;
        oitList.add(oit);
    }
    
    if(!oitList.isEmpty()) {
        insert oitList;
        System.debug('---Order Item Inserted Size---' + oitList.size());
    }
}

Thanks in Advance.
Hi Friends,

I have a requirement when I need to insert Opportunity Contact Role when Opportunity is created.
My code is working fine when creating a Opportunity from Contact but a duplicate is getting created when Converting a Opportunity from Lead.
 
trigger updateContactRole on Opportunity (after insert, after update) {
    
    System.debug('-- Inside Opportunity Contact Role Trigger---');
    
    List<OpportunityContactRole> newContactRoleList = new List<OpportunityContactRole>();
    Map<Id, Id> opportunityAccountMap = new Map<Id, Id>();
	Map<Id, List<Id>> mapOpportunityContact = new Map<Id, List<Id>>();
	Map<Id, List<Id>> mapOpportunityContactRole = new Map<Id, List<Id>>();
	
	for(Opportunity opp : trigger.new) {
		if(opp.AccountId != null) {
			opportunityAccountMap.put(opp.AccountId, opp.Id);
		}
	}
	
	// get contacts from opportunity account 
	for(Contact cont: [SELECT Id, AccountId FROM Contact WHERE accountId IN: opportunityAccountMap.keySet()]) {
		List<Id> contactIds = new List<Id>();
		if(mapOpportunityContact.containsKey(opportunityAccountMap.get(cont.AccountId))) {
			contactIds = mapOpportunityContact.get(opportunityAccountMap.get(cont.AccountId));
		}
		contactIds.add(cont.Id);
		mapOpportunityContact.put(opportunityAccountMap.get(cont.AccountId), contactIds);
	}
	
	
	// get contacts from opportunity contact role. 
	for(OpportunityContactRole contRole: [SELECT Id, OpportunityId, ContactId FROM OpportunityContactRole 
											WHERE OpportunityId IN: opportunityAccountMap.values()]) {
		List<Id> oppContactIds = new List<Id>();
		if(mapOpportunityContactRole.containsKey(contRole.OpportunityId)) {
			oppContactIds = mapOpportunityContactRole.get(contRole.OpportunityId);
		}
		oppContactIds.add(contRole.ContactId);
		mapOpportunityContactRole.put(contRole.OpportunityId, oppContactIds);
	}
	
	
	for(Id oppId : mapOpportunityContact.keySet()) {		
		// opp account contacts
		List<Id> contactRoles = new List<Id>();
        if(mapOpportunityContactRole.containsKey(oppId)) {
            contactRoles = mapOpportunityContactRole.get(oppId);
        }
		
		for(Id contId :  mapOpportunityContact.get(oppId)){
			if(!contactRoles.contains(contId)){
				OpportunityContactRole myContactRole = new OpportunityContactRole();
				myContactRole.ContactId = contId;
				myContactRole.OpportunityId = oppId;
                                myContactRole.isPrimary = true;
				newContactRoleList.add(myContactRole);
			}
		}		
	}
    
    try {
        if(newContactRoleList.size()>0) {
            insert newContactRoleList;
        }
    }

    catch(Exception e) {
        System.debug(e);
    }
}

Kindly refer the code and let me know how can I solve this issue.

Thanks in advance..
Hi Friends,

I have a requirement where I need to create a Quote when a Opportunity Product is added.
When creating a Quote I need to copy contact details based on Opportunity Contact Role where Contact is Primary.
I am getting Contact Name but, got Stuck in getting a Contact Email, Contact MailingAddress and Contact Other Address. It is not getting populated in Quote.
 
/** Trigger on Opportunity Line Item to insert Quote and Quotelineitem **/
trigger quoteCreation on OpportunityLineItem (after insert) {
    if(Trigger.isAfter && Trigger.isInsert){
        List<Quote> quoteList = new List<Quote>();
        Set<ID> oppIds = new Set<ID>();
        Set<Id> processIds = new Set<ID>();
        
        for(OpportunityLineItem oppli : Trigger.New){
            oppIds.add(oppli.Id);
        }
        
        List<OpportunityLineItem> opplList = new List<OpportunityLineItem>();
        if(oppIds != null && oppIds.size() >0){
            opplList = [SELECT Id, Opportunity.Name, Opportunity.AccountId, Opportunity.Account.PersonContactId, OpportunityId, Opportunity.Account.Name, Opportunity.Account.PersonEmail,
                        Opportunity.Account.Salutation, Opportunity.Account.BillingCity, Opportunity.Account.BillingCountry, Opportunity.Account.BillingPostalCode, Opportunity.Account.BillingState,
                        Opportunity.Account.ShippingCity, Opportunity.Account.ShippingCountry, Opportunity.Account.ShippingPostalCode, Opportunity.Account.ShippingState,
                        Opportunity.Account.BillingStreet, Opportunity.Account.ShippingStreet, Opportunity.ContactId, Opportunity.Account.isPersonAccount
                        FROM OpportunityLineItem 
                        WHERE Id IN:oppIds];
        }
        if(opplList != null && opplList.size() >0 ){
            for(OpportunityLineItem oppli : opplList) {        
                Quote quo = new Quote();
                quo.Name = 'Quote - ' + oppli.Opportunity.Name;
                quo.Status = 'Draft';
                quo.OpportunityId = oppli.OpportunityId;
               // Getting Contact Details from Business Account.
                if(oppli.Opportunity.Account.isPersonAccount == False)
                {
                    quo.ContactId = oppli.Opportunity.ContactId;
                    quo.Email = oppli.Opportunity.Contact.Email;
                    /*
                          Need to get Contact Mailing Address and Other Address.
                    */
                }

               // Getting Contact Details from Person Account.
                else
                {
                    quo.ContactId = oppli.Opportunity.Account.PersonContactId;
                    quo.Email = oppli.Opportunity.Account.PersonEmail;
                    quo.BillingName = oppli.Opportunity.Account.Name;
                    quo.ShippingName = oppli.Opportunity.Account.Name;
                    quo.BillingStreet = oppli.Opportunity.Account.BillingStreet; 
                    quo.BillingCity = oppli.Opportunity.Account.BillingCity;
                    quo.BillingCountry = oppli.Opportunity.Account.BillingCountry;
                    quo.BillingPostalCode = oppli.Opportunity.Account.BillingPostalCode;
                    quo.BillingState = oppli.Opportunity.Account.BillingState;
                    quo.ShippingStreet = oppli.Opportunity.Account.ShippingStreet;        
                    quo.ShippingCity = oppli.Opportunity.Account.ShippingCity;
                    quo.ShippingCountry = oppli.Opportunity.Account.ShippingCountry;
                    quo.ShippingPostalCode = oppli.Opportunity.Account.ShippingPostalCode;
                    quo.ShippingState = oppli.Opportunity.Account.ShippingState;
                }
               
                if(!processIds.contains(quo.OpportunityId))
                {
                    quoteList.add(quo);
                    processIds.add(quo.OpportunityID);
                }
            }
        }
        
        try {        
            if(quoteList.size() > 0) {    
                insert quoteList;
            }
        }
        catch(Exception e) {
            System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
        }
        // Insert Quote Line Item 
        set<Id> oppId = new Set<Id>();
        set<Id> pcrId = new set<Id>(); 
        List<QuoteLineItem> oliPist = new  List<QuoteLineItem>();
        if(quoteList != null && quoteList.size() >0){
            for(Quote quo : quoteList) {
                if(quo.opportunityId != null) {
                    oppId.add(quo.opportunityId);
                }
            }
        }
        Map<Id, List<OpportunityLineItem>> olitoOpp = new  Map<Id, List<OpportunityLineItem>>();
        if(oppId != null && oppId.size() >0){
            for(OpportunityLineItem oli : [SELECT Id, Quantity, UnitPrice, PricebookEntryId, Product2Id, OpportunityId 
                                           FROM OpportunityLineItem WHERE opportunityId IN : oppId]) {
                                               pcrId.add(oli.Product2Id);
                                               if(olitoOpp.containsKey(oli.opportunityId)) {
                                                   olitoOpp.get(oli.opportunityId).add(oli);
                                               }
                                               else {
                                                   olitoOpp.put(oli.opportunityId, new List<OpportunityLineItem> {oli});
                                               }
                                           }
        }
        
        for(Quote quot : quoteList) {
            if(olitoOpp.containsKey(quot.opportunityId)) {
                for(OpportunityLineItem  oli : olitoOpp.get(quot.opportunityId)){
                    if(oli != null)
                        oliPist.add(new QuoteLineItem(QuoteId=quot.Id,Quantity = oli.Quantity,PricebookEntryId = oli.PricebookEntryId,UnitPrice = oli.UnitPrice,Product2Id = oli.Product2Id));
                }
            }
        }
        if(!oliPist.isEmpty()) {
            insert oliPist;
        }
    }
}

Kindly review my code and let me know how can I get contact values.

Thanks in Advance.

 
Hi Friends,

I have created a trigger on Opportunity to insert a contact role based on Account in Opportunity.
This is working fine when I create a account--> contact --> opportunity. But when I am converting a lead to account--> contact--> opportunity, 2 contact roles are getting created which is duplicate.
 
trigger updateContactRole on Opportunity (after insert, after update) {
    
    System.debug('-- Inside Opportunity Contact Role Trigger---');
    
    List<OpportunityContactRole> newContactRoleList = new List<OpportunityContactRole>();
    Map<Id, Id> opportunityAccountMap = new Map<Id, Id>();
	Map<Id, List<Id>> mapOpportunityContact = new Map<Id, List<Id>>();
	Map<Id, List<Id>> mapOpportunityContactRole = new Map<Id, List<Id>>();
	
	for(Opportunity opp : trigger.new) {
		if(opp.AccountId != null) {
			opportunityAccountMap.put(opp.AccountId, opp.Id);
		}
	}
	
	// get contacts from opportunity account 
	for(Contact cont: [SELECT Id, AccountId FROM Contact WHERE accountId IN: opportunityAccountMap.keySet()]) {
		List<Id> contactIds = new List<Id>();
		if(mapOpportunityContact.containsKey(opportunityAccountMap.get(cont.AccountId))) {
			contactIds = mapOpportunityContact.get(opportunityAccountMap.get(cont.AccountId));
		}
		contactIds.add(cont.Id);
		mapOpportunityContact.put(opportunityAccountMap.get(cont.AccountId), contactIds);
	}
	
	
	// get contacts from opportunity contact role. 
	for(OpportunityContactRole contRole: [SELECT Id, OpportunityId, ContactId FROM OpportunityContactRole 
											WHERE OpportunityId IN: opportunityAccountMap.values()]) {
		List<Id> oppContactIds = new List<Id>();
		if(mapOpportunityContactRole.containsKey(contRole.OpportunityId)) {
			oppContactIds = mapOpportunityContactRole.get(contRole.OpportunityId);
		}
		oppContactIds.add(contRole.ContactId);
		mapOpportunityContactRole.put(contRole.OpportunityId, oppContactIds);
	}
	
	
	for(Id oppId : mapOpportunityContact.keySet()) {		
		// opp account contacts
		List<Id> contactRoles = new List<Id>();
        if(mapOpportunityContactRole.containsKey(oppId)) {
            contactRoles = mapOpportunityContactRole.get(oppId);
        }
		
		for(Id contId :  mapOpportunityContact.get(oppId)){
			if(!contactRoles.contains(contId)){
				OpportunityContactRole myContactRole = new OpportunityContactRole();
				myContactRole.ContactId = contId;
				myContactRole.OpportunityId = oppId;
				newContactRoleList.add(myContactRole);
			}
		}		
	}
    
    try {
        if(newContactRoleList.size()>0) {
            insert newContactRoleList;
        }
    }

    catch(Exception e) {
        System.debug(e);
    }
}

Kinldy review my code and let me know what condition I need to change to check and create contact role.

Thanks in advance. 
Hi Friends,

I have a requirement where I need to create a Quote and QuoteLineItem when OpportunityLineItem is created.

I have created a trigger on Opportunitylineitem and it is working fine but I am facing an issue that more number of Quotes is getting created based on Opportunitylineitems.
For Eg: I have 3 products in Opplineitem. I need to create 1 Quote with 3 QuoteLineitem. But it is creating 3 Quotes. However, Quotelineitem is creating correctly.

Below is my trigger
trigger quoteCreation on OpportunityLineItem (after insert) {
    System.debug('--- Inside Oppslineitem Trigger ---');

    List<Quote> quoteList = new List<Quote>();
    Set<ID> oppIds = new Set<ID>();

    for(OpportunityLineItem oppli : Trigger.New){
        oppIds.add(oppli.Id);
        System.debug('--- Opportunity Id: ---' + oppli.OpportunityId);
    }
    
    List<OpportunityLineItem> opplList = [SELECT Id, Opportunity.Name, Opportunity.AccountId, Opportunity.Account.PersonContactId, OpportunityId, Opportunity.Account.Name, Opportunity.Account.PersonEmail,
                                                 Opportunity.Account.Salutation, Opportunity.Account.BillingCity, Opportunity.Account.BillingCountry, Opportunity.Account.BillingPostalCode, Opportunity.Account.BillingState,
                                                 Opportunity.Account.ShippingCity, Opportunity.Account.ShippingCountry, Opportunity.Account.ShippingPostalCode, Opportunity.Account.ShippingState,
                                                 Opportunity.Account.BillingStreet, Opportunity.Account.ShippingStreet
                                            FROM OpportunityLineItem 
                                            WHERE Id IN:oppIds];
    
    for(OpportunityLineItem oppli : opplList) {
        System.debug('--- Inside Opportunity Loop ---' + opplList.size());
        
        //Create Quote        
        Quote quo = new Quote();
        quo.Name = oppli.Opportunity.Name + '-' + 'Quote';
        quo.Status = 'Draft';
        quo.OpportunityId = oppli.OpportunityId;
        quo.ContactId = oppli.Opportunity.Account.PersonContactId;
        quo.Email = oppli.Opportunity.Account.PersonEmail;
        quo.BillingName = oppli.Opportunity.Account.Salutation + ' ' + oppli.Opportunity.Account.Name;
        quo.ShippingName = oppli.Opportunity.Account.Salutation + ' ' + oppli.Opportunity.Account.Name;
        quo.BillingStreet = oppli.Opportunity.Account.BillingStreet; 
        quo.BillingCity = oppli.Opportunity.Account.BillingCity;
        quo.BillingCountry = oppli.Opportunity.Account.BillingCountry;
        quo.BillingPostalCode = oppli.Opportunity.Account.BillingPostalCode;
        quo.BillingState = oppli.Opportunity.Account.BillingState;
        quo.ShippingStreet = oppli.Opportunity.Account.ShippingStreet;        
        quo.ShippingCity = oppli.Opportunity.Account.ShippingCity;
        quo.ShippingCountry = oppli.Opportunity.Account.ShippingCountry;
        quo.ShippingPostalCode = oppli.Opportunity.Account.ShippingPostalCode;
        quo.ShippingState = oppli.Opportunity.Account.ShippingState;
        quoteList.add(quo);
    }
        
    try {        
        if(quoteList.size() > 0) {    
            insert quoteList;
        }
        System.debug('--- Inserted Order List: ---' + quoteList.size()); 
    }
    catch(Exception e) {
        System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
    }
    
    // Insert Quote Line Item 
    set<Id> oppId = new Set<Id>();
    set<Id> pcrId = new set<Id>(); 
    List<QuoteLineItem> oliPist = new  List<QuoteLineItem>();
    
    for(Quote quo : quoteList) {
        System.debug('--- Inside Quote Loop ---' + quo);
        if(quo.opportunityId != null) {
            oppId.add(quo.opportunityId);
        }
    }
    
    Map<Id, List<OpportunityLineItem>> olitoOpp = new  Map<Id, List<OpportunityLineItem>>();
    
    for(OpportunityLineItem oli : [SELECT Id, Quantity, UnitPrice, PricebookEntryId, Product2Id, OpportunityId 
                                          FROM OpportunityLineItem WHERE opportunityId IN : oppId]) {
        pcrId.add(oli.Product2Id);
        if(olitoOpp.containsKey(oli.opportunityId)) {
            olitoOpp.get(oli.opportunityId).add(oli);
        }
        else {
            olitoOpp.put(oli.opportunityId, new List<OpportunityLineItem> {oli});
        }
    }
    
    for(Quote quot : quoteList) {
        if(olitoOpp.containsKey(quot.opportunityId)) {
            for(OpportunityLineItem  oli : olitoOpp.get(quot.opportunityId)){
    
                QuoteLineItem od = new QuoteLineItem();
                od.QuoteId = quot.Id;
                od.Quantity = oli.Quantity;
                od.PricebookEntryId = oli.PricebookEntryId;
                od.UnitPrice = oli.UnitPrice;
                od.Product2Id = oli.Product2Id;
                oliPist.add(od);
            }
        }
    }
    
    if(!oliPist.isEmpty()) {
        insert oliPist;
    }
            
}

Kindly review my code and let me know what I need to change.

Thanks in advance.
Hello Friends,

I have completed trigger on Quote (after Update). When Quote Status is updated as Approved. Order is created.
This is working fine. But when I update the quote any field Order is getting created again and again.

Below is my trigger. Kindly check and let me know what to change. 
trigger createOrderOnQuote on Quote (after update) {
        
    // Create Order once Quote is Approved.
    if(Trigger.isafter & Trigger.isupdate) {
        Set<Id> quoteIds = new Set<Id>();
        List<Order> orderList = new List<Order>();
        
        for(Quote q : Trigger.New) {
            quoteIds.add(q.Id);
            System.debug('--- Picking Quote Id ---' + quoteIds);
        }
        
        List<Quote> quoteList = [SELECT Id, Name, Status, OpportunityId, Email, AccountId, ContactId, BillingCountry, BillingPostalCode, BillingState, BillingCity, BillingStreet, 
                                        ShippingCountry, ShippingCity, ShippingPostalCode, ShippingState, ShippingStreet, BillingName, QuoteNumber, TotalPrice, ShippingName
                                   FROM Quote 
                                   WHERE Id =: quoteIds];
        
        // Create Order when Quote Approved.
        for(Quote q : quoteList){
            system.debug('--- Quote List ---' + quoteList);
            if(q.Status == 'Approved') {
                System.debug('--- Quote Status ---' + q.Status);
                
                Order o = new Order();
                o.EffectiveDate = system.today();
                o.Status = 'Draft';
                o.AccountId = q.AccountId;
                o.OpportunityId = q.OpportunityId;
                o.QuoteId = q.Id;
                o.Bill_To_Name__c = q.BillingName;
                o.BillingStreet = q.BillingStreet;
                o.BillingCountry = q.BillingCountry;
                o.BillingState = q.BillingState;
                o.BillingCity = q.BillingCity;
                o.BillingPostalCode = q.BillingPostalCode;
                o.Ship_To_Name__c = q.ShippingName;
                o.ShippingStreet = q.ShippingStreet;
                o.ShippingCountry = q.ShippingCountry;
                o.ShippingState = q.ShippingState;
                o.ShippingCity = q.ShippingCity;
                o.ShippingPostalCode = q.ShippingPostalCode;
                orderList.add(o);
            }
            System.debug('--- Order List Size ---' + orderList.size());
        }
            
        try {
            if(orderList.size() > 0) {    
                insert orderList;
            }
            System.debug('--- Inserted Order List: ---' + orderList.size()); 
        }
        catch(Exception e) {
            System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
        }
    }   
}
Thanks in Advance..
 
Hi Friends,

I have 4 checkboxes in Parent Object and saved a record. Then, I need to display only selected check box sections in child object which is related lists.

Need help in visualforce page code how can I display the values.

Kindly let me know how can I achieve this requirement.

Thanks.
Hi Friends,

I have a requirement when I need to create records based on dates with incrementl due dates.

I have a custom obj with start date and end date fields. After saving the record I want to create a records in Child Object with due date as incremental dates.

Eg: My Start Date is 05-03-2020 and End Date is 10-03-2020.
Date Difference is 6 days. I will create 6 records with different due dates with next date 
1st record Due Date - 06-03-2020. 2nd Record Due Date - 07-03-2020.

Below is the code for creating dates but I could not able to do incremental due dates.
 
Trigger:

rigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();
      
    for(Study_Plan__c sp : Trigger.New)
    {
        Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c);
        System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
        System.debug('--- Day Count ---' + daycount);
        
        for(integer i=0; i<=daycount; i++)
        {
            Daily_Practice__c dps = new Daily_Practice__c();
            dps.Due_Date__c = sp.Phase_Start_Date__c + 1; // I have given currently as stratdate + 1.
            dps.StudyPlan__c = sp.Id;
            dps.Status__c = 'Assigned';
            dplist.add(dps);
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}



Need your assistance to complete.

Thanks.
 
Hi Friends,

I need assistance in working on Trigger. I have a requirement, where I need to insert contact when Checkbox is clicked in account.

Eg: I have 3 checkboxes Electronics, Fashion, Furnitures. If I select 2 checkboxes Electronics and Fashion and save the Account. Then, I need to insert 2 contacts with field selected as Electronics and field selected as Fashion in another record.

I need assistance in this requirement.

Thanks.
Hi Friends,

I have a requirement, where I need to insert child records based on date difference.

Below details:
After insert trigger on Order to insert a child custom object based on start date and end date difference.
For Eg: Start Date = 28/02/2020 and End Date = 28/03/2020.
Difference is 29 days and I want to create 29 child records.

How can I start writing the trigger. Kindly give your suggestions.

Thanks in Advance.
Hi Friends,

I am learning Integration and I need some clarification for the below question.
Scenario:
I have 3 methods in REST Api class,
@HttpGet
@HttpPost
@HttpPut
I have all the methods in single class.

Question:
Whether I can use each method in each class.
Like, @HttpGet in one class and @HttpPost in one class..
So that If I want to make any changes to particulat method only that class and corresponding test class is modified.

Kinldly need some inputs for my understanding.

Thanks.
Hi Experts,

I need to update accountnumber in account using rest services.
Need your help on code snippet to update.
I tried the below code but getting error when trying to update.
Error 
System.QueryException: List has no rows for assignment to SObject Class.RESTClass.updateAccount: line 7, column 1
 
@HttpPatch 
    global static String updateAccount(string accnumber){
        String accid1 = RestContext.request.params.get('id');
        Account acc = [select accountnumber from account where id =: accid1];
        acc.accountnumber = accnumber;
        update acc;
        return 'account updated';
    }

Let me know what I need to change to make this work.

Thanks
Hi Friends,
I need help in getting record values from lead object for below class.
I am getting blank values when testing.
 
Class ::

public with sharing class helperleadTrigger {
    
    public static List<Lead> sendEmail(List<Lead> leads){
        Leads = [SELECT Id, Name, FirstName, LastName, Email, Business_Hub__c, Title__c FROM Lead WHERE Id =: recordId];
        for(Lead l : leads){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[]{'test@gmail.com'};
            mail.setToAddresses(toAddresses);
            mail.setTargetObjectId(l.Id);
            mail.setTemplateId('00X5D000000EmxQ');
            mail.saveAsActivity = false;
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            //Set email file attachments
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [select Id, Name, Body, ContentType, BodyLength from Attachment where ParentId =: l.Id]) {
             // Add to attachment file list
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                efa.setContentType(a.ContentType);
                fileAttachments.add(efa);
            }
            mail.setFileAttachments(fileAttachments);
        }
        return leads;
    }

Thanks in advance.
Hi Friends,

I need help in fixing the VF Pages. 
I created a Class and VF Pages where I want to display a Table values. so, I created a Pageblocktable. Now I have 1 issue when I table has values and other table does not have a values it is diplaying both table which looks awkward.
I need to hide the columns if there is no values.

Below is my VF code and Image for your reference.
<apex:panelGrid columns="3" width="90%">
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList1}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Body" >
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
                            </apex:column>
                        </apex:pageBlockTable>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageblock>
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList2}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Fridge">
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
                            </apex:column>
                        </apex:pageBlockTable>
                   </apex:column>
                </apex:pageBlockTable>
            </apex:pageblock>
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList3}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Tail Lift" >
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
                            </apex:column>
                        </apex:pageBlockTable> 
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageblock>
        </apex:panelGrid> <br/>
Pageblock Table VIew

Kindly advice how can solve this issue.

Thanks. 
Hi Friends,

I want to update the attachments name with versions.
I have a pdf templates to attach in account object. When I update the record and click on PDF template it is again inserting with same name. I want to insert with same name with some versioning like testv1, samplev1.
How can I do this. I have class to attach the template in account. Whether I can modify the class or trigger is required.

Kindly need inputs to achieve this requirement.

Thanks. 
Hi Friends,

I have created a custom controller and a vf page and when I run the vf page I am getting List has no Rows error.

Kindly needed your help to resolve this issue.

Below is my class and VF code.
 
Apex Class:

public class quoteController {

    private final SBQQ__Quote__c quotePDF;
    private final SBQQ__Quote__c quoteOpp;
    private final SBQQ__Quote__c quoteProd;

    public quoteController() {
        // Query for QuoteLineItem
        quotePDF = [SELECT Id, SBQQ__Account__r.Name, SBQQ__BillingCity__c, SBQQ__BillingName__c, SBQQ__ShippingCity__c, SBQQ__ShippingName__c, 
                           (Select Id, SBQQ__ProductName__c, SBQQ__Quantity__c, SBQQ__Description__c, SBQQ__ListPrice__c, SBQQ__NetTotal__c from SBQQ__LineItems__r) 
                      FROM SBQQ__Quote__c
                      WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    
        // Query for Quote Opportunity
        quoteOpp = [SELECT Id, SBQQ__Opportunity2__r.Vehicle_Make__c, SBQQ__Opportunity2__r.Rego_Fleet_Number__c, SBQQ__Opportunity2__r.Vin_Number__c, SBQQ__Opportunity2__r.Odometer__c, 
                           SBQQ__Opportunity2__r.Vehicle_Model__c
                      FROM SBQQ__Quote__c
                      WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
                      
        // Query for Quote Product
        quoteProd = [SELECT Id, (Select Id, SBQQ__Product__r.Refrigeration_Gas__c
                               from SBQQ__LineItems__r)
                       FROM SBQQ__Quote__c
                       WHERE Id = :ApexPages.currentPage().getParameters().get('id')];    

    }

    public SBQQ__Quote__c getquotePDF(){
        return quotePDF; 
    }
    
    public SBQQ__Quote__c getquoteOpp(){
        return quoteOpp;
    }
    
    public SBQQ__Quote__c getquoteProd(){
        return quoteProd;
    }
}
 
VF Page:

<apex:page controller="quoteController" tabStyle="SBQQ__Quote__c" showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false">
    <html>               
        <body> 
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="95%" value="{!quotePDF}" var="myOrder">                    
                <apex:column value="{!myOrder.SBQQ__Account__r.Name}" />        
                <apex:column value="{!myOrder.SBQQ__BillingCity__c}" />        
                <apex:column value="{!myOrder.SBQQ__BillingName__c}" />
                <apex:column headerValue="QTY">
                    <apex:outputText value=" " />
                </apex:column>
                <apex:column value="{!myOrder.SBQQ__ShippingCity__c}" />        
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
        
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="95%" value="{!quoteOpp}" var="quoteOpp">                    
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Vehicle_Make__c}" />        
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Rego_Fleet_Number__c }" />        
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Vin_Number__c }" />
                <apex:column headerValue="QTY">
                    <apex:outputText value="{!quoteOpp.SBQQ__Opportunity2__r.Odometer__c}" />
                </apex:column>
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Vehicle_Model__c}" />
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
        
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="100%" value="{!quotePDF.SBQQ__LineItems__r}" var="OrderItems" >
                <apex:column headerValue="Product Name">
                    <apex:outputField value="{!OrderItems.SBQQ__ProductName__c}"/>
                </apex:column>
                <apex:column headerValue="PartNumber">
                    <apex:outputField value="{!OrderItems.SBQQ__Quantity__c}"/>
                </apex:column>
                <apex:column headerValue="Item Type">
                    <apex:outputField value="{!OrderItems.SBQQ__Description__c}"/>
                </apex:column>
                <apex:column headerValue="Option Type">
                    <apex:outputText value="{!OrderItems.SBQQ__ListPrice__c}"/>
                </apex:column>
                <apex:column headerValue="Value">
                    <apex:outputField value="{!OrderItems.SBQQ__NetTotal__c}"/>
                </apex:column>                                                                              
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
        
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="100%" value="{!quoteProd.SBQQ__LineItems__r}" var="prod" >
                <apex:column headerValue="Refrigeration Gas">
                    <apex:outputField value="{!prod.SBQQ__Product__r.Refrigeration_Gas__c}"/>
                </apex:column>
                                -->                                            
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
           
        </body>
    </html>    
</apex:page>

Thanks in Advance.
Hi Experts,
I have a requirement to add Multiple visualforce pages to combine as single page. This Visualforce pages are render as PDF. 
I want to create a new page like wizard where I need to display some vf pages and provide users to select the page and save. Once saved I need to attach them to record.

Kindly need inputs how can I approach.

Thanks.
Hi Experts,

Help needed to solve the below error in trigger. 

execution of AfterInsert caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): Trigger.insertOppsLineitem: line 31, column 1
 
trigger insertOppsLineitem on OrderItems__c (after insert, after update) {
    System.debug('--- Inside orderItems Trigger ---');

    Set<String> orderIds = new Set<String>();
    List<Opportunitylineitem> oliinsertList = new List<Opportunitylineitem>();
    List<Opportunitylineitem> oliupdateList = new List<Opportunitylineitem>();
    
    for(OrderItems__c oi : Trigger.new) {
        orderIds.add(oi.Name);
        orderIds.add(oi.Product_Id__c);
        System.debug('--- OrderItems Id: ---' + oi.Name);                
        System.debug('--- Product Name: ---' + oi.Product_Id__c);        
    }

    Map<String, List<Opportunity>> oppMap = new Map<String, List<Opportunity>>();
    
    List<Opportunitylineitem> oppliList = new List<Opportunitylineitem>();
    oppliList = [SELECT Id, OpportunityId, Name__c, Name, product_id__c FROM Opportunitylineitem WHERE product_id__c IN: orderIds];
    
    Map<String, List<pricebookentry>> pricebookMap = new Map<String, List<pricebookentry>>();
    
//Error below query:::
    List<Pricebookentry> pbeList = new List<Pricebookentry>();
    pbeList = [SELECT Id, Name, Pricebook2Id, Pricebook2.Name, Product2Id, IsActive, Product2.entity_id__c
                  FROM Pricebookentry 
                  WHERE IsActive = true AND Pricebook2.Name = 'Standard Price Book' AND Product2.entity_id__c IN: orderIds];
    
    if(!orderIds.isEmpty()) {
        for(Opportunity opps : [SELECT Id, Name FROM Opportunity WHERE Name IN: orderIds]){
            if(!oppMap.containsKey(opps.Name)){
                oppMap.put(opps.Name, new List<Opportunity> {opps});
                System.debug('--- Inside OppMap ---' + oppMap);
            }
            else{
                List<Opportunity> oppList = oppMap.get(opps.Name);
                oppList.add(opps);
                oppMap.put(opps.Name, oppList);
                System.debug('--- Else oppMap ---' + oppList);
            }
        }
        
        for(Pricebookentry pbe : pbeList) {
            if(!pricebookMap.containsKey(pbe.Product2.entity_id__c)) {
                pricebookMap.put(pbe.Product2.entity_id__c, new List<Pricebookentry> {pbe});
            }
            else {
                List<Pricebookentry> pbeList = pricebookMap.get(pbe.Product2.entity_id__c);
                pbeList.add(pbe);
                pricebookMap.put(pbe.Product2.entity_id__c, pbeList);
            }
        }
    }
    
    Pricebookentry pbe = [SELECT Id, Name, isActive FROM Pricebookentry WHERE isActive = true AND Name = 'Zookal Product' Limit 1];
    
    // Insert Opportunity Products.
    if(Trigger.isInsert && Trigger.isAfter) {
        for(OrderItems__c oi : Trigger.New) {
            System.debug('--- Name of Order Items: ---' + oppMap);
            if(oppMap.containsKey(oi.Name)) {
                
                //Inserting into Opportunity with Opportunity Name.
                for(Opportunity opp : oppMap.get(oi.Name)) {
                    System.debug('--- Name of Order Items: ---' + oppMap.get(oi.Name));
                    if(pricebookMap.containsKey(oi.Product_Id__c)) {
                    
                        //Getting the Pricebookentry Name and Inserting Opportunity Lineitem.
                        for(Pricebookentry pe : pricebookMap.get(oi.Product_Id__c)) {
                            System.debug('--- Name of Order Items: ---' + pricebookMap.get(oi.Product_Id__c));
                            Opportunitylineitem oli = new Opportunitylineitem ();
                            oli.OpportunityId = opp.Id;
                            oli.PricebookEntryId = pe.Id;
                            oli.Quantity = 1;
                            oli.TotalPrice = oi.Price__c;                
                            oli.item_id__c = oi.item_id__c;
                            oli.Name__c = oi.Name__c;
                            oli.product_id__c = oi.product_id__c;
                            oli.Due_Date__c = oi.Due_Date__c;
                            oli.product_type__c = oi.product_type__c;
                            oli.qty_backordered__c = oi.qty_backordered__c;
                            oli.qty_canceled__c = oi.qty_canceled__c;
                            oli.qty_invoiced__c = oi.qty_invoiced__c;
                            oli.qty_ordered__c = oi.qty_ordered__c;
                            oli.qty_refunded__c = oi.qty_refunded__c;
                            oli.qty_returned__c = oi.qty_returned__c;
                            oli.qty_shipped__c = oi.qty_shipped__c;
                            oli.Discount_Amount__c = oi.Discount_Amount__c;
                            oli.Sku__c = oi.Sku__c;
                            oliinsertList.add(oli);
                        }
                    }
                    else {
                        Opportunitylineitem oli = new Opportunitylineitem ();
                        oli.OpportunityId = opp.Id;
                        oli.PricebookEntryId = pbe.Id;
                        oli.Quantity = 1;
                        oli.TotalPrice = oi.Price__c;                
                        oli.item_id__c = oi.item_id__c;
                        oli.Name__c = oi.Name__c;
                        oli.product_id__c = oi.product_id__c;
                        oli.Due_Date__c = oi.Due_Date__c;
                        oli.product_type__c = oi.product_type__c;
                        oli.qty_backordered__c = oi.qty_backordered__c;
                        oli.qty_canceled__c = oi.qty_canceled__c;
                        oli.qty_invoiced__c = oi.qty_invoiced__c;
                        oli.qty_ordered__c = oi.qty_ordered__c;
                        oli.qty_refunded__c = oi.qty_refunded__c;
                        oli.qty_returned__c = oi.qty_returned__c;
                        oli.qty_shipped__c = oi.qty_shipped__c;
                        oli.Discount_Amount__c = oi.Discount_Amount__c;
                        oli.Sku__c = oi.Sku__c;
                        oliinsertList.add(oli);
                    }
                }
            }
        }
    }

    // Update Opportunity Lineitem Method.
    if(Trigger.isUpdate) {
        List<Opportunitylineitem> oliLists = new List<Opportunitylineitem>();
        Set<String> oliIds = new Set<String>();
        Map<String, List<Opportunitylineitem>> oppliMap = new Map<String, List<Opportunitylineitem>>();
        
        for(OrderItems__c oi : Trigger.New) {
            oliIds.add(oi.Name__c);
            System.debug('--- Order Ids ---' + oi.Name__c);
        }
        
        oliLists = [SELECT Id, Name, Name__c FROM Opportunitylineitem WHERE Name__c IN: oliIds];
        System.debug('--- oliLists ---' + oliLists.size());
        
        for(OrderItems__c oi : Trigger.New) {
            for(Opportunitylineitem olits : oppliList) {                   
                olits.Quantity = 1;
                olits.TotalPrice = oi.Price__c;
                olits.item_id__c = oi.item_id__c;
                olits.Name__c = oi.Name__c;
                olits.product_id__c = oi.product_id__c;
                olits.Due_Date__c = oi.Due_Date__c;
                olits.product_type__c = oi.product_type__c;
                olits.qty_backordered__c = oi.qty_backordered__c;
                olits.qty_canceled__c = oi.qty_canceled__c;
                olits.qty_invoiced__c = oi.qty_invoiced__c;
                olits.qty_ordered__c = oi.qty_ordered__c;
                olits.qty_refunded__c = oi.qty_refunded__c;
                olits.qty_returned__c = oi.qty_returned__c;
                olits.qty_shipped__c = oi.qty_shipped__c;
                olits.Discount_Amount__c = oi.Discount_Amount__c;
                olits.Sku__c = oi.Sku__c;
                oliupdateList.add(olits);
            }
        }    
    }
    
    //Insert and Update Methods.    
    try {
        if(oliinsertList.size() > 0) {    
            insert oliinsertList;
        }
        if(oliupdateList.size() > 0) {
            update oliupdateList;
        }
        System.debug('--- Inserted Opportunitylineitem List: ---' + oliinsertList.size());
        System.debug('--- Updated Opportunitylineitem List: ---' + oliupdateList.size());
    }
    catch (Exception e) {
        System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
    }
}

Thanks in Advance
Hi,
I have a the requirement: I need to create a Custom Object with a relationship to Contact. I need to create 5 checkbox in Contacts and same in custom object. Now when I enter the values in the checkboxes in contact I need to insert a new record in custom object with the checkbox values. After inserting the record in cusgom object I need to make the contact checkbox to unselsect if 2 checkbox is selected. How can I do this. I am done with insert and update trigger. Below is my Trigger for reference. Please give me your suggestions.

trigger projInsert on Contact (after insert, after update) {
    System.debug('---- Inside Contact :----');
    
    if(trigger.isInsert) {
        List<Project__c> projList = new List<Project__c>();
        for(Contact con : Trigger.new) {
            System.debug('---- Inside For Loop : ----');    
            if (con.LastName != '' && con.LastName != null) {
                System.debug('---- Inside IF Loop : ----');    
                Project__c proj = new Project__c();
                proj.Contact__c = con.id;
                proj.Feature_1__c = con.Feature_1__c;
                proj.Feature_2__c = con.Feature_2__c;
                if(con.Product_A__c == true) {
                    proj.Products__c = 'Product A';
                }
                else if (con.Product_B__c == true) {
                    proj.Products__c = 'Product B';
                }
                else {
                    proj.Products__c = '';
                }
                projList.add(proj);
            }
            System.debug('---- Proj List ----');
            System.debug('---- Proj List After If : ----'+projList);   
        }
        
        if(projList.size() > 0) {
            insert projList;
        }
        System.debug('---- Proj List : ----');
        System.debug('---- Proj List Size : ----' +projList.size());
    }
       
    if(trigger.isUpdate) {
        Map <Id, Contact> mapContact = new Map <Id, Contact>();
        List<Project__c> listProject = new List<Project__c>();
        
        for(Contact cont : trigger.new)
            mapContact.put(cont.Id, cont);
        
        listProject = [SELECT id, Contact__c, Feature_1__c, Feature_2__c, Products__c
                         FROM Project__c 
                         WHERE Contact__c IN : mapContact.keySet()];
        
        if (listProject.size() > 0) {
            for (Project__c pro : listProject) {
                pro.Feature_1__c = mapContact.get(pro.Contact__c).Feature_1__c;
                pro.Feature_2__c = mapContact.get(pro.Contact__c).Feature_2__c;
            }
            update listProject;
        }
    }        
}

Thanks
Hi Experts,

I have the below requirement and I need to know how can I proceed.
I have a custom field in Account Obj as Status "Active and Inactive" which is a picklist.
When an account is Inactive, I should not allow the user to edit the record. But I need to allow them to enter or edit Tasks, Events, Relatedlists on that record.

I have created the Validation Rule but it is not allowing any changes on the account when Inactive.

Kindly need your inputs to complete.

Thanks in Advance.
Hi Friends,

I have a requirement when I need to insert Opportunity Contact Role when Opportunity is created.
My code is working fine when creating a Opportunity from Contact but a duplicate is getting created when Converting a Opportunity from Lead.
 
trigger updateContactRole on Opportunity (after insert, after update) {
    
    System.debug('-- Inside Opportunity Contact Role Trigger---');
    
    List<OpportunityContactRole> newContactRoleList = new List<OpportunityContactRole>();
    Map<Id, Id> opportunityAccountMap = new Map<Id, Id>();
	Map<Id, List<Id>> mapOpportunityContact = new Map<Id, List<Id>>();
	Map<Id, List<Id>> mapOpportunityContactRole = new Map<Id, List<Id>>();
	
	for(Opportunity opp : trigger.new) {
		if(opp.AccountId != null) {
			opportunityAccountMap.put(opp.AccountId, opp.Id);
		}
	}
	
	// get contacts from opportunity account 
	for(Contact cont: [SELECT Id, AccountId FROM Contact WHERE accountId IN: opportunityAccountMap.keySet()]) {
		List<Id> contactIds = new List<Id>();
		if(mapOpportunityContact.containsKey(opportunityAccountMap.get(cont.AccountId))) {
			contactIds = mapOpportunityContact.get(opportunityAccountMap.get(cont.AccountId));
		}
		contactIds.add(cont.Id);
		mapOpportunityContact.put(opportunityAccountMap.get(cont.AccountId), contactIds);
	}
	
	
	// get contacts from opportunity contact role. 
	for(OpportunityContactRole contRole: [SELECT Id, OpportunityId, ContactId FROM OpportunityContactRole 
											WHERE OpportunityId IN: opportunityAccountMap.values()]) {
		List<Id> oppContactIds = new List<Id>();
		if(mapOpportunityContactRole.containsKey(contRole.OpportunityId)) {
			oppContactIds = mapOpportunityContactRole.get(contRole.OpportunityId);
		}
		oppContactIds.add(contRole.ContactId);
		mapOpportunityContactRole.put(contRole.OpportunityId, oppContactIds);
	}
	
	
	for(Id oppId : mapOpportunityContact.keySet()) {		
		// opp account contacts
		List<Id> contactRoles = new List<Id>();
        if(mapOpportunityContactRole.containsKey(oppId)) {
            contactRoles = mapOpportunityContactRole.get(oppId);
        }
		
		for(Id contId :  mapOpportunityContact.get(oppId)){
			if(!contactRoles.contains(contId)){
				OpportunityContactRole myContactRole = new OpportunityContactRole();
				myContactRole.ContactId = contId;
				myContactRole.OpportunityId = oppId;
                                myContactRole.isPrimary = true;
				newContactRoleList.add(myContactRole);
			}
		}		
	}
    
    try {
        if(newContactRoleList.size()>0) {
            insert newContactRoleList;
        }
    }

    catch(Exception e) {
        System.debug(e);
    }
}

Kindly refer the code and let me know how can I solve this issue.

Thanks in advance..
Hi Friends,

I have a requirement where I need to create a Quote when a Opportunity Product is added.
When creating a Quote I need to copy contact details based on Opportunity Contact Role where Contact is Primary.
I am getting Contact Name but, got Stuck in getting a Contact Email, Contact MailingAddress and Contact Other Address. It is not getting populated in Quote.
 
/** Trigger on Opportunity Line Item to insert Quote and Quotelineitem **/
trigger quoteCreation on OpportunityLineItem (after insert) {
    if(Trigger.isAfter && Trigger.isInsert){
        List<Quote> quoteList = new List<Quote>();
        Set<ID> oppIds = new Set<ID>();
        Set<Id> processIds = new Set<ID>();
        
        for(OpportunityLineItem oppli : Trigger.New){
            oppIds.add(oppli.Id);
        }
        
        List<OpportunityLineItem> opplList = new List<OpportunityLineItem>();
        if(oppIds != null && oppIds.size() >0){
            opplList = [SELECT Id, Opportunity.Name, Opportunity.AccountId, Opportunity.Account.PersonContactId, OpportunityId, Opportunity.Account.Name, Opportunity.Account.PersonEmail,
                        Opportunity.Account.Salutation, Opportunity.Account.BillingCity, Opportunity.Account.BillingCountry, Opportunity.Account.BillingPostalCode, Opportunity.Account.BillingState,
                        Opportunity.Account.ShippingCity, Opportunity.Account.ShippingCountry, Opportunity.Account.ShippingPostalCode, Opportunity.Account.ShippingState,
                        Opportunity.Account.BillingStreet, Opportunity.Account.ShippingStreet, Opportunity.ContactId, Opportunity.Account.isPersonAccount
                        FROM OpportunityLineItem 
                        WHERE Id IN:oppIds];
        }
        if(opplList != null && opplList.size() >0 ){
            for(OpportunityLineItem oppli : opplList) {        
                Quote quo = new Quote();
                quo.Name = 'Quote - ' + oppli.Opportunity.Name;
                quo.Status = 'Draft';
                quo.OpportunityId = oppli.OpportunityId;
               // Getting Contact Details from Business Account.
                if(oppli.Opportunity.Account.isPersonAccount == False)
                {
                    quo.ContactId = oppli.Opportunity.ContactId;
                    quo.Email = oppli.Opportunity.Contact.Email;
                    /*
                          Need to get Contact Mailing Address and Other Address.
                    */
                }

               // Getting Contact Details from Person Account.
                else
                {
                    quo.ContactId = oppli.Opportunity.Account.PersonContactId;
                    quo.Email = oppli.Opportunity.Account.PersonEmail;
                    quo.BillingName = oppli.Opportunity.Account.Name;
                    quo.ShippingName = oppli.Opportunity.Account.Name;
                    quo.BillingStreet = oppli.Opportunity.Account.BillingStreet; 
                    quo.BillingCity = oppli.Opportunity.Account.BillingCity;
                    quo.BillingCountry = oppli.Opportunity.Account.BillingCountry;
                    quo.BillingPostalCode = oppli.Opportunity.Account.BillingPostalCode;
                    quo.BillingState = oppli.Opportunity.Account.BillingState;
                    quo.ShippingStreet = oppli.Opportunity.Account.ShippingStreet;        
                    quo.ShippingCity = oppli.Opportunity.Account.ShippingCity;
                    quo.ShippingCountry = oppli.Opportunity.Account.ShippingCountry;
                    quo.ShippingPostalCode = oppli.Opportunity.Account.ShippingPostalCode;
                    quo.ShippingState = oppli.Opportunity.Account.ShippingState;
                }
               
                if(!processIds.contains(quo.OpportunityId))
                {
                    quoteList.add(quo);
                    processIds.add(quo.OpportunityID);
                }
            }
        }
        
        try {        
            if(quoteList.size() > 0) {    
                insert quoteList;
            }
        }
        catch(Exception e) {
            System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
        }
        // Insert Quote Line Item 
        set<Id> oppId = new Set<Id>();
        set<Id> pcrId = new set<Id>(); 
        List<QuoteLineItem> oliPist = new  List<QuoteLineItem>();
        if(quoteList != null && quoteList.size() >0){
            for(Quote quo : quoteList) {
                if(quo.opportunityId != null) {
                    oppId.add(quo.opportunityId);
                }
            }
        }
        Map<Id, List<OpportunityLineItem>> olitoOpp = new  Map<Id, List<OpportunityLineItem>>();
        if(oppId != null && oppId.size() >0){
            for(OpportunityLineItem oli : [SELECT Id, Quantity, UnitPrice, PricebookEntryId, Product2Id, OpportunityId 
                                           FROM OpportunityLineItem WHERE opportunityId IN : oppId]) {
                                               pcrId.add(oli.Product2Id);
                                               if(olitoOpp.containsKey(oli.opportunityId)) {
                                                   olitoOpp.get(oli.opportunityId).add(oli);
                                               }
                                               else {
                                                   olitoOpp.put(oli.opportunityId, new List<OpportunityLineItem> {oli});
                                               }
                                           }
        }
        
        for(Quote quot : quoteList) {
            if(olitoOpp.containsKey(quot.opportunityId)) {
                for(OpportunityLineItem  oli : olitoOpp.get(quot.opportunityId)){
                    if(oli != null)
                        oliPist.add(new QuoteLineItem(QuoteId=quot.Id,Quantity = oli.Quantity,PricebookEntryId = oli.PricebookEntryId,UnitPrice = oli.UnitPrice,Product2Id = oli.Product2Id));
                }
            }
        }
        if(!oliPist.isEmpty()) {
            insert oliPist;
        }
    }
}

Kindly review my code and let me know how can I get contact values.

Thanks in Advance.

 
Hi Friends,

I have a requirement when I need to create records based on dates with incrementl due dates.

I have a custom obj with start date and end date fields. After saving the record I want to create a records in Child Object with due date as incremental dates.

Eg: My Start Date is 05-03-2020 and End Date is 10-03-2020.
Date Difference is 6 days. I will create 6 records with different due dates with next date 
1st record Due Date - 06-03-2020. 2nd Record Due Date - 07-03-2020.

Below is the code for creating dates but I could not able to do incremental due dates.
 
Trigger:

rigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();
      
    for(Study_Plan__c sp : Trigger.New)
    {
        Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c);
        System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
        System.debug('--- Day Count ---' + daycount);
        
        for(integer i=0; i<=daycount; i++)
        {
            Daily_Practice__c dps = new Daily_Practice__c();
            dps.Due_Date__c = sp.Phase_Start_Date__c + 1; // I have given currently as stratdate + 1.
            dps.StudyPlan__c = sp.Id;
            dps.Status__c = 'Assigned';
            dplist.add(dps);
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}



Need your assistance to complete.

Thanks.
 
Hi Friends,

I need assistance in working on Trigger. I have a requirement, where I need to insert contact when Checkbox is clicked in account.

Eg: I have 3 checkboxes Electronics, Fashion, Furnitures. If I select 2 checkboxes Electronics and Fashion and save the Account. Then, I need to insert 2 contacts with field selected as Electronics and field selected as Fashion in another record.

I need assistance in this requirement.

Thanks.
Hi Friends,
I need help in getting record values from lead object for below class.
I am getting blank values when testing.
 
Class ::

public with sharing class helperleadTrigger {
    
    public static List<Lead> sendEmail(List<Lead> leads){
        Leads = [SELECT Id, Name, FirstName, LastName, Email, Business_Hub__c, Title__c FROM Lead WHERE Id =: recordId];
        for(Lead l : leads){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[]{'test@gmail.com'};
            mail.setToAddresses(toAddresses);
            mail.setTargetObjectId(l.Id);
            mail.setTemplateId('00X5D000000EmxQ');
            mail.saveAsActivity = false;
            
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            
            //Set email file attachments
            List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
            for (Attachment a : [select Id, Name, Body, ContentType, BodyLength from Attachment where ParentId =: l.Id]) {
             // Add to attachment file list
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(a.Name);
                efa.setBody(a.Body);
                efa.setContentType(a.ContentType);
                fileAttachments.add(efa);
            }
            mail.setFileAttachments(fileAttachments);
        }
        return leads;
    }

Thanks in advance.
Hi Friends,

I need help in fixing the VF Pages. 
I created a Class and VF Pages where I want to display a Table values. so, I created a Pageblocktable. Now I have 1 issue when I table has values and other table does not have a values it is diplaying both table which looks awkward.
I need to hide the columns if there is no values.

Below is my VF code and Image for your reference.
<apex:panelGrid columns="3" width="90%">
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList1}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Body" >
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
                            </apex:column>
                        </apex:pageBlockTable>
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageblock>
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList2}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Fridge">
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
                            </apex:column>
                        </apex:pageBlockTable>
                   </apex:column>
                </apex:pageBlockTable>
            </apex:pageblock>
            <apex:pageblock >
                <apex:pageBlockTable value="{!orderItemsList3}" width="100%" var="div">
                    <apex:column >
                        <apex:pageBlockTable width="100%" columns="1" border="1" cellspacing="0" cellPadding="1" value="{!div.OrderItems}" var="custom">
                            <apex:column headerValue="Tail Lift" >
                                <apex:outputField value="{!custom.Product2.Name}"/><p class="onepointfive"/>
                                Blue Plates Required:<apex:outputField value="{!custom.Product2.Blue_plates__c}"/><p class="onepointfive"/>
                                <apex:outputText value="Serial No:" /> <p class="onepointfive"/>
                                <apex:outputText value="Work Order #" />
                            </apex:column>
                        </apex:pageBlockTable> 
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageblock>
        </apex:panelGrid> <br/>
Pageblock Table VIew

Kindly advice how can solve this issue.

Thanks. 
Hi Friends,

I have created a custom controller and a vf page and when I run the vf page I am getting List has no Rows error.

Kindly needed your help to resolve this issue.

Below is my class and VF code.
 
Apex Class:

public class quoteController {

    private final SBQQ__Quote__c quotePDF;
    private final SBQQ__Quote__c quoteOpp;
    private final SBQQ__Quote__c quoteProd;

    public quoteController() {
        // Query for QuoteLineItem
        quotePDF = [SELECT Id, SBQQ__Account__r.Name, SBQQ__BillingCity__c, SBQQ__BillingName__c, SBQQ__ShippingCity__c, SBQQ__ShippingName__c, 
                           (Select Id, SBQQ__ProductName__c, SBQQ__Quantity__c, SBQQ__Description__c, SBQQ__ListPrice__c, SBQQ__NetTotal__c from SBQQ__LineItems__r) 
                      FROM SBQQ__Quote__c
                      WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
    
        // Query for Quote Opportunity
        quoteOpp = [SELECT Id, SBQQ__Opportunity2__r.Vehicle_Make__c, SBQQ__Opportunity2__r.Rego_Fleet_Number__c, SBQQ__Opportunity2__r.Vin_Number__c, SBQQ__Opportunity2__r.Odometer__c, 
                           SBQQ__Opportunity2__r.Vehicle_Model__c
                      FROM SBQQ__Quote__c
                      WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
                      
        // Query for Quote Product
        quoteProd = [SELECT Id, (Select Id, SBQQ__Product__r.Refrigeration_Gas__c
                               from SBQQ__LineItems__r)
                       FROM SBQQ__Quote__c
                       WHERE Id = :ApexPages.currentPage().getParameters().get('id')];    

    }

    public SBQQ__Quote__c getquotePDF(){
        return quotePDF; 
    }
    
    public SBQQ__Quote__c getquoteOpp(){
        return quoteOpp;
    }
    
    public SBQQ__Quote__c getquoteProd(){
        return quoteProd;
    }
}
 
VF Page:

<apex:page controller="quoteController" tabStyle="SBQQ__Quote__c" showHeader="false" sidebar="false" standardStylesheets="false" applyBodyTag="false" applyHtmlTag="false">
    <html>               
        <body> 
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="95%" value="{!quotePDF}" var="myOrder">                    
                <apex:column value="{!myOrder.SBQQ__Account__r.Name}" />        
                <apex:column value="{!myOrder.SBQQ__BillingCity__c}" />        
                <apex:column value="{!myOrder.SBQQ__BillingName__c}" />
                <apex:column headerValue="QTY">
                    <apex:outputText value=" " />
                </apex:column>
                <apex:column value="{!myOrder.SBQQ__ShippingCity__c}" />        
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
        
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="95%" value="{!quoteOpp}" var="quoteOpp">                    
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Vehicle_Make__c}" />        
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Rego_Fleet_Number__c }" />        
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Vin_Number__c }" />
                <apex:column headerValue="QTY">
                    <apex:outputText value="{!quoteOpp.SBQQ__Opportunity2__r.Odometer__c}" />
                </apex:column>
                <apex:column value="{!quoteOpp.SBQQ__Opportunity2__r.Vehicle_Model__c}" />
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
        
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="100%" value="{!quotePDF.SBQQ__LineItems__r}" var="OrderItems" >
                <apex:column headerValue="Product Name">
                    <apex:outputField value="{!OrderItems.SBQQ__ProductName__c}"/>
                </apex:column>
                <apex:column headerValue="PartNumber">
                    <apex:outputField value="{!OrderItems.SBQQ__Quantity__c}"/>
                </apex:column>
                <apex:column headerValue="Item Type">
                    <apex:outputField value="{!OrderItems.SBQQ__Description__c}"/>
                </apex:column>
                <apex:column headerValue="Option Type">
                    <apex:outputText value="{!OrderItems.SBQQ__ListPrice__c}"/>
                </apex:column>
                <apex:column headerValue="Value">
                    <apex:outputField value="{!OrderItems.SBQQ__NetTotal__c}"/>
                </apex:column>                                                                              
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
        
        <apex:pageBlock >
            <apex:pageBlockTable columns="5" border="1" cellspacing="0" cellPadding="5" width="100%" value="{!quoteProd.SBQQ__LineItems__r}" var="prod" >
                <apex:column headerValue="Refrigeration Gas">
                    <apex:outputField value="{!prod.SBQQ__Product__r.Refrigeration_Gas__c}"/>
                </apex:column>
                                -->                                            
            </apex:pageBlockTable>
        </apex:pageBlock> <p class="onepointfive"/>
           
        </body>
    </html>    
</apex:page>

Thanks in Advance.
Hi Experts,
I have a requirement to add Multiple visualforce pages to combine as single page. This Visualforce pages are render as PDF. 
I want to create a new page like wizard where I need to display some vf pages and provide users to select the page and save. Once saved I need to attach them to record.

Kindly need inputs how can I approach.

Thanks.
Hello Friends,

Need help in trigger test class code coverage. I am getting 53% code coverage.

Requirement: Checking Opportunity Line Item already exists in Opportunity. If exists display error.

Kindly check the code below and let me know what change need to be done.
Trigger:

trigger avoiddupOli on OpportunityLineItem (before insert) {
    System.debug('---Inside Oli Trigger---');
    Map<Id,List<Id>> mapProduct = new Map<Id,List<Id>>();
    Set<Id> setOppIds = new Set<Id>();
    for(OpportunityLineItem oli: Trigger.new){
        setOppIds.add(oli.OpportunityId);
        System.debug('--- Opportunity Id ---' + oli.OpportunityId);
    }
    for(OpportunityLineItem oli: [Select Id, Product2Id, OpportunityId from OpportunityLineItem where OpportunityId IN:setOppIds]){
        if(mapProduct.containsKey(oli.OpportunityId))
            mapProduct.get(oli.OpportunityId).add(oli.Product2Id);
        else
            mapProduct.put(oli.OpportunityId,new List<Id>{oli.Product2Id});
    }
    for(OpportunityLineItem oli: Trigger.new){
        if(mapProduct.containsKey(oli.OpportunityId)){
            for(Id prodId: mapProduct.get(oli.OpportunityId)){
                if(oli.Product2Id.equals(prodId))
                    oli.addError('Product already Exists');
                    System.debug('--- Product Error ---' + oli.Product2Id);
            }
        }
    }
}
 
Test Class:

@isTest(SeeAllData=true)
public class avoiddupOliTest {
    static testMethod void testUnit() {
        
        Pricebook2 standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
        
        Id RecordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
  
        Account acc = new Account(LastName = 'Account Test', recordtypeid = RecordTypeIdAccount);
        insert acc;
        
        Opportunity opps = new Opportunity(Name = 'Test Opps', CloseDate = system.today(), StageName = 'New', AccountId = acc.Id);
        insert opps;
        
        product2 prod = new Product2(Name = 'Test Prod', entity_id__c = '98765');
        insert prod;
        
        Pricebookentry pbey = new Pricebookentry(isActive = true, product2Id = prod.Id, UnitPrice = 50, Pricebook2ID = standardPb.id);
        insert pbey;
        
        Test.startTest();
        
            OpportunityLineItem item = new OpportunityLineItem(
                pricebookentryid = pbey.Id,
                Name__c = 'Test Prod',
                product_id__c = '98765',
                TotalPrice = 100,
                Quantity = 1,
                OpportunityID = opps.Id
            );
            
            try { 
                insert item;
            }
            catch (Exception duplicate) {
            
            }
            
        Test.stopTest();
    }
}

Thanks.
Hello All,

I need help in splitting FirstName and LastName in Account.

My Requirement:
If FirstName is empty, break LastName by first space character and use first part of it as firstname and the remaining as lastname.

How can I achieve this ? Trigger or Config.

Kindly Suggest.

Thanks.
Hi,

Kindly help me in reaching 75% in code coverage. I am getting 45% for the below trigger. Kindly refer the Trigger and Test Class and let me know what change to achieve 75%.
 
Trigger -----

trigger insertOppsLineitem on OrderItems__c (after insert) {
    System.debug('--- Inside OrderItems Trigger ---');      
          
    Set<Decimal> orderIds = new Set<Decimal>();
    
    for(OrderItems__c oi : Trigger.New) {
        orderIds.add(oi.OrderId__c);
        System.debug('--- Getting Custom Obj Id: ---' + orderIds);
    }
    
    Map<Decimal, List<Opportunity>> oppMap = new Map<Decimal, List<Opportunity>>();
    
    if(!orderIds.isEmpty()){
        System.debug('--- Checking Order ID: ---');
        for(Opportunity opp : [SELECT Id, Name, OrderItem__c FROM Opportunity WHERE OrderItem__c IN: orderIds]) {
            if(!oppMap.containsKey(opp.OrderItem__c)) {
                oppMap.put(opp.OrderItem__c, new List<Opportunity> {opp});
                System.debug('--- Opportunity Map ---' + oppMap);
            }            
        } 
    }
    
    List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE PriceBook2.isStandard = true LIMIT 1];

    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
    
    for(OrderItems__c oi : Trigger.New){
        System.debug('--- Order Items: ---' + oi);
        if(oppMap.containsKey(oi.OrderId__c)){
            for(Opportunity opp : oppMap.get(oi.OrderId__c)) {
                System.debug('--- Inside Opportunity ---');
                OpportunityLineItem oli = new OpportunityLineItem();                
                oli.OpportunityId = opp.Id;
                oli.PricebookEntryId = priceBookList[0].Id; 
                oli.Quantity = oi.Qty_Ordered__c;
                oli.TotalPrice = oi.Price__c;                
                oli.item_id__c = oi.Name;
                oli.Name__c = oi.Name__c;
                oliList.add(oli);
                System.debug('--- Inside Opportunity' + opp);
                System.debug('--- Oli List: ---');
            }
        }
    }
    try {
        if(oliList.size()>0) {
            insert oliList;
            System.debug('--- Inserted Opp Line Items: ---');
            System.debug('--- Inserted Opp Line Items: ---' + olilist.size()); 
        }
    }
    catch(Exception e){
        System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
    }
}
 
Test Class ----

@isTest
private class insertOppsLineitemTest {
    static testMethod void testorderItems() {
            OrderItems__c oi = new OrderItems__c();
            oi.Qty_Ordered__c = 1;
            oi.OrderId__c = 2333;
            oi.Price__c = 100;                
            oi.Name = 'Test';            
            insert oi;
            
            OrderItems__c o = [SELECT Id, Name FROM OrderItems__c WHERE Name = 'Test'];            
            
            Id RecordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('AccountRecordType').getRecordTypeId();
            
            Account acc = new Account();
            acc.Name = 'Test';
            acc.recordtypeid = RecordTypeIdAccount;             
            insert acc; 
            
            Opportunity opp = new Opportunity();
            opp.Name = 'Test';
            opp.CloseDate = system.today();
            opp.StageName = 'New';
            opp.Account.Id = acc.Id;
            opp.OrderItem__c = oi.OrderId__c;
            insert opp;
                        
            List<Opportunity> oppList = [SELECT Id, Name FROM Opportunity WHERE Name = 'Test'];
            
            List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE PriceBook2.isStandard = true LIMIT 1];
            
            Id pricebookId = Test.getStandardPricebookId();
            
            //Create your product
            Product2 prod = new Product2(
                 Name = 'Product X',
                 ProductCode = 'Pro-X',
                 isActive = true
            );
            insert prod;
            
            //Create your pricebook entry
            PricebookEntry pbEntry = new PricebookEntry(
                 Pricebook2Id = pricebookId,
                 Product2Id = prod.Id,
                 UnitPrice = 100.00,
                 IsActive = true
            );
            insert pbEntry;
            
            OpportunityLineItem oli = new OpportunityLineItem();                
            oli.OpportunityId = opp.Id;
            oli.PricebookEntryId = pbEntry.Id; 
            oli.Quantity = 1;
            oli.TotalPrice = 100;                
            oli.item_id__c = '1254';
            oli.Name__c = 'Testing';
            insert oli;            
            
    }
}

 
Hi,

My trigger is not checking Email exists in Account when inserting custom object with same email. But when I insert new custom object it is inserting account.

My Requirement:
1) Want to create a Custom Object by checking Email exists in Account or Not.
2) If Email Exists update the fields with that of custom object values.
3) If not Email Exists create New Account.
4) Delete the Custom Object Record once Account is created.

Kindly review my below code and please let me know what changes need to be done to achieve my requirement.
 
trigger updateCustomer on Customer__c (before insert, before update, after insert, after delete) {
    system.debug('--- Inside Customer Trigger ---');
                
    Set<String> cusSet = new Set<String>();
    List<Customer__c> cusList = [SELECT Id, Name FROM Customer__c WHERE Id IN: cusSet];        
    for(Customer__c cus : trigger.New) {
        System.debug('--- Inside Customer Obj: ---' + cus);
        cusSet.add(cus.Email__c);
    }
            
    List<Account> accList = new List<Account>();
    Map<String, List<Account>> accMap = new  Map<String, List<Account>>();
    accList = [SELECT Id, Name, PersonEmail, City__pc FROM Account WHERE PersonEmail IN: cusSet];
    
    System.debug('--- Account List ---' + accList);        
    
    if(!cusSet.isEmpty()){
        System.debug('--- cusSet ---' + cusSet);
        for(Account acc : accList) {
            System.debug('--- Account Email Map: ---' + acc);
            if(!accMap.containsKey(acc.PersonEmail)) {
                System.debug('--- Account Map: ---' + accMap);
                accMap.put(acc.PersonEmail, new List<Account> {acc});
            }
            else {
                System.debug('--- Inside Else Map ---');
                List<Account> acList = accMap.get(acc.PersonEmail);
                accList.add(acc);
                accMap.put(acc.PersonEmail, accList);
                System.debug('--- Inside Account List ---' + acList);
            }
        } 
    }
    
    if(trigger.isUpdate && trigger.isBefore) {
        for(Customer__c cus : Trigger.New) {
            System.debug('--- Inside Customer Forloop ---' + cus);
            if(accMap.containsKey(cus.Email__c)) {
                System.debug('--- Customer Email ---' + accMap);
                for(Account a : accMap.get(cus.Email__c)) {
                    System.debug('--- Matching Email ---' + a);
                    Account acct = new Account (id = a.Id);
                    acct.LastName = cus.Name;
                    acct.City__pc = cus.City__c;
                    accList.add(acct);
                }
                try {
                    System.debug('--- Inside try ---');
                    if(accList.size()>0) {
                        update accList;
                        System.debug('--- Inserted Account : ---');
                        System.debug('--- Account List: ---' + accList.size()); 
                    }
                }
                catch(Exception e) {
                    System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
                }
            }
        }
    }            
        
    if(trigger.isInsert && trigger.isAfter) {
        System.debug('--- Inside Insert ---');
        for(Customer__c cus : Trigger.New) {
            System.debug('--- Inside Customer Forloop ---' + cus);            
            if(!accMap.containsKey(cus.Email__c)) {
                System.debug('--- Customer Email ---' + accMap);
                Account acct = new Account();
                acct.PersonEmail = cus.Email__c;
                acct.LastName = cus.Name;
                acct.City__pc = cus.City__c;
                accList.add(acct);
            }
            try {
                System.debug('--- Inside try ---');
                if(accList.size()>0) {
                    insert accList;
                    System.debug('--- Inserted Account : ---');
                }
                System.debug('--- Account List: ---' + accList.size());
            }
            catch(Exception e) {
                System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
            }
        }
    }        
    
    if(trigger.isAfter && trigger.isDelete){
        for(Customer__c cus : Trigger.old){
            if(cus.Id != null) {
                cusSet.add(cus.Id);
            }
            try {
                System.debug('--- Inside try ---');
                if(cusList.size()>0) {
                    delete cusList;
                    System.debug('--- Deleted Customer : ---');
                }
                System.debug('--- Deleted List: ---' + accList.size());
            }
            catch(Exception e) {
                System.debug('The Following Exception has occurred: '+ e.getLinenumber() + ' : ' + e.getMessage());
            }
        }
    }            
}

Thanks in Advance