• Kevin Cross
  • NEWBIE
  • 174 Points
  • Member since 2016
  • Crossed Logic Consulting LLC


  • Chatter
    Feed
  • 4
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 77
    Replies
Why is it necessary to have a nested for loop to go through results when a query from a parent sObject includes fields from the child sObject, but not when the query is from the child sObject and includes parent fields? 

Thank you.
Hello,

I have created the below trigger from events to write certain information to leads if event type criterea met:

1
2
3
4
5
6
7
8
9
10
11
12
13
trigger LeadUpdates on Event (before insert) {
  Set<Id> recordIds = new Set<Id>();
  List<Lead> leadsToUpdate = new List<Lead>();
      for(Event t:Trigger.new)
        if(t.type=='Discovery')
          recordIds.add(t.whoid);
      leadsToUpdate = [select id from lead where id in :recordIds];
          for(Lead l:leadsToUpdate)
            {L.SQL_Scheduled__c = TRUE;
             L.Status = '07 SQL';
             }
            update leadsToUpdate;
}

Here is the test class I wrote.  What am I missing?  When I validate the depoyment I get an error that there is 0% coverage for my trigger:


@isTest
public class testEventTrigger {
  static testMethod void test1() {
        // set up leads
        List<Lead> testLeads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.Company = 'Test 1 New Company';
        lead1.LastName = 'Martha';
        lead1.LeadSource = 'Not Converted';
        lead1.Status = '04 Sales Lead';
        lead1.Email = 'test@test.com';
        lead1.Business_Type__c = 'App/Business';
        lead1.Lead_Role__c = 'Product';
        testLeads.add(lead1);
        
        Lead lead2 = new Lead();
        lead2.Company = 'Test 12';
        lead2.LastName = 'Jordan';
        lead2.LeadSource = 'Not Converted';
        lead2.Status = '04 Sales Lead';
        lead2.Email = 'test@test.com';
        lead2.Business_Type__c = 'App/Business';
        lead2.Lead_Role__c = 'Product';
        testLeads.add(lead2);
    insert testLeads;
    
        // set up Events
       List<Event> events = new List<Event>();
       Event event1 = new Event();
       event1.WhoId=testLeads[0].Id; 
       event1.Subject= 'Test0';
       event1.Type='Discovery';
       event1.STARTDATETIME=System.today();
       event1.ENDDATETIME=System.today();

       Event event2 = new Event();
       event2.WhoId=testLeads[1].Id; 
       event2.Subject= 'Test1';
       event2.Type='Discovery';
       event2.STARTDATETIME=System.today();
       event2.ENDDATETIME=System.today();
    
    insert events;
    
    Map<Id,Lead> leadResults1 = new Map<Id,Lead>([select id,SQL_Scheduled__c from lead where id in :testLeads]);
    System.assertEquals(testLeads[1].SQL_Scheduled__c,leadResults1.get(testLeads[1].Id).SQL_Scheduled__c,TRUE);
    System.assertEquals(testLeads[0].SQL_Scheduled__c,leadResults1.get(testLeads[0].id).SQL_Scheduled__c,TRUE);
    
    Map<Id,Lead> leadResults2 = new Map<Id,Lead>([select id,Status from lead where id in :testLeads]);
    System.assertEquals(testLeads[1].Status,leadResults2.get(testLeads[1].Id).Status,'07 SQL');
    System.assertEquals(testLeads[0].Status,leadResults2.get(testLeads[0].id).Status,'07 SQL');
  }}
Hello, 

new to Triggers, we want to populate a custom lookup field with the current user when an opportunity is closed. 

For example, we have a custom field called closed_by__c which is a lookup to the user object. When a user selects "Closed" from the standard stagename field we want to have the users name populated in the closed_by__c 

I've spent a ton of time looking through the forums but I haven't come across somebody with the same situation. 

any thoughts on how to do this ?
here is what I started with
trigger updateClosedByField on Opportunity (after insert, after update){
for(opportunity opp : trigger.new) 
 
 {
 
    opp.closed_by__c = opp.StageName;
    }
    
    }

 
public pageReference addToCart() {
        if(!Catalog_Order__c.sObjectType.getDescribe().isUpdateable() || !Catalog_Line_Item__c.sObjectType.getDescribe().isCreateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        if( productId == null ) {} else {
        // First make sure that our Order is in the database
        upsert myOrder;
        orderId = myOrder.Id;

        produto = productId;
        // Check if the product is already in the Cart
        if( productSet.contains( productId ) ) { } else {
            // Here is where we add the ID to the set...
            productSet.add( productId );
            // ...and to the Order.
            Catalog_Line_Item__c li =  new Catalog_Line_item__c();
            li.Product__c = productId;
            produto = productId;
            li.Catalog_Order__c = myOrder.Id;
            li.Quantity__c = 1;
            insert li;        
            
            // Added to Cart
            }
        }
        // Clear the parameter and reupsert
        productId = null;
        upsert myOrder;
        return null;
    }
 public PageReference toCart() {

        integer stdPriceBookRecId2; 
        List<Pricebook2> stdPriceBookRecId = new List<Pricebook2>();
        Catalog_Order__c[] orderQuery = [SELECT Items__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Quantity__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Status__c = 'Cart' AND CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];

        // Insert Pricebook
        PriceBook2 customPriceBook = new PriceBook2();
        customPriceBook.Name='Custom Pricebook';
        customPriceBook.IsActive=true;
        insert customPriceBook;
        
        // Query Standard and Custom Price Books
        Pricebook2 customPriceBookRec=[select Id from Pricebook2 where id=:customPriceBook.Id];
        stdPriceBookRecId = [SELECT Id, isstandard FROM Pricebook2 WHERE IsStandard=true];
        
        // Create Standard PriceBookEntry
        PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
        stdPriceBookEntry.Product2Id=produto;
        stdPriceBookEntry.Pricebook2Id=stdPriceBookRecId[0].Id;
        stdPriceBookEntry.UnitPrice=2001;
        stdPriceBookEntry.IsActive=true;
        insert stdPriceBookEntry;
        
        // Create Custom PriceBookEntry
        PriceBookEntry customPriceBookEntry = new PriceBookEntry();     
        customPriceBookEntry.Product2Id=produto;
        customPriceBookEntry.Pricebook2Id=customPriceBookRec.Id;
        customPriceBookEntry.UnitPrice=5001;
        customPriceBookEntry.IsActive=true;
        insert customPriceBookEntry;
        
        // Create Opportunity
        Opportunity opp = new Opportunity();
        opp.Name = 'OPORTUNIDADE TESTE';
        opp.CloseDate= System.Today();
        opp.StageName='Prospecting';
        insert opp;
        
        // Add product and Pricebook to the particular opportunity using OpportunityLineItem 
        OpportunityLineItem oppLineItem = new OpportunityLineItem();
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
        oppLineItem.UnitPrice = 7001;
        oppLineItem.Quantity = 4;
        insert oppLineItem;  
        
        
        if(!Catalog_Order__c.sObjectType.getDescribe().isAccessible()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        try{
            myOrder = [SELECT Items__c,Lines__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Price__c,Quantity__c,Subtotal__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Id =: orderId LIMIT 1];
        } catch (exception e) {System.debug(e.getMessage());}

        PageReference next = new PageReference('/apex/catalog_cart');
        next.setRedirect(false);
        // Directing to Cart
        return next;
    }
This is the code.

These are pieces of Catalog_Controller Class that I'm modifying to add the products of the Catalog Order to an Opportunity that's created when the catalog is submited. The error : 
' Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, This price definition already exists in this price book: [] '
appers.

Can someone help me?

Thanks.
Hello everyone 

I want to update event custom field in lead detail page please help me.
Ques: I have a three custom field in Event object
1- Meeting Status (API - Meeting_Status__c(picklist)) (values: Scheduled, Rescheduled, Cancelled, No Show)
2- Is Meeting Completed-( API-Is_Meeting_Completed__c(Checkbox))
3-First Meeting Scheduled-
(API - First_Meeting_Scheduled__c(Checkbox))

same as in Lead object 
I want that when any Event  create with the values of these three custom object or two custom field, lead  detail page would update them with same values.  
Crux of the matter is that i want to update Event custom field in Lead detail page.
 
See the Scenario...
 For more Details
 Please Help me And reply  ASAP.

Thanks and Regards
Bharat Sharma



 
At the click of a custom button on an Opportunity object, this is supposed to:
  1. Capture all Opportunity line items
  2. Concatenate all line items except ones that have DISCOUNT in the name into a Samples_Sent__c field
  3. Delete all Opportunity line items
It executes perfectly if the net count (opportunity line items that do not have DISCOUNT in the name) of the items being concatenated is two or more but does nothing (does not concatenate and no errors) if the net count is one.
 
{!REQUIRESCRIPT("/soap/ajax/32.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/32.0/apex.js")}
var record = new sforce.SObject("Opportunity");
record.Id = '{!Opportunity.Id}';

var retriveOpptyLineItems = sforce.connection.query("Select PricebookEntry.Product2.Name, Quantity, TotalPrice From OpportunityLineItem WHERE OpportunityId = '{!Opportunity.Id}' and (NOT Name like '%Discount%')");

var strProductNames = '';
for(var i=0; i<retriveOpptyLineItems.records.length ; i++){
strProductNames += 'PRODUCT NAME: ' + retriveOpptyLineItems.records[i].PricebookEntry.Product2.Name + ' --- QUANTITY: ' + retriveOpptyLineItems.records[i].Quantity + ' --- TOTAL PRICE: $ ' + retriveOpptyLineItems.records[i].TotalPrice +',' + '\n ';
}

//eliminate the last ','
if(strProductNames.length>0){
strProductNames = strProductNames.substring(0,strProductNames.length-1);
}
record.Samples_Sent__c = strProductNames;

sforce.connection.update([record]);
window.location.reload();

 
Hi friends,
I am facing problem for writing a trigger. Condition is as below:
This is for Apportunity object. Whenever I am creating an apportunity and saving the record then The Product detail should display with price under Product section of detail page. I have created Price book for all items as below.

Picklist field is --  Business category and values are Product and  Service.
Dependent picklist (on business category) field is - Select product is - Product (BPMS and Lhetto) and for service (Java, Dot Net, salesforce)
For product, there is another field Licence which contains Unit Licence and Enterprise.

After saving the selected items in all these 3 fields, then the respective product or service with price shoud displace in Product section of the record detail page.
  • August 14, 2016
  • Like
  • 0
Hi,

I'' m trying to put the value of Quantity from Catalog_Line_Item__c to 'Quantity' from Opportunity.
 
/* 
     *  updateQuantity(String ID) 
     *  Updates the Quantity field of the Catalog Line Item with the given Id 
     */
    public PageReference updateQuantity() {
        if(!Catalog_Line_Item__c.sObjectType.getDescribe().isUpdateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        
        li = [SELECT Quantity__c FROM Catalog_Line_Item__c WHERE Id =: productId LIMIT 1];
        li.Quantity__c = productQuantity;
        update li;
        update myOrder;      
        quantity = li.Quantity__c;
        
        // Stay on current page
        return null;
    }
(variable 'quantity' is double)
 
// Add product and Pricebook to the particular opportunity using OpportunityLineItem 
        OpportunityLineItem oppLineItem = new OpportunityLineItem();
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
        oppLineItem.UnitPrice = customPriceBookEntry.UnitPrice;
        oppLineItem.Quantity = quantity ;
        insert oppLineItem;

This is the error message. that appeats when I Execute the Catalog:
Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING: [Quantity]: [Quantity].

Can someone help me?
Thanks.
Hi 
I am using Standard controller (Case ) with extesion controller  I ma upsertingthe case record in amy controller ;
public with sharing Myclass{


//Constructor   

  
    public myController(ApexPages.StandardController stdController){
    
   
            try{
            this.caseId= ApexPages.currentPage().getParameters().get('id');
            if(caseId != null)
                oCase = [select Id, CaseNumber,AccountId, Owner.Name, Status, Priority, Origin, Contact.Name, Account.Name, Type, Reason, Subject, Description,(Select CommentBody from CaseComments order by createddate limit 1) from Case where Id = :caseId];
        } 
        catch(Exception e){
            ExceptionLogger.addException(e,'myController','Constructor'); 
            
        }
    }    
    
     public PageReference save(){

    upsert oCase;
   PageReference pg = new PageReference('/apex/Mypage');
   pg.getParameters().put('id',oCase.Id);        
    flag1=true;
    flag2= false;
    return pg;

}

When I try to cover /run the test class on save() in Test Class , after inserting Case it give me an error 
Attempted to upsert a null list

//Test Class Code :

Insert CaseList[with data ];
System.debug('showCas caseList= '+caseList); //Here i can see the case list 
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(caseList[0]);
        myController controller = new myController(sc);
        controller.save() // Attempted to upsert a null list
Please help me ! Really needed ,

Thanks in Advance ! 
Hi everyone,

I have a trigger on the Event Object that basically serves as a rollup summary to count the number of certain types of Events that are related to an account, and then display that number on the parent Account. The code seems to work really well, except for when the whatId relationship is changed or removed on the event.

For example, if I have a single Event A where the whatId is Account A, it properly shows on the Account A record that there is 1 child event. However, if I change the whatId relationship to Account B, Account A will not get updated by the trigger on the event, and will still show (falsely) that there is 1 child event on the account.

I believe that I need to add a case for my code using the trigger.old value for the event, however I could really use some guidence on how exactly to account for this case. Here is my current code.
 
/* Provide summary of Number of Site Visit Events on Account record and populates the Site Visit Date field*/

trigger countSiteVisits on Event (after delete, after insert, after undelete, 
after update) {

    Event[] events;
    if (Trigger.isDelete) 
        events = Trigger.old;
    else
        events = Trigger.new;

    // get list of accounts
    Set<ID> acctIds = new Set<ID>();
    for (Event evn : events) {
            acctIds.add(evn.WhatId);
    }
    
    Map<ID, Event> eventsForAccounts = new Map<ID, Event>([select Id
                                                            ,WhatId
                                                            from Event
                                                            where WhatId in :acctIds AND Type ='Site Visit' AND GTM_Status__c = 'Completed' AND isDeleted = FALSE ALL ROWS]);

    Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id
                                                                 ,Completed_Site_Visits__c
                                                                  from Account
                                                                  where Id in :acctIds]);
    
    for (Account acct : acctsToUpdate.values()) {
        Set<ID> eventIds = new Set<ID>();
        
        for (Event evn : eventsForAccounts.values()) {
            if (evn.WhatId == acct.Id)
            eventIds.add(evn.Id);
        }
              
        if (acct.Completed_Site_Visits__c != eventIds.size())
            acct.Completed_Site_Visits__c = eventIds.size();
            
        Map<ID, Event> latestEventForAccount = new Map<ID, Event>([SELECT Id, ActivityDate FROM Event
                                                                    WHERE WhatId = :acct.Id AND ID in :eventIds AND Type ='Site Visit' AND GTM_Status__c = 'Completed' AND isDeleted = FALSE ORDER BY ActivityDate DESC LIMIT 1 ALL ROWS]);
        
        for (Event mylatestEvent: latestEventForAccount.values()) {
            if (mylatestEvent.ActivityDate != null)
            acct.Site_Visit_Date__c = mylatestEvent.ActivityDate;
        }
    }

    try {
        update acctsToUpdate.values();
    }
    
    catch (DMLException e) {
        for (event eventCatch: trigger.new) {
            eventCatch.addError(e.getDmlMessage(0));
        }
    }
    catch (Exception e) {
        for (event eventCatch : trigger.new) {
            eventCatch.addError(e.getMessage());
        }
    }
}
Any help appreciated, thank you!
 
public pageReference addToCart() {
        if(!Catalog_Order__c.sObjectType.getDescribe().isUpdateable() || !Catalog_Line_Item__c.sObjectType.getDescribe().isCreateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        if( productId == null ) {} else {
        // First make sure that our Order is in the database
        upsert myOrder;
        orderId = myOrder.Id;

        produto = productId;
        // Check if the product is already in the Cart
        if( productSet.contains( productId ) ) { } else {
            // Here is where we add the ID to the set...
            productSet.add( productId );
            // ...and to the Order.
            Catalog_Line_Item__c li =  new Catalog_Line_item__c();
            li.Product__c = productId;
            produto = productId;
            li.Catalog_Order__c = myOrder.Id;
            li.Quantity__c = 1;
            insert li;        
            
            // Added to Cart
            }
        }
        // Clear the parameter and reupsert
        productId = null;
        upsert myOrder;
        return null;
    }
 public PageReference toCart() {

        integer stdPriceBookRecId2; 
        List<Pricebook2> stdPriceBookRecId = new List<Pricebook2>();
        Catalog_Order__c[] orderQuery = [SELECT Items__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Quantity__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Status__c = 'Cart' AND CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];

        // Insert Pricebook
        PriceBook2 customPriceBook = new PriceBook2();
        customPriceBook.Name='Custom Pricebook';
        customPriceBook.IsActive=true;
        insert customPriceBook;
        
        // Query Standard and Custom Price Books
        Pricebook2 customPriceBookRec=[select Id from Pricebook2 where id=:customPriceBook.Id];
        stdPriceBookRecId = [SELECT Id, isstandard FROM Pricebook2 WHERE IsStandard=true];
        
        // Create Standard PriceBookEntry
        PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
        stdPriceBookEntry.Product2Id=produto;
        stdPriceBookEntry.Pricebook2Id=stdPriceBookRecId[0].Id;
        stdPriceBookEntry.UnitPrice=2001;
        stdPriceBookEntry.IsActive=true;
        insert stdPriceBookEntry;
        
        // Create Custom PriceBookEntry
        PriceBookEntry customPriceBookEntry = new PriceBookEntry();     
        customPriceBookEntry.Product2Id=produto;
        customPriceBookEntry.Pricebook2Id=customPriceBookRec.Id;
        customPriceBookEntry.UnitPrice=5001;
        customPriceBookEntry.IsActive=true;
        insert customPriceBookEntry;
        
        // Create Opportunity
        Opportunity opp = new Opportunity();
        opp.Name = 'OPORTUNIDADE TESTE';
        opp.CloseDate= System.Today();
        opp.StageName='Prospecting';
        insert opp;
        
        // Add product and Pricebook to the particular opportunity using OpportunityLineItem 
        OpportunityLineItem oppLineItem = new OpportunityLineItem();
        oppLineItem.OpportunityId = opp.Id;
        oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
        oppLineItem.UnitPrice = 7001;
        oppLineItem.Quantity = 4;
        insert oppLineItem;  
        
        
        if(!Catalog_Order__c.sObjectType.getDescribe().isAccessible()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        try{
            myOrder = [SELECT Items__c,Lines__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Price__c,Quantity__c,Subtotal__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Id =: orderId LIMIT 1];
        } catch (exception e) {System.debug(e.getMessage());}

        PageReference next = new PageReference('/apex/catalog_cart');
        next.setRedirect(false);
        // Directing to Cart
        return next;
    }
This is the code.

These are pieces of Catalog_Controller Class that I'm modifying to add the products of the Catalog Order to an Opportunity that's created when the catalog is submited. The error : 
' Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, This price definition already exists in this price book: [] '
appers.

Can someone help me?

Thanks.