• NecroGiggles
  • NEWBIE
  • 80 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 11
    Questions
  • 12
    Replies
I am having a problem with the before insert part of this trigger I think. The problem is  when a new lead or contact is added to the campain member object. The below trigger does not work it only seems to work right when a update to a exsting campain record object. I dont know were to start trying to fix it. 
 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
// Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];

for (CampaignMember member : Trigger.New) {
    for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
        if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
            kpiTarget.ECI_Product__c == member.ECI_Product__c &&
            kpiTarget.CurrencyIsoCode == member.Currency__c &&
            kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
            kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
            member.HasResponded == True)
        {
            member.Marketing_KPI_Target__c = kpiTarget.Id;
            continue;
        }
    }
}
}

 
I am having a problem with the timing of this trigger. Here is the scenario that cuases it not to work right.

When you add a Lead or Contact as a Campain Memebr and you set the  Response_Tracking_date__c from Null to a date the trigger does not fire off. It will fire if you edit the same recored and save it again no problem or if you just leave Response_Tracking_date__c blank and let the system fill it out. 

I think it has something to do with it being "before Insert" I am guessing the new info in  Response_Tracking_date__c is not there to look at when the trigger fires off. I tired adding "after Insert" but get errror " execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.CampaignMemberTrigger: line 15, column 1"
 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update, after insert) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.Currency__c &&
               	member.Response_Tracking_date__c != Null &&
                kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}



 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.Currency__c &&
               	member.Response_Tracking_date__c != Null &&
                kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}

 
My problem is that whenever we delete the date info from Response_Tracking_Date__c  on a Campaign Member object I get an error.
"System.NullPointerException: Attempt to de-reference a null object: Trigger.CampaignMemberTrigger: line 10, column 1"

I am not sure what I need to do to the code to get around this problem. I was thinking an if statement between the 2 for loops on line 5 and 6. 

 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.CurrencyIsoCode &&
               	kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}


 
I need to link "Campaign Members" to a custom object "KPITarget" based on values of both objects using a lookup field. 
The conditions are based on vales from both objects 3 fields that need to match on both objects and a date fields that just needs the month and year to mach. The last thing is the "HasResponded" field must be true on Campaign member.

I think this needs to be a class called by a Trigger but I am not sure since there will be no link between the objects at the start.
Create a List of all Campaign Member Id's getting the values of the 3 fields, Date Range and, HasResponded That the trigger fires off.
Create a List of all KPITargets Id’s that match the values of the Campaign Member, There should only be one.
The update the look up field on Campaign member with the ID of the KPITarget that matches.
 
How does that sound?
 
I just got back from taking ADM-231 and I am trying to put what i learned in to practices. We have some custom code that I need to edit. I can kind of tell what it says now but still not sure.

I need to edit it so that it does not up date  "CampaignId" unless HasResponded = True in the CampaignMember sObject. 
Any help would be great.
 
trigger Opportunity on Opportunity (after delete, after insert, after undelete, after update, before delete, before insert, before update) {
    if(trigger.isBefore){
        if(trigger.isInsert){
   
           /////////// non bulk trigger
           if(trigger.new.size() > 1){
            return;
           }
           /////////// non bulk trigger
         
           Opportunity o = trigger.new[0];
           System.debug('Akash --> o:' + o);
            System.debug('Akash --> 1:' + o.ECi_Product__c);
           
         
           if((o.Type_of_Sale__c == 'New System' || o.Type_of_Sale__c == 'Aftermarket')){
                
                list<Contact> lstContact = [Select Id From Contact Where AccountId = :o.AccountId ];
               list<Lead> lstLead = [Select Id From Lead Where Id  =: o.Leadid__c ];
               String soql = ' Select Id,CampaignId,Campaign.Type,Response_Tracking_Date__c, Campaign.Type_of_sale__c ';
               soql += ' From CampaignMember ';
               soql += ' Where Campaign.ECi_Product__c = \'' + o.ECi_Product__c + '\' and Campaign.Type_of_sale__c = \''+ o.Type_of_Sale__c+'\'';
               
               System.debug('Akash --> lstContact:' +lstContact);
               System.debug('anuj--> LstLead:' +lstLead);
               /*    
               if(o.Type_of_Sale__c == 'Aftermarket'){
                soql += ' And Campaign.ECi_Aftermarket__c = \'' + o.ECi_Aftermarket__c + '\'';
               }
                */
               soql += ' And Status = \'Responded\'';
               soql += ' And Response_Tracking_Date__c != null';
               soql += ' And ( ContactId In :lstContact OR LeadId In :lstLead )';
               soql += ' Order By Response_Tracking_Date__c Desc';
                
               System.debug('Akash --> soql:' + soql);
               List<CampaignMember> cmList = new List<CampaignMember>();
               cmList = Database.Query(soql);
               if(cmList.size() > 0){
                   for(CampaignMember cm: cmList){
                     
                       System.debug('Akash --> cm:' + cm);
                       System.debug('Akash --> cm.Campaign.Type:' + cm.Campaign.Type);
                         
                       Campaign_Type_Time_Mapping__c cttm = Campaign_Type_Time_Mapping__c.getall().get(cm.Campaign.Type); 
                    
                      
                         
                       if(cttm != null && cttm.Value__c != null){
                         
                           DateTime startDT = DateTime.now(); 
                           DateTime EndDT = DateTime.now();
                             
                           
                             
                           if(cttm.Type__c == 'Year'){
                                startDT = startDT.addYears(-1*Integer.valueOf(cttm.Value__c));
                           }else if(cttm.Type__c == 'Month'){
                                startDT = startDT.addMonths(-1*Integer.valueOf(cttm.Value__c));
                           }else if(cttm.Type__c == 'Day'){
                                startDT = startDT.addDays(-1*Integer.valueOf(cttm.Value__c));
                           }
                             
                           System.debug('Akash --> startDT:' + startDT);
                           System.debug('Akash --> EndDT:' + EndDT);
                            
                           if(cm.Response_Tracking_Date__c >= startDT && cm.Response_Tracking_Date__c <= EndDT){
                                
                               System.debug('Akash --> cm.Response_Tracking_Date__c:' + cm.Response_Tracking_Date__c);
                               System.debug('Akash --> startDT:' + startDT);
                               System.debug('Akash --> EndDT:' + EndDT);
                                    
                               o.CampaignId = cm.CampaignId;
                               System.debug('Akash --> oppor \n' + o);
                               break;
                           }
                       }
                   }
               }else{
                    o.CampaignId = null;
               }    
           }
        }
    }
}

 
I need to edit this SQOL query in this code so that it only looks at task that are (status = complet) and (Type = up to 6 diffrent values)" I asume I need to use a or statmnet but I am having no luck getting it to work. I also need to remove the part were it looks for Events. I am haveing no luck with this any help would be great. 

 
public with sharing class OpportunityCallActivityCount {
 
public static Boolean didRun = false;
public static String oppPrefix = Opportunity.sObjectType.getDescribe().getKeyPrefix();
 
/*
* Takes a set of opportunity IDs, queries those opportunities, and updates the activity count if appropriate
*/
public static void updateOpportunityCounts(Set<ID> oppIds) {
 
if (didRun == false) { //We only want this operation to run once per transaction.
didRun = true;
 
//Query all the opportunites, including the tasks child relationships
List<Opportunity> opps = [SELECT ID, Email_Activities__c, (SELECT ID FROM Tasks where Type='Email' AND Status='Completed'), (SELECT ID FROM Events) FROM Opportunity WHERE ID IN :oppIds];
List<Opportunity> updateOpps = new List<Opportunity>();
 
for (Opportunity o : opps) {
Integer count = o.tasks.size() + o.events.size();
 
if (o.Call_Activity__c != count) {
o.Call_Activity__c = count;
updateOpps.add(o); //we're only doing updates to opps that have changed...no need to modify the others
}
}
 
//Update the appropriate opportunities
try {
update updateOpps;
} catch (Exception e) {
//This is controversial. Anything could happen when updating the opportunity..validation rule, security, etc. The key is we don't
//want the event update to fail...so we put a try catch around the opp update to make sure we don't stop that from happening.
}
}
}
}

 
I need to make a trigger on the opportunity object that Adds +1 to a custom filed on the user object every time an opportunity that the user owns has the "Date qualified" filed changed from null to having a date. 

I tired making a workflow but the field update cant cross to the user object. And I am not sure were to start on this code any help would be great.
I am trying to creat a map to grap the product ID that are added to the "opportunityLineItem" opject so I can show list price on a VF page. I am getting a error when trying to svae the code. 

"Error: Compile Error: No such column 'ProductId' on entity 'PricebookEntry'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. at line 209 column 66"

Am I using the wrong object?
public Map<Id, Double> listPriceMap {get; private set;}  

List<PricebookEntry> pricebookEntries = new List<PricebookEntry>([select Id, ProductId, UnitPrice from PricebookEntry where ProductId in :productIds]);
listPriceMap = new Map<Id, Double>(); 
for (PricebookEntry pbe : pricebookEntries) {  
    listPriceMap.put(pbe.ProductId, pbe.UnitPrice);

 
I am trying to edit this code so when I add a product it will add 2 custom fileds to the opprtuinty line item. " A formula field on Price book entery "Type_c" =Text (Product2.Product_Type__c) and a check box "Needs_Approval__c"  I can't seem to get it added with out an error.  

public void addToShoppingCart(){
    
        // This function runs when a user hits "select" button next to a product
    
        for(PricebookEntry d : AvailableProducts){
            if((String)d.Id==toSelect){
                shoppingCart.add(new opportunityLineItem(OpportunityId=theOpp.Id, PriceBookEntry=d, PriceBookEntryId=d.Id, UnitPrice=d.UnitPrice, ));
                break;
            }
        }
        
        updateAvailableList();  
    }
I have been playing around with a VF page and I can't figure out why i am getting this error the code saves fine. I did not write the code I am just trying to edit it. 

Here is the VF code  I underlined and bolded the code I added 


I have been playing around with a VF page and I can't figure out why i am getting this error the code saves fine. I did not write the code I am just trying to edit it.
 
 
<apex:page standardController="Opportunity" extensions="opportunityProductEntryExtension" action="{!priceBookCheck}" >
 
    <apex:sectionHeader Title="Manage {!$ObjectType.Product2.LabelPlural}" subtitle="{!opportunity.Name}"/>
    <apex:messages style="color:red"/>
 
    <style>
        .search{
            font-size:14pt;
            margin-right: 20px;   
        }
        .fyi{
            color:red;
            font-style:italic;
        }
        .label{
            margin-right:10px;
            font-weight:bold;
        }
    </style>
   
    <script type='text/javascript'>
   
        // This script assists the search bar functionality
        // It will execute a search only after the user has stopped typing for more than 1 second
        // To raise the time between when the user stops typing and the search, edit the following variable:
       
        var waitTime = 1;
       
   
        var countDown = waitTime+1;
        var started = false;
       
        function resetTimer(){
       
            countDown=waitTime+1;
           
            if(started==false){
                started=true;
                runCountDown();
            }
        }
       
        function runCountDown(){
       
            countDown--;
           
            if(countDown<=0){
                fetchResults();
                started=false;
            }
            else{
                window.setTimeout(runCountDown,1000);
            }
        }
   
    </script>
  
 
    <apex:form >
   
        <apex:outputPanel id="mainBody">
       
            <apex:outputLabel styleClass="label">PriceBook: </apex:outputLabel>
            <apex:outputText value="{!theBook.Name}"/>&nbsp;
            <apex:commandLink action="{!changePricebook}" value="change" immediate="true"/>
            <br/>
            <!-- not everyone is using multi-currency, so this section may or may not show -->
            <apex:outputPanel rendered="{!multipleCurrencies}">
                <apex:outputLabel styleClass="label">Currency: </apex:outputLabel>
                <apex:outputText value="{!chosenCurrency}"/>
                <br/>
            </apex:outputPanel>
            <br/>
           
<!-- this is the upper table... a.k.a. the "Shopping Cart"-->
 
            <!-- notice we use a lot of $ObjectType merge fields... I did that because if you have changed the labels of fields or objects it will reflect your own lingo -->
            <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected">
                      
                <apex:pageblockTable value="{!shoppingCart}" var="s">
                <apex:column >
                        <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">
                            <!-- this param is how we send an argument to the controller, so it knows which row we clicked 'remove' on -->
                            <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                        </apex:commandLink>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                        <apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                      <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Product_Type__c.label}">
                        <apex:inputField value="{!s.Product_Type__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Terms__c.label}">
                        <apex:inputField value="{!s.Terms__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Tearms_Legth__c.label}">
                        <apex:inputField value="{!s.Tearms_Legth__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                        <apex:inputField value="{!s.UnitPrice}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Description.Label}">
                        <apex:inputField value="{!s.Description}" required="false"/>
                    </apex:column>
                   
                </apex:pageblockTable>
           
           
                <apex:pageBlockButtons >
                    <apex:commandButton action="{!onSave}" value="Save"/>
                    <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
                </apex:pageBlockButtons>
           
            </apex:pageBlock>
   
<!-- this is the lower table: search bar and search results -->
   
            <apex:pageBlock >
           
                <apex:outputPanel styleClass="search">
                    Search for {!$ObjectType.Product2.LabelPlural}:
                </apex:outputPanel>
 
                <apex:actionRegion renderRegionOnly="false" immediate="true">
               
                    <apex:actionFunction name="fetchResults" action="{!updateAvailableList}" reRender="searchResults" status="searchStatus"/>
                    
                    <!-- here we invoke the scripting to get out fancy 'no button' search bar to work -->
                    <apex:inputText value="{!searchString}" onkeydown="if(event.keyCode==13){this.blur();}else{resetTimer();}" style="width:300px"/>
                    &nbsp;&nbsp;
                    <i>
                        <!-- actionStatus component makes it easy to let the user know when a search is underway -->
                        <apex:actionStatus id="searchStatus" startText="searching..." stopText=" "/>
                    </i>
                   
                </apex:actionRegion>
           
                <br/>
                <br/>
           
                <apex:outputPanel id="searchResults">
               
                    <apex:pageBlockTable value="{!AvailableProducts}" var="a">
                   
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Name.Label}" value="{!a.Product2.Name}" />
                       
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Family.Label}" value="{!a.Product2.Family}"/>
                       
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Description.Label}" value="{!a.Product2.Description}"/>

                       
                         <apex:column headerValue="{!$ObjectType.Product2.Fields.Product_Type__c.Label}" value="{!a.Product2.Product_Type__c}"/>
                       
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Terms__c.Label}" value="{!a.Product2.Terms__c}"/>
                       
                        <apex:column >
                            <!-- command button in a column... neato -->
                            <apex:commandButton value="Select" action="{!addToShoppingCart}" reRender="selected,searchResults" immediate="true">
                                <!-- again we use apex:param to be able to tell the controller which row we are working with -->
                                <apex:param value="{!a.Id}" assignTo="{!toSelect}" name="toSelect"/>
                            </apex:commandButton>
                        </apex:column>
                       
                    </apex:pageBlockTable>
                   
                    <!-- We put up a warning if results exceed 100 rows -->
                    <apex:outputPanel styleClass="fyi" rendered="{!overLimit}">
                        <br/>
                        Your search returned over 100 results, use a more specific search string if you do not see the desired {!$ObjectType.Product2.Label}.
                        <br/>
                    </apex:outputPanel>
                    
                </apex:outputPanel>
           
            </apex:pageBlock>
           
        </apex:outputPanel>
 
    </apex:form>
 
</apex:page>
 
I am trying to write a trigger that will send a Opportuinty to approval when the stage is set to "send to accountig" I dot get a error when I save the code but it does not work and I am not sure why. 

trigger OpportunitySubmitForApproval2 on Opportunity (after update) {

for (Opportunity opp : Trigger.new){

if (opp.Stagename =='Sent To Accounting'){
    Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
    
}
}
}
 
I am having a problem with the before insert part of this trigger I think. The problem is  when a new lead or contact is added to the campain member object. The below trigger does not work it only seems to work right when a update to a exsting campain record object. I dont know were to start trying to fix it. 
 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
// Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];

for (CampaignMember member : Trigger.New) {
    for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
        if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
            kpiTarget.ECI_Product__c == member.ECI_Product__c &&
            kpiTarget.CurrencyIsoCode == member.Currency__c &&
            kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
            kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
            member.HasResponded == True)
        {
            member.Marketing_KPI_Target__c = kpiTarget.Id;
            continue;
        }
    }
}
}

 
I am having a problem with the timing of this trigger. Here is the scenario that cuases it not to work right.

When you add a Lead or Contact as a Campain Memebr and you set the  Response_Tracking_date__c from Null to a date the trigger does not fire off. It will fire if you edit the same recored and save it again no problem or if you just leave Response_Tracking_date__c blank and let the system fill it out. 

I think it has something to do with it being "before Insert" I am guessing the new info in  Response_Tracking_date__c is not there to look at when the trigger fires off. I tired adding "after Insert" but get errror " execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.CampaignMemberTrigger: line 15, column 1"
 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update, after insert) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.Currency__c &&
               	member.Response_Tracking_date__c != Null &&
                kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}



 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.Currency__c &&
               	member.Response_Tracking_date__c != Null &&
                kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}

 
I need to link "Campaign Members" to a custom object "KPITarget" based on values of both objects using a lookup field. 
The conditions are based on vales from both objects 3 fields that need to match on both objects and a date fields that just needs the month and year to mach. The last thing is the "HasResponded" field must be true on Campaign member.

I think this needs to be a class called by a Trigger but I am not sure since there will be no link between the objects at the start.
Create a List of all Campaign Member Id's getting the values of the 3 fields, Date Range and, HasResponded That the trigger fires off.
Create a List of all KPITargets Id’s that match the values of the Campaign Member, There should only be one.
The update the look up field on Campaign member with the ID of the KPITarget that matches.
 
How does that sound?
 
I just got back from taking ADM-231 and I am trying to put what i learned in to practices. We have some custom code that I need to edit. I can kind of tell what it says now but still not sure.

I need to edit it so that it does not up date  "CampaignId" unless HasResponded = True in the CampaignMember sObject. 
Any help would be great.
 
trigger Opportunity on Opportunity (after delete, after insert, after undelete, after update, before delete, before insert, before update) {
    if(trigger.isBefore){
        if(trigger.isInsert){
   
           /////////// non bulk trigger
           if(trigger.new.size() > 1){
            return;
           }
           /////////// non bulk trigger
         
           Opportunity o = trigger.new[0];
           System.debug('Akash --> o:' + o);
            System.debug('Akash --> 1:' + o.ECi_Product__c);
           
         
           if((o.Type_of_Sale__c == 'New System' || o.Type_of_Sale__c == 'Aftermarket')){
                
                list<Contact> lstContact = [Select Id From Contact Where AccountId = :o.AccountId ];
               list<Lead> lstLead = [Select Id From Lead Where Id  =: o.Leadid__c ];
               String soql = ' Select Id,CampaignId,Campaign.Type,Response_Tracking_Date__c, Campaign.Type_of_sale__c ';
               soql += ' From CampaignMember ';
               soql += ' Where Campaign.ECi_Product__c = \'' + o.ECi_Product__c + '\' and Campaign.Type_of_sale__c = \''+ o.Type_of_Sale__c+'\'';
               
               System.debug('Akash --> lstContact:' +lstContact);
               System.debug('anuj--> LstLead:' +lstLead);
               /*    
               if(o.Type_of_Sale__c == 'Aftermarket'){
                soql += ' And Campaign.ECi_Aftermarket__c = \'' + o.ECi_Aftermarket__c + '\'';
               }
                */
               soql += ' And Status = \'Responded\'';
               soql += ' And Response_Tracking_Date__c != null';
               soql += ' And ( ContactId In :lstContact OR LeadId In :lstLead )';
               soql += ' Order By Response_Tracking_Date__c Desc';
                
               System.debug('Akash --> soql:' + soql);
               List<CampaignMember> cmList = new List<CampaignMember>();
               cmList = Database.Query(soql);
               if(cmList.size() > 0){
                   for(CampaignMember cm: cmList){
                     
                       System.debug('Akash --> cm:' + cm);
                       System.debug('Akash --> cm.Campaign.Type:' + cm.Campaign.Type);
                         
                       Campaign_Type_Time_Mapping__c cttm = Campaign_Type_Time_Mapping__c.getall().get(cm.Campaign.Type); 
                    
                      
                         
                       if(cttm != null && cttm.Value__c != null){
                         
                           DateTime startDT = DateTime.now(); 
                           DateTime EndDT = DateTime.now();
                             
                           
                             
                           if(cttm.Type__c == 'Year'){
                                startDT = startDT.addYears(-1*Integer.valueOf(cttm.Value__c));
                           }else if(cttm.Type__c == 'Month'){
                                startDT = startDT.addMonths(-1*Integer.valueOf(cttm.Value__c));
                           }else if(cttm.Type__c == 'Day'){
                                startDT = startDT.addDays(-1*Integer.valueOf(cttm.Value__c));
                           }
                             
                           System.debug('Akash --> startDT:' + startDT);
                           System.debug('Akash --> EndDT:' + EndDT);
                            
                           if(cm.Response_Tracking_Date__c >= startDT && cm.Response_Tracking_Date__c <= EndDT){
                                
                               System.debug('Akash --> cm.Response_Tracking_Date__c:' + cm.Response_Tracking_Date__c);
                               System.debug('Akash --> startDT:' + startDT);
                               System.debug('Akash --> EndDT:' + EndDT);
                                    
                               o.CampaignId = cm.CampaignId;
                               System.debug('Akash --> oppor \n' + o);
                               break;
                           }
                       }
                   }
               }else{
                    o.CampaignId = null;
               }    
           }
        }
    }
}

 
I am trying to edit this code so when I add a product it will add 2 custom fileds to the opprtuinty line item. " A formula field on Price book entery "Type_c" =Text (Product2.Product_Type__c) and a check box "Needs_Approval__c"  I can't seem to get it added with out an error.  

public void addToShoppingCart(){
    
        // This function runs when a user hits "select" button next to a product
    
        for(PricebookEntry d : AvailableProducts){
            if((String)d.Id==toSelect){
                shoppingCart.add(new opportunityLineItem(OpportunityId=theOpp.Id, PriceBookEntry=d, PriceBookEntryId=d.Id, UnitPrice=d.UnitPrice, ));
                break;
            }
        }
        
        updateAvailableList();  
    }
I have been playing around with a VF page and I can't figure out why i am getting this error the code saves fine. I did not write the code I am just trying to edit it. 

Here is the VF code  I underlined and bolded the code I added 


I have been playing around with a VF page and I can't figure out why i am getting this error the code saves fine. I did not write the code I am just trying to edit it.
 
 
<apex:page standardController="Opportunity" extensions="opportunityProductEntryExtension" action="{!priceBookCheck}" >
 
    <apex:sectionHeader Title="Manage {!$ObjectType.Product2.LabelPlural}" subtitle="{!opportunity.Name}"/>
    <apex:messages style="color:red"/>
 
    <style>
        .search{
            font-size:14pt;
            margin-right: 20px;   
        }
        .fyi{
            color:red;
            font-style:italic;
        }
        .label{
            margin-right:10px;
            font-weight:bold;
        }
    </style>
   
    <script type='text/javascript'>
   
        // This script assists the search bar functionality
        // It will execute a search only after the user has stopped typing for more than 1 second
        // To raise the time between when the user stops typing and the search, edit the following variable:
       
        var waitTime = 1;
       
   
        var countDown = waitTime+1;
        var started = false;
       
        function resetTimer(){
       
            countDown=waitTime+1;
           
            if(started==false){
                started=true;
                runCountDown();
            }
        }
       
        function runCountDown(){
       
            countDown--;
           
            if(countDown<=0){
                fetchResults();
                started=false;
            }
            else{
                window.setTimeout(runCountDown,1000);
            }
        }
   
    </script>
  
 
    <apex:form >
   
        <apex:outputPanel id="mainBody">
       
            <apex:outputLabel styleClass="label">PriceBook: </apex:outputLabel>
            <apex:outputText value="{!theBook.Name}"/>&nbsp;
            <apex:commandLink action="{!changePricebook}" value="change" immediate="true"/>
            <br/>
            <!-- not everyone is using multi-currency, so this section may or may not show -->
            <apex:outputPanel rendered="{!multipleCurrencies}">
                <apex:outputLabel styleClass="label">Currency: </apex:outputLabel>
                <apex:outputText value="{!chosenCurrency}"/>
                <br/>
            </apex:outputPanel>
            <br/>
           
<!-- this is the upper table... a.k.a. the "Shopping Cart"-->
 
            <!-- notice we use a lot of $ObjectType merge fields... I did that because if you have changed the labels of fields or objects it will reflect your own lingo -->
            <apex:pageBlock title="Selected {!$ObjectType.Product2.LabelPlural}" id="selected">
                      
                <apex:pageblockTable value="{!shoppingCart}" var="s">
                <apex:column >
                        <apex:commandLink value="Remove" action="{!removeFromShoppingCart}" reRender="selected,searchResults" immediate="true">
                            <!-- this param is how we send an argument to the controller, so it knows which row we clicked 'remove' on -->
                            <apex:param value="{!s.PriceBookEntryId}" assignTo="{!toUnselect}" name="toUnselect"/>
                        </apex:commandLink>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.Product2.LabelPlural}" value="{!s.PriceBookEntry.Product2.Name}"/>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Quantity.Label}">
                        <apex:inputField value="{!s.Quantity}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                      <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Product_Type__c.label}">
                        <apex:inputField value="{!s.Product_Type__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Terms__c.label}">
                        <apex:inputField value="{!s.Terms__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Tearms_Legth__c.label}">
                        <apex:inputField value="{!s.Tearms_Legth__c}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                  
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.UnitPrice.Label}">
                        <apex:inputField value="{!s.UnitPrice}" style="width:70px" required="true" onkeyup="refreshTotals();"/>
                    </apex:column>
                   
                    <apex:column headerValue="{!$ObjectType.OpportunityLineItem.Fields.Description.Label}">
                        <apex:inputField value="{!s.Description}" required="false"/>
                    </apex:column>
                   
                </apex:pageblockTable>
           
           
                <apex:pageBlockButtons >
                    <apex:commandButton action="{!onSave}" value="Save"/>
                    <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
                </apex:pageBlockButtons>
           
            </apex:pageBlock>
   
<!-- this is the lower table: search bar and search results -->
   
            <apex:pageBlock >
           
                <apex:outputPanel styleClass="search">
                    Search for {!$ObjectType.Product2.LabelPlural}:
                </apex:outputPanel>
 
                <apex:actionRegion renderRegionOnly="false" immediate="true">
               
                    <apex:actionFunction name="fetchResults" action="{!updateAvailableList}" reRender="searchResults" status="searchStatus"/>
                    
                    <!-- here we invoke the scripting to get out fancy 'no button' search bar to work -->
                    <apex:inputText value="{!searchString}" onkeydown="if(event.keyCode==13){this.blur();}else{resetTimer();}" style="width:300px"/>
                    &nbsp;&nbsp;
                    <i>
                        <!-- actionStatus component makes it easy to let the user know when a search is underway -->
                        <apex:actionStatus id="searchStatus" startText="searching..." stopText=" "/>
                    </i>
                   
                </apex:actionRegion>
           
                <br/>
                <br/>
           
                <apex:outputPanel id="searchResults">
               
                    <apex:pageBlockTable value="{!AvailableProducts}" var="a">
                   
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Name.Label}" value="{!a.Product2.Name}" />
                       
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Family.Label}" value="{!a.Product2.Family}"/>
                       
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Description.Label}" value="{!a.Product2.Description}"/>

                       
                         <apex:column headerValue="{!$ObjectType.Product2.Fields.Product_Type__c.Label}" value="{!a.Product2.Product_Type__c}"/>
                       
                        <apex:column headerValue="{!$ObjectType.Product2.Fields.Terms__c.Label}" value="{!a.Product2.Terms__c}"/>
                       
                        <apex:column >
                            <!-- command button in a column... neato -->
                            <apex:commandButton value="Select" action="{!addToShoppingCart}" reRender="selected,searchResults" immediate="true">
                                <!-- again we use apex:param to be able to tell the controller which row we are working with -->
                                <apex:param value="{!a.Id}" assignTo="{!toSelect}" name="toSelect"/>
                            </apex:commandButton>
                        </apex:column>
                       
                    </apex:pageBlockTable>
                   
                    <!-- We put up a warning if results exceed 100 rows -->
                    <apex:outputPanel styleClass="fyi" rendered="{!overLimit}">
                        <br/>
                        Your search returned over 100 results, use a more specific search string if you do not see the desired {!$ObjectType.Product2.Label}.
                        <br/>
                    </apex:outputPanel>
                    
                </apex:outputPanel>
           
            </apex:pageBlock>
           
        </apex:outputPanel>
 
    </apex:form>
 
</apex:page>
 
I am trying to write a trigger that will send a Opportuinty to approval when the stage is set to "send to accountig" I dot get a error when I save the code but it does not work and I am not sure why. 

trigger OpportunitySubmitForApproval2 on Opportunity (after update) {

for (Opportunity opp : Trigger.new){

if (opp.Stagename =='Sent To Accounting'){
    Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
    
}
}
}
 

How can I reassign the Amount value on the Opportunity to each a custom field?  My goal is to have Forecast see our Net Revenue field from the opportunity page.