• HTANIRS
  • NEWBIE
  • 125 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 31
    Replies
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.
Hello Friends,

I want to send an email with Attachments from Notes & Attachments of a Record.
I had created a Trigger but it is not sending a template with Attachments.

Below is my code:
Apex Class:

public with sharing class HelperContactTrigger {
    //static method
    public static List<Lead> sendEmail(List<Lead> leads) {

        //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name=:'Thank You Email'];

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

        //loop
        for(Lead le : Leads){

            //check for LastName
            if(le.LastName != null){                                
                
                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id
                singleMail.setTargetObjectId(le.Id);

                //set template Id
                singleMail.setTemplateId(et.Id);

                //flag to false to stop inserting activity history
                singleMail.setSaveAsActivity(false);

                //add mail
                emails.add(singleMail);

               //This will not send email to contact  
                singleMail.setTreatTargetObjectAsRecipient(false);
            }
        }

        //send mail
        Messaging.sendEmail(emails);

        return leads;
        
    } 
}

Apex Trigger:

trigger SendEmail on Lead (after insert) {
    if(Trigger.isAfter){
        if(Trigger.isInsert ){ 
            HelperContactTrigger.sendEmail(trigger.new);
        }
    }
}

Kindly need your inputs. Thanks.
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
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
Hi,
I have created a schedule class to RUN every 1 hour but It is not checking the newly created record and inserting. Kindly review my code and let me know what changes need to be done.

My Requirement:
I want to write a schedule class on custom object to check newly created custom object record is created in Opportunity Line Items.
I have a field common to find custom obj and opportunity which is used to find opplineitems.
 
global class orderItems Implements Schedulable {

    global void execute(SchedulableContext sc) {
        insertOrder();
    }

    public void insertOrder() {
        
        List<OrderItems__c> lstOpty = [SELECT Id, Name, OrderId__c, Due_Date__c, Name__c, Discount_Amount__c, Price__c, Product_Id__c, Product_Type__c,
                                              Qty_Backordered__c, Qty_Canceled__c, Qty_Invoiced__c, Qty_Ordered__c, Qty_Refunded__c, Qty_Returned__c, Qty_Shipped__c, Sku__c
                                          FROM OrderItems__c WHERE CreatedDate > TODAY];
        
        Set<Decimal> orderIds = new Set<Decimal>();

        for(OrderItems__c oi : lstOpty) {
            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 : lstOpty){
            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;
                    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.Sku__c = oi.Sku__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());
        }
    }
}

Need assistance to complete this code.

Thanks.
Hi,
i need help in creating Apex schedule jobs to check every 5 mins whether opportunity is newly created or not. I don't know how to start.
Please need your help to complete.

Thanks
Hi,

I need help in below Trigger. I am unable to pull opportunity Id to insert Opportunity Line Items. I have hardcoded and inserted in below code.
Requirement:
I have a Custom Object where it has same fields as Opportunity Line Items. When Inserting Custom Object I want to insert Opportunity Line Items with respect to opportunity. Opportunity and custom object does not have relationship. But they have a common field called orderId where I can match Opp and Custom Obj.
 
trigger insertOppsLineitem on OrderItems__c (after insert) {
    System.debug('--- Inside OrderItems Trigger ---');      

    Set<Id> orderIds = new Set<Id>();
    Set<Id> oppIds = new Set<Id>();
    
    for(OrderItems__c oi : Trigger.New) {
        orderIds.add(oi.Id);
        System.debug('--- Getting Custom Obj Id: ---' + orderIds);
    }
    
    Map<Id, List<Opportunity>> oppMap = new Map<Id, List<Opportunity>>();
    
    if(!orderIds.isEmpty()){
        System.debug('--- Checking Order ID: ---');
        for(Opportunity opp : [SELECT Id, Name FROM Opportunity WHERE Name IN: orderIds]){
            orderIds.add(opp.Id);
            System.debug('--- opportunity Ids:' + orderIds);
        } 
    }    

    List<OrderItems__c> orderItems = [SELECT Id, Name, OrderId__c FROM OrderItems__c WHERE Id IN :Trigger.newMap.keyset()];
    
    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 o : Trigger.New){
        System.debug('--- Order Items : ---');
       // for(Opportunity opp : oppMap.get(o.Name)){
            System.debug('--- Inside Opportunity');
            OpportunityLineItem oli = new OpportunityLineItem();
            oli.OpportunityId = '0060p000001rgcR';
            oli.PricebookEntryId = priceBookList[0].Id; 
            oli.Quantity = o.Qty_Ordered__c;
            oli.TotalPrice = o.Price__c;
            oliList.add(oli);
         //   System.debug('--- Inside Opportunity' + opp);
            System.debug('--- Oli List: ---');
        //}
    }
}

Kindly help to achieve this code freeze.

Thanks.
Hi Friends,

I need help in writing trigger to insert a record in custom object.
I have enabled Person Account. Now I have Person Account and Account in my org. I have created a lookup field to Account in campaign.
My Requirement is :
When importing a campaignmember in a Campaign and mapping to Person Account. Then I should create a record in the custom object with the account name in campaign.
Custom Object is Related List to Person Account.

Am trying to solve using below Trigger but cannot able to create a new record in custom object.

trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Inside CampaignMember : Entered Trigger ----');
    try{
        
        Set <Id> cIds = new Set <Id> ();
        Map<Id,campaign> accountCampaignMap = new Map<Id,campaign>();

        for (CampaignMember cm : Trigger.new) {
            System.debug('---- Inside CampaignMember : ----');
            cIds.add(cm.CampaignId);
        }
        
        
        for(Campaign cam : [Select Id, Name, Business_Accounts__c from Campaign where Business_Accounts__c = :cIds]){
            System.debug('---- Inside CampaignMember List: ----');
            accountCampaignMap.put(cam.Business_Accounts__c,cam);
        }
        
        List<Customer_Object__c> customObjectList = new List<Customer_Object__c>();
        
        for (CampaignMember cm : Trigger.new) {
            if(accountCampaignMap.containsKey(cm.CampaignId)) {
                System.debug('---- Inserting Record in Custom Object : ----');                
                Customer_Object__c cusobj = new Customer_Object__c(Business_Accounts__c = accountCampaignMap.get(cm.CampaignId).Id);
                customobjectList.add(cusobj);
            }
        }
        
        if(customObjectList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customObjectList;
        }
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }
    
}


Please Help.... Thanks in advance..
 
  • September 05, 2018
  • Like
  • 0
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 Friends,

Need help to write test class for below class:

global class AutocreatedRegHandler1432826053915 implements Auth.RegistrationHandler{

    global User createUser(Id portalId, Auth.UserData data){

        User u = [SELECT ID FROM User Where Other_Salesforce_Org_Username__c = : data.username];

        return u;

    }

    global void updateUser(Id userId, Id portalId, Auth.UserData data){
       System.debug('Update User called for: ' + data.email);    
    User u = new User(id=userId);
    u.email = data.email;
    u.lastName = data.lastName;
    u.firstName = data.firstName;
    update(u);

    }
}

Thanks.
Hi Friends,

Please help on below Trigger. I am trying to insert Quote when the attachment is added to Opporunity and the file name contains PDF.

trigger oppattachment on Attachment (after insert, after update) {
    
    Set <Id> oppIds = new Set <Id>();    
    for(Attachment attach : Trigger.new) {
        if(attach.ParentId.getSobjectType() == Opportunity.SobjectType) {
            if(string.valueOf(attach.Name).contains('.pdf')) {
                oppIds.add(attach.ParentId);
            }
        }
    }
    List <Quote> quoteList = [SELECT id, name, opportunityid FROM Quote WHERE Id IN: oppIds];
    for(Attachment attach : Trigger.new) {
        if(quoteList !=null && quoteList.size()>0){
            for(quote q : quotelist){    
                q.name = attach.name;       
            }
            insert quoteList;
        }
    }                
}

Thanks.
Hi, 
I need help in passing opportunity id in the below soql query for Trigger. Am using this trigger to copy attachments from opportunity to Quote whenever the quote is created from opportunity. I have hard coded the record id and i need to how to get the record id in the query.

trigger CloneAtt on Quote (after insert) {    
    
    Attachment[] attList = [SELECT id, name, body, parentid
                              FROM Attachment 
                              WHERE ParentId = '0060K00000Ra3Ei'];

    
    Attachment[] insertAttList = new Attachment[]{};
    
    for(Attachment a: attList){
        Attachment att = new Attachment(name = a.name, body = a.body, parentid = Trigger.new[0].id);
        insertAttList.add(att);
    }
    
    if(insertAttList.size() > 0){
        insert insertAttList;
    }
}
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 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
Hi,
I have created a schedule class to RUN every 1 hour but It is not checking the newly created record and inserting. Kindly review my code and let me know what changes need to be done.

My Requirement:
I want to write a schedule class on custom object to check newly created custom object record is created in Opportunity Line Items.
I have a field common to find custom obj and opportunity which is used to find opplineitems.
 
global class orderItems Implements Schedulable {

    global void execute(SchedulableContext sc) {
        insertOrder();
    }

    public void insertOrder() {
        
        List<OrderItems__c> lstOpty = [SELECT Id, Name, OrderId__c, Due_Date__c, Name__c, Discount_Amount__c, Price__c, Product_Id__c, Product_Type__c,
                                              Qty_Backordered__c, Qty_Canceled__c, Qty_Invoiced__c, Qty_Ordered__c, Qty_Refunded__c, Qty_Returned__c, Qty_Shipped__c, Sku__c
                                          FROM OrderItems__c WHERE CreatedDate > TODAY];
        
        Set<Decimal> orderIds = new Set<Decimal>();

        for(OrderItems__c oi : lstOpty) {
            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 : lstOpty){
            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;
                    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.Sku__c = oi.Sku__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());
        }
    }
}

Need assistance to complete this code.

Thanks.
Hi,
i need help in creating Apex schedule jobs to check every 5 mins whether opportunity is newly created or not. I don't know how to start.
Please need your help to complete.

Thanks
Hi,

I need help in below Trigger. I am unable to pull opportunity Id to insert Opportunity Line Items. I have hardcoded and inserted in below code.
Requirement:
I have a Custom Object where it has same fields as Opportunity Line Items. When Inserting Custom Object I want to insert Opportunity Line Items with respect to opportunity. Opportunity and custom object does not have relationship. But they have a common field called orderId where I can match Opp and Custom Obj.
 
trigger insertOppsLineitem on OrderItems__c (after insert) {
    System.debug('--- Inside OrderItems Trigger ---');      

    Set<Id> orderIds = new Set<Id>();
    Set<Id> oppIds = new Set<Id>();
    
    for(OrderItems__c oi : Trigger.New) {
        orderIds.add(oi.Id);
        System.debug('--- Getting Custom Obj Id: ---' + orderIds);
    }
    
    Map<Id, List<Opportunity>> oppMap = new Map<Id, List<Opportunity>>();
    
    if(!orderIds.isEmpty()){
        System.debug('--- Checking Order ID: ---');
        for(Opportunity opp : [SELECT Id, Name FROM Opportunity WHERE Name IN: orderIds]){
            orderIds.add(opp.Id);
            System.debug('--- opportunity Ids:' + orderIds);
        } 
    }    

    List<OrderItems__c> orderItems = [SELECT Id, Name, OrderId__c FROM OrderItems__c WHERE Id IN :Trigger.newMap.keyset()];
    
    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 o : Trigger.New){
        System.debug('--- Order Items : ---');
       // for(Opportunity opp : oppMap.get(o.Name)){
            System.debug('--- Inside Opportunity');
            OpportunityLineItem oli = new OpportunityLineItem();
            oli.OpportunityId = '0060p000001rgcR';
            oli.PricebookEntryId = priceBookList[0].Id; 
            oli.Quantity = o.Qty_Ordered__c;
            oli.TotalPrice = o.Price__c;
            oliList.add(oli);
         //   System.debug('--- Inside Opportunity' + opp);
            System.debug('--- Oli List: ---');
        //}
    }
}

Kindly help to achieve this code freeze.

Thanks.
Hi Friends,

I need help in writing trigger to insert a record in custom object.
I have enabled Person Account. Now I have Person Account and Account in my org. I have created a lookup field to Account in campaign.
My Requirement is :
When importing a campaignmember in a Campaign and mapping to Person Account. Then I should create a record in the custom object with the account name in campaign.
Custom Object is Related List to Person Account.

Am trying to solve using below Trigger but cannot able to create a new record in custom object.

trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Inside CampaignMember : Entered Trigger ----');
    try{
        
        Set <Id> cIds = new Set <Id> ();
        Map<Id,campaign> accountCampaignMap = new Map<Id,campaign>();

        for (CampaignMember cm : Trigger.new) {
            System.debug('---- Inside CampaignMember : ----');
            cIds.add(cm.CampaignId);
        }
        
        
        for(Campaign cam : [Select Id, Name, Business_Accounts__c from Campaign where Business_Accounts__c = :cIds]){
            System.debug('---- Inside CampaignMember List: ----');
            accountCampaignMap.put(cam.Business_Accounts__c,cam);
        }
        
        List<Customer_Object__c> customObjectList = new List<Customer_Object__c>();
        
        for (CampaignMember cm : Trigger.new) {
            if(accountCampaignMap.containsKey(cm.CampaignId)) {
                System.debug('---- Inserting Record in Custom Object : ----');                
                Customer_Object__c cusobj = new Customer_Object__c(Business_Accounts__c = accountCampaignMap.get(cm.CampaignId).Id);
                customobjectList.add(cusobj);
            }
        }
        
        if(customObjectList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customObjectList;
        }
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }
    
}


Please Help.... Thanks in advance..
 
  • September 05, 2018
  • Like
  • 0