• iKnowSFDC
  • NEWBIE
  • 195 Points
  • Member since 2012
  • Principal
  • iKnowledge


  • Chatter
    Feed
  • 7
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 30
    Questions
  • 47
    Replies

Hi All,

        

I have create custom User lookup field in Account,Field Name is SalesRep.When i select user name(John) and save the account.  Opportunity Owner name chanege as (john) on Opportunity in the Account

 

I can't deploy it to production because I'm not able to create a test class for it... . The code is below, can someone help me build a test class for it? 

 

trigger Opportunity_SalesRep on Account(after update) {
     List<Id> accIds = new List<Id>(); 
     for(Account acc : trigger.New){
         //check if salesrep changed
         if(acc.EXO_Sales_Rep__c != trigger.oldMap.get(acc.Id).EXO_Sales_Rep__c){
              accIds.add(acc.Id);
         }
     }
    //query all the matching opps
    List<Opportunity > oppList = [SELECT Id,AccountId FROM Opportunity WHERE AccountId IN:accIds];

    for(Opportunity opp : oppList ){
    if(trigger.NewMap.containsKey(opp.AccountId)&&
trigger.NewMap.get(opp.AccountId).EXO_Sales_Rep__c != null){
          opp.OwnerId = trigger.NewMap.get(opp.AccountId).EXO_Sales_Rep__c;
          }
 }
     
 update oppList; 
}

Hi All

 

my need is i want to create a formula field it displays current month name...is it possible to display current month  name using formula field??

 

Thanks,

Jake

  • November 05, 2012
  • Like
  • 0
Hi All,

I'm working on some test code for a trigger that flags a check box is the owner's user role and the invitee user role are part of a list defined in a custom setting. The trigger works as expected, however, when testing the trigger, I am not getting the isGroupEvent flag to populate. I've found several posts around this issue, but the solutions posted have not worked for me. Below is the code, any suggestions would be VERY appreciated.
 
@isTest
private class testEventUpdateTrigger {
    
    private testMethod static void testEventTrigger(){
        //find users with appropriate roles to generate joint meeting flag
        User BHFAUser = [SELECT id, UserRoleId, UserRole.Name FROM User WHERE UserRole.Name = 'Financial Advisor BHFA - Arizona FA' LIMIT 1];
        User preferredUser = [SELECT id, UserRoleId, UserRole.Name FROM User WHERE UserRole.Name = 'Preferred - AZ Premier Bankers' LIMIT 1];
        
        //test 1 - insert an event & verify that the joint meeting flag was set to false.
        system.runAs(BHFAUser){
            Event e1 = new Event(Subject='Test', StartDateTime = date.today(), DurationInMinutes = 60);
            insert e1;
            system.assert(!e1.Joint_Meeting__c);
            
            //Add an Event Relation Record
            EventRelation er1 = new EventRelation(EventId = e1.id, RelationId = preferredUser.id, IsInvitee=true,
                                                 Status='New');
            insert er1;
           	
            e1.Description = 'invited new user';
            update e1;

            system.debug('is group event flag>>>'+e1.IsGroupEvent);
            
            //this assert is failing
            system.assert(e1.Joint_Meeting__c);
            
        }
    }
    

}

 
I'm having an issue with some code - this code was written by a previous contractor but I'm updating it to support a larger data set and to provide a more usable interface.  Currently, the list of products is displayed and the user can select the product they are registering and the quantity. The list is very large, over 1000 which is a problem in and of itself.

The change I'm trying to make is to provide the user a product group (in this case a custom field on the product2 object called Forecast__c) and to give the user a smaller list of products associated with that category. 

The solution is adding records to a custom object (Registration_Product__c) that is linked via a master-detail relationship to a Parent object (Deal_Registration__c). 

The issue I"m having is when a second line item is added, the product group is defaulted to the first line item's group. 

Here is controller: 
 
public with sharing class ProductController {
    public Deal_Registration__c dealReg { get; private set; }
    private Integer nextId = 0;
    private String selectedId;
    public Boolean error {get; private set;}
    public Boolean testLimit {get; set;}

    public List<ProductRow> productRows { get; private set; } 
    private List<Registration_Product__c> deleted = new List<Registration_Product__c>();
    private List<SelectOption> productOptions = null;
    private List<SelectOption> productCapacities = null;
    
    
    Public String currentProduct {get;set;}
    Public String currentProductFamily {get;set;}


    public ProductController(ApexPages.StandardController controller) {
    	this.testLimit = false;
        final String dealRegProductId = ApexPages.currentPage().getParameters().get('id');
        final String dealRegId = ApexPages.currentPage().getParameters().get('dealRegId');
        System.debug('dealRegProductId:' + dealRegProductId);
        System.debug('dealRegId:' + dealRegId);
        if (dealRegProductId != null) {
            Registration_Product__c dealRegProduct = [Select Product__c, Storage_Capacity__c, 
                                                      Deal_Registration__c, Product__r.Forecast__c
                                                      from Registration_Product__c 
                                                      where Id = :dealRegProductId order by CreatedDate ];
            this.dealReg = [SELECT Name, Registration_Status__c FROM Deal_Registration__c WHERE Id = :dealRegProduct.Deal_Registration__c];         
        } else if (dealRegId != null) {
            this.dealReg = [Select Name, Registration_Status__c from Deal_Registration__c where Id =:dealRegId];
        } else {
            Registration_Product__c dealRegProduct = (Registration_Product__c) controller.getRecord();
            this.dealReg = [Select Name, Registration_Status__c from Deal_Registration__c where Id = :dealRegProduct.Deal_Registration__c];
        }
       
        productRows = new List<ProductRow>();
        productCapacities = new List<SelectOption>();
        error = false;
    }

    
    public PageReference onLoad() {
        System.debug('dealreg:' + dealReg);
        String status = this.dealReg.Registration_Status__c;
        System.debug('dealreg.status:' + status);
        if (status == null) status = '';
        if (status.equals('Submitted') || 
            status.equals('Approved'))  
        {
            ApexPages.Message m =new ApexPages.Message(ApexPages.Severity.ERROR, 'Deal Registration is locked and cannot be edited.'); 
            ApexPages.addMessage(m);
            error = true;
            return null;
        }
        for (Registration_Product__c dealRegProd : [SELECT Product__c, Storage_Capacity__c, Quantity__c, 
                                                    Deal_Registration__c 
                                                    FROM Registration_Product__c 
                                                    WHERE Deal_Registration__c = :dealReg.Id order by CreatedDate]) {
            nextId++;
            productRows.add(new ProductRow(String.valueOf(nextId), dealRegProd));
        }
        
        if (productRows.size() == 0) {
            nextId++;
            productRows.add(new ProductRow(String.valueOf(nextId), new Registration_Product__c()));
        }
        
        return null;
    }
    //New method added to support new product selector: 11/17/14
    Public List<SelectOption> getListGroups(){  
        List<SelectOption> options=New List<SelectOption> {new SelectOption('','-- Choose')};
        for(Schema.pickListEntry pe:Product2.Forecast__c.getDescribe().getpickListValues()){
            options.add(new SelectOption(pe.getValue(),pe.getLabel()));
        }
        return options;
    }

    //New method added to support new product selector: 11/17/14
    Public List<SelectOption> getListProducts(){
        List<SelectOption> options=New List<SelectOption>();
        if(currentProductFamily == null || currentProductFamily == ''){
            return options;
        }
        options.add(new SelectOption('','-- Choose --'));
        for(Product2 p2:[SELECT id, Name FROM Product2 
                         WHERE Forecast__c = : currentProductFamily 
                         AND isActive = TRUE 
                         AND Visible_in_Portal__c = TRUE
                         ORDER BY Name]) {
            options.add(new SelectOption(p2.id,p2.name));
        }
        return options;
        return Null;
    }
    
	
    /* *****Old product list 
	public List<SelectOption> getProductOptions() {
        if (productOptions == null) {
            productOptions = new List<SelectOption>();
            List<Product2> productList = null;
            productList = [Select Name from Product2 where isActive = true order by name ];
            if(productList.size()>1000){
                testLimit = true;
            }
            if (this.testLimit) {
            	productList = [Select Name from Product2 where isActive = true AND Visible_in_Portal__c = true order by name limit 1000];
            } else {
            	productList =[Select Name from Product2 where isActive = true AND Visible_in_Portal__c = true order by name];
            }
            for (Product2 p : productList) {
                productOptions.add(new SelectOption(p.Id, p.Name));
            }
        }
        return productOptions;
    }*/
    
    public List<SelectOption> getProductCapacities() {
        transient Schema.DescribeFieldResult F = Registration_Product__c.Storage_Capacity__c.getDescribe();
        transient List<Schema.Picklistentry> plValues = F.getPicklistValues();
        productCapacities.add(new SelectOption('none', 'none'));
        for(Schema.Picklistentry value : plValues){
            productCapacities.add(new SelectOption(value.getValue(), value.getLabel()));
        }

        return productCapacities;
    }
    
    public PageReference onAddCondition() {
        String selectedId = ApexPages.currentPage().getParameters().get('selectedId');
        System.debug('selectedId --- onAddCondition---------->'+ selectedId);
        if (selectedId != null) {
            for (Integer i=0;i<productRows.size();i++) {
                ProductRow row = productRows.get(i);
                if (row.getId().equals(selectedId)) {
                    nextId++;
                    Registration_Product__c prod = new Registration_Product__c();
                    prod.Quantity__c = 1;
                    if (i == (productRows.size() - 1)) {
                        productRows.add(new ProductRow(String.valueOf(nextId), prod));
                    } else {
                        productRows.add(i + 1, new ProductRow(String.valueOf(nextId), prod));
                    }
                    return null;
                }
            }
        }
        return null;
    }
    
    public PageReference onRemoveCondition() {
        String selectedId = ApexPages.currentPage().getParameters().get('selectedId');
        System.debug('selectedId --- onRemoveCondition---------->'+ selectedId);
        if (selectedId != null) {
            for (Integer i = 0; i < productRows.size(); i++) {
                ProductRow row = productRows.get(i);
                if (row.getId().equals(selectedId)) {
                    productRows.remove(i);
                    if (row.getDealRegProduct().Id != null) {
                        deleted.add(row.getDealRegProduct());
                    }
                    return null;
                }
            }
        }
        return null;
    }
    
    public PageReference onSave() {
        delete deleted;
        try {
            List<Registration_Product__c> batch = new List<Registration_Product__c>();
            for (ProductRow row : productRows) {
                Registration_Product__c prod = row.getDealRegProduct();
                if (prod.Id == null) {
                    prod.Deal_Registration__c = dealReg.Id;
                }
                batch.add(prod);
            }
        	upsert batch;
        }
        catch (Exception e) {
            ApexPages.addMessages(e); 
            return null;
        }
        
        return new PageReference('/' + dealReg.Id);
    }
    
    
    public PageReference onCancel() {
        return new PageReference('/' + dealReg.Id);
    }
     
        
    public class ProductRow {
        private String id;
        private Registration_Product__c dealRegProduct;
        
        public ProductRow(String id, Registration_Product__c dealRegProduct) {
            this.id = id;
            this.dealRegProduct = dealRegProduct;
        }
        
        public String getId() {
            return id;
        }
        
        public Registration_Product__c getDealRegProduct() {
            return dealRegProduct;
        }
        
    }
}

VisualForce Code: 
 
<apex:page standardController="Registration_Product__c" extensions="ProductController" action="{!onLoad}" >
    
    <apex:sectionHeader title="{!$Label.addEditProds}" subtitle="{!dealReg.Name}"/>

    <apex:form >
        <apex:pageBlock >
        <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton action="{!onSave}" value="{!$Label.Save}" rendered="{!NOT(error)}" />
                <apex:commandButton action="{!onCancel}" immediate="true" value="{!$Label.Cancel}"/>
            </apex:pageBlockButtons>
            
            
            <apex:pageBlockTable id="row" value="{!productRows}" var="row" rendered="{!NOT(error)}">
                <apex:column >
                    <apex:outputPanel >
                        <apex:commandButton action="{!onAddCondition}" immediate="false" reRender="row" value="+">
                            <apex:param name="selectedId" value="{!row.id}"/>
                        </apex:commandButton>
                        <apex:commandButton action="{!onRemoveCondition}" immediate="false" reRender="row" value="-">
                            <apex:param name="selectedId" value="{!row.id}"/>
                        </apex:commandButton>
                    </apex:outputPanel>
                </apex:column>
                <apex:column headerValue="{!$Label.Quantity}">
                    <apex:inputField value="{!row.dealRegProduct.Quantity__c}" required="true"/>
                </apex:column>
                <apex:column headerValue="Product Family">
                	<apex:outputPanel>
                    	<apex:SelectList value="{!currentProductFamily}" size="1" multiselect="False" >                            
                              <apex:selectOptions value="{!ListGroups}"/>                                 
                                  <apex:actionsupport rerender="theProducts" event="onchange" status="loadingProducts" />
                         </apex:SelectList>   
                    </apex:outputPanel>
                </apex:column>
                <apex:column headerValue="{!$Label.Product}">
                    <apex:actionstatus startStyleClass="statusMessage" startText="Please Wait,Loading Products.." id="loadingProducts"/>
                    <apex:outputPanel id="theProducts">
                        <apex:SelectList value="{!row.dealRegProduct.Product__c}" size="1" multiselect="false" >
                            <apex:selectOptions value="{!listProducts}"/>
                        </apex:SelectList>
                    </apex:outputPanel>
                </apex:column>
                <!-- Old Product selection 
					<apex:column headerValue="{!$Label.Product}">
                    <apex:selectList size="1" value="{!row.dealRegProduct.Product__c}" required="true">
                        <apex:selectOptions value="{!productOptions}"/>
                    </apex:selectList>
                </apex:column>
               ****Capacity view not being utilized currently*****
                <apex:column headerValue="Capacity">
                    <apex:selectList size="1" value="{!row.dealRegProduct.Storage_Capacity__c}" required="false">
                        <apex:selectOptions value="{!productCapacities}"/>
                    </apex:selectList>
                </apex:column>-->
                
                
            </apex:pageBlockTable> 
        </apex:pageBlock>

    </apex:form>
    
</apex:page>

 
Hi,

I need to render the background color of a cell based on the value in the cell. The value is retrieved from the a map generated by the controller. The background color will be one of seven colors based on the value retrieved. I have a method written that sets the value of the color as a string and takes the value of the rendered double as an arguement.

It's returning an error "Unknown property 'heatMapController.color'. I figured out from other posts in the forum about this error  that the system is looking at the statement:

style="{!color(defendNTAPNum[o.id])}"

as a function instead of a method call, but how do I call the method and pass the value in?  The method signature is:  String getColor(Double Val)

Here is the method:
public string getColor(Double val){
        color = '';
        if(val >= 0 && val < 25){
            color='background-color:#FF0000;';
        }
        if(val >= 25 && val < 50){
            color='background-color:#FF1493;';
        }
        if(val >= 50 && val < 75){
            color='background-color:#FFB6C1;';
        }
        if(val >= 75 && val < 85){
            color='background-color:#FFFF00;';
        }
        if(val >= 85 && val < 95){
            color='background-color:#ADFF2F;';
        }
        if(val >= 95 && val < 100){
            color='background-color:#9ACD32;';
        }
        if(val == 100){
            color='background-color:#228B22;';
        }
        return color;
    }


And this is how I'm calling it:

<apex:column headervalue="SitNum" style="{!color(defendNTAPNum[o.id])}">



Thank you for your feedback!
Hi, I have a trigger in place that updates the product schedule dates if the Opportunity close date changes.  The trigger works exactly as expected, however, I'm unable to test it adequately. The test logic does not insert the default product schedules automatically, so I'm trying to insert them manually so I can generate adequate coverage. However, the code fails on insert when I try to insert the OpportunityProductSchedule record, the error is: 

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

When I looked up the Object reference for OpportunityLineItemSchedule, it shows as createable so I'm not sure what the issue is - anyone been able to test product schedules? All of the posts I found it looks like other people are having the same issues and am not finding any resolutions posted. 

APEX Trigger and Class: 
trigger updateProdScheduleTrigger on Opportunity (after update) {
   
    Set<id> olisIds = new Set<id>();
    Set<id> opptyIds = new Set<id>();
   
    for(Opportunity o : trigger.new){
        if(o.CloseDate != trigger.oldMap.get(o.id).CloseDate){
     opptyIds.add(o.id);
        }
    }
    if(!opptyIds.isEmpty()){
    List<OpportunityLineItem> oli = [SELECT id FROM OpportunityLineItem WHERE OpportunityId IN :opptyIds AND HasRevenueSchedule = TRUE];
        if(!oli.isEmpty()){
            for(OpportunityLineItem olis : oli){
                olisIds.add(olis.id);
            }
        }
        updateProductSchedule.updateSchedule(olisIds);
    }

}

public class updateProductSchedule{
   
   
    public static void updateSchedule(Set<id> olisIds){
       
        List<OpportunityLineItem> olis = [SELECT id, OpportunityId, Opportunity.CloseDate, UnitPrice
                                          FROM OpportunityLineItem
                                          WHERE Id IN :olisIds];
        Map<String, Date> lineCloseDate = new Map<String, Date>();
        for(OpportunityLineItem o : olis){
            lineCloseDate.put(o.id, o.Opportunity.CloseDate);
        }
       
        List<OpportunityLineItemSchedule> oliSchedules = new List<OpportunityLineItemSchedule>();
       
  oliSchedules = [SELECT id, ScheduleDate, OpportunityLineItemId, Quantity, Revenue, Type, OpportunityLineItem.UnitPrice,
                        OpportunityLineItem.OpportunityId, OpportunityLineItem.Opportunity.CloseDate
                        FROM OpportunityLineItemSchedule
                        WHERE OpportunityLineItemId IN :olisIds ORDER BY ScheduleDate ASC];
      
        for(OpportunityLineItemSchedule os : oliSchedules){
            system.debug('current os schedule date>>>'+os.ScheduleDate +  ' and revenue>>>'+os.Revenue);
        }
   List<OpportunityLineItemSchedule> olischedToUpdate = new List<OpportunityLineItemSchedule>();       
       
       
        Date newStartSchedDate = oliSchedules[0].OpportunityLineItem.Opportunity.CloseDate;
        Decimal newREvScheduleAmt = oliSchedules[0].OpportunityLineItem.UnitPrice / 12;
        for(Integer i = 0; i<oliSchedules.size(); i++){
            oliSchedules[i].Revenue = newRevScheduleAmt;
            oliSchedules[i].ScheduleDate = newStartSchedDate.addMonths(i);
            olischedToUpdate.add(oliSchedules[i]);
            system.debug('current os schedule date>>>'+oliSchedules[i].ScheduleDate +  ' and revenue>>>'+oliSchedules[i].Revenue);
        }
        update olischedToUpdate;
      
    }

}

TEST Code: 

@istest (seeAlldata=True)
public class testUpdateProdSchedule{
    private testmethod static void testUpdateSched(){
       
        List<Account> accts = new List<Account>();
        for(integer i=0; i<200; i++){           
            Account a = new Account(Name='test'+i);
            accts.add(a);
        }
        insert accts;
       
        List<Opportunity> opptys = new List<Opportunity>();
        for(integer i=0; i<200; i++){
            Opportunity o = new Opportunity(Name='test'+i, AccountId = accts[i].id, CloseDate=date.today().addMonths(12),
                                            Amount=0, StageName='Proposed');
            opptys.add(o);
        }
        insert Opptys;
        Set<id> opptyIds = new Set<Id>();
        for(Opportunity o : opptys){
            opptyIds.add(o.id);
        }
        PricebookEntry pbe = [SELECT id, UnitPrice, Product2.NumberOfRevenueInstallments FROM PriceBookEntry
                              WHERE isActive=True
                              AND Product2.NumberOfRevenueInstallments = 12 LIMIT 1];
       
        system.debug('number of rev installments for pbe>>>'+pbe.Product2.NumberOfRevenueInstallments);
       
        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
        for(integer i=0; i<200; i++){
         OpportunityLineItem oli = new OpportunityLineItem();
            oli.OpportunityId=opptys[i].id;
            oli.PricebookEntryId=pbe.id;
            oli.Quantity=1;
            oli.UnitPrice=1200000;
            olis.add(oli);
        }
        insert olis;
        OpportunityLineItem line = [SELECT id FROM OpportunityLineItem WHERE PriceBookEntryId=:pbe.id LIMIT 1];
        List<OpportunityLineItemSchedule> oliSchedToInsert = new List<OpportunityLineItemSchedule>();
        for(integer i=0; i<12; i++){
            OpportunityLineItemSchedule s = new OpportunityLineItemSchedule();
            s.Revenue = 100000;
            s.ScheduleDate = date.today().addMonths(i);
            s.OpportunityLineItemId = line.id;
            s.type = 'Both';
            s.Quantity = 1;
           
            oliSchedToInsert.add(s);
        }
        insert oliSchedToInsert;
       
        List<OpportunityLineItemSchedule> oliSched = [SELECT id, Revenue, ScheduleDate,OpportunityLineItemId,
                                                      OpportunityLineItem.OpportunityId FROM OpportunityLineItemSchedule
                                                      WHERE OpportunityLineItem.OpportunityId IN : opptyIds];
       
        system.debug('size of schedule list>>>'+oliSched.size());
        //system.assertEquals(oliSched.size()>0, true);
        opptys[0].closeDate = date.today().addMonths(13);
        update opptys[0];
       
        List<Opportunity> opptysToUpdate = new List<Opportunity>();
       /* for(integer i=0;i<200; i++){
            opptys[i].CloseDate = date.today().addMonths(14);
            opptysToUpdate.add(opptys[i]);
        }
        update opptysToUpdate;*/
       
    }
}
Hi Everyone, hoping there is someone that is seeing something I'm not.  I have the following trigger, setRegPartnerTrigger that calls the APEX Class setRegPartner. The test code is testSetRegPartner. The test code executes with no issues in sandbox, the test leads are inserted, updated and result in 95% plus coverage. When I try to deploy, the test code errors out telling me it can't insert the first lead. 

I have run the code from the trigger and the test lead insert in an execute anonomyous window successfully so am completely stumped.  Hoping someone sees something I'm missing. 

APEX CLASS: 
public class setRegPartner{

    public static void setPartnerLookUp(Set<Id> dealRegIds){
        system.debug('number of leads received by SetPartnerOnDealReg class>>>'+dealRegIds.size());
        List<Lead> dealRegs = new List<Lead>();
        //put the leads in the trigger into a list for processing
        dealRegs = [SELECT id, Name, FirstName, LastName, Email, Phone, City, State, PostalCode, Company,
                            Deal_Registration_Status__c, Deal_Product__c, Deal_Registration_Date__c, deal_exp_close_date__c,
                            Deal_Registration_Expiration__c, Registered_Reseller__c, Preferred_Reseller__c,
                            Reseller_Sales_Person__c, Reseller_Phone_Number__c, Registered_Partner_Rep_Email__c,
                            Reseller_Region__c, Distributor__c, Deal_Distributor__c, Reseller_Rep__c
                            FROM Lead WHERE id IN :dealRegIds];
        system.debug('Deal Reg '+dealRegs);
        system.debug('number of leads in dealRegs List>>>'+dealRegs.size());
        //put partner account and reps into maps for later retrieval
        Map<String, Account> ptnrAccts = new Map<String, Account>();
        Map<String, Contact> ptnrReps = new Map<String, Contact>();
        Map<string, Account> ptnrDomains = new map<String,Account>();
       
        Set<String> acctTypes = new Set<String>();
        acctTypes.add('Var- Other');
        acctTypes.add('Var- Preferred');
        acctTypes.add('DMR');
        acctTypes.add('Etail');
        List<Account> ptnrs = new List<Account>();
        ptnrs = [SELECT id, Name, Type, OwnerId, email_domain__c FROM Account WHERE
                 Type IN :acctTypes];

        system.debug('partner type VAR- Other'+ptnrs);
        set<id> ptnrAcctIds = new Set<id>();
        set<string> emailset = new set<string>();
       
            for(Account a : ptnrs){
                ptnrAccts.put(a.Id, a);
                ptnrAcctIds.add(a.id);
                if(string.isNotblank(a.email_domain__c)){
                    ptnrDomains.put(a.email_domain__c, a);
                }
            }
            List<Contact> repList = [SELECT id, AccountId, FirstName, LastName, Email,
                          Phone, Account.OwnerId FROM Contact
                          WHERE AccountId IN :ptnrAcctIds];
              
            for(Contact c : repList){
                    system.debug('email for rep>>>'+c.email);
                    ptnrReps.put(c.email, c);
                    emailset.add(c.email);
                }
           
            system.debug('contact emails----   '+emailset);
            List<Contact> contactsToInsert = new List<Contact>();
        for(Lead l : dealRegs)
        {
            if (emailset.contains(l.Registered_Partner_Rep_Email__c))
              system.debug('email exist');
              else
              system.debug('doesnt exist');
        }
        //system.debug('print partner Account'+ptnrAccts);
        //system.debug('print partner Contact'+ptnrReps);
       
       Map<String, Account> distyAccts = new Map<String, Account>();
   
    //put distributors accounts into map
       List<Account> distys = new List<Account>();
        distys = [SELECT id, Name, Type, OwnerId FROM Account WHERE Type = 'Distributor'];
            for(Account d : distys){
                distyAccts.put(d.Name, d);
                }

        list<Lead> leadsToUpdate = new List<Lead>();
       
        for(Lead l : dealRegs) {
          String email =  l.Registered_Partner_Rep_Email__c;
                list <String> extractEmail = email.split('@');
                system.debug('email array'+ extractEmail);
                email = extractEmail[1];
            if(emailset.contains(l.Registered_Partner_Rep_Email__c)) {
                           
                    string acctId = ptnrReps.get(l.Registered_Partner_Rep_Email__c).Accountid;
                    l.Reseller_Rep__c = ptnrReps.get(l.Registered_Partner_Rep_Email__c).id;
                    l.Registered_Reseller__c = acctId;
                    l.Deal_Distributor__c = distyAccts.get(l.Distributor__c).id;
                    l.OwnerId = ptnrReps.get(l.Registered_Partner_Rep_Email__c).Account.OwnerId;
                    leadsToUpdate.add(l);                        
               
            } else if(!emailset.contains(l.Registered_Partner_Rep_Email__c) && ptnrDomains.get(email) != NULL){
                system.debug('doesnt exist');
               
               
                        String fName = l.Reseller_Sales_Person__c.left(l.Reseller_Sales_Person__c.indexOf(' '));
                        String lName = l.Reseller_Sales_Person__c.right(l.Reseller_Sales_Person__c.length()-

            l.Reseller_Sales_Person__c.indexOf(' '));                                              
                       
                        Contact newContact = new Contact();
                        newContact.FirstName = fName;
                        newContact.LastName = lName;
                        newContact.Email =l.Registered_Partner_Rep_Email__c;
                        newContact.Phone = l.Reseller_Phone_Number__c;
                        newContact.AccountId = ptnrDomains.get(email).id;
                       
                        system.debug('insert contact ' +newContact);
                        insert newContact;
                      l.Reseller_Rep__c = newContact.id;
                      l.Registered_Reseller__c = newContact.AccountId;
                      l.Deal_Distributor__c = distyAccts.get(l.Distributor__c).id;
                      leadsToUpdate.add(l);
               
            } else {
                   l.Partner_Status__c = 'Not Found';
                    leadsToUpdate.add(l);                        
                }
            }
        update leadsToUpdate;
    }
}

TRIGGER: 
trigger setRegPartnerTrigger on Lead (after insert) {
  Set<id> leadIds = new Set<id>();

    for(Lead l : trigger.new){
         
        if(l.LeadSource == 'Deal Registration'){
              system.debug(l); 
            leadIds.add(l.id);
        }
    }
    system.debug('number of leads sent to setRegPartner class>>>'+leadIds.size());   
    setRegPartner.setPartnerLookUp(leadIds);
   
}

TEST CODE: 
@isTest (seeAllData=true)
public class testSetRegPartner{
 
    static testmethod void testRegPartner(){
       
       Account disty = new Account(Name='Ingram Micro', Type='Distributor', Customer_ID__c = 'ING4051', email_domain__c = 'ingram.com');
       insert disty;
       Account ptnr = new Account(Name='Partner', Type='VAR- Other', Customer_ID__c = 'other123', email_domain__c = 'partner.com');
       insert ptnr;
       Contact rep = new Contact(FirstName='Pard', LastName='Rep', Email = 'pard@partner.com', Accountid = ptnr.id);
         insert rep;
       Contact distyRep = new Contact(FirstName='disty', lastName='Rep', Email='disty@rep.com', Accountid=disty.id, Deal_Registration_Contact__c = 'yes');
        insert distyRep;
       
       String DealRegRecTypeId = [SELECT id FROM RecordType WHERE SobjectType = 'Lead' and Name ='Partner Deal Registrations'].id;
      Lead noRepAcct = new Lead();
          noRepAcct.RecordTypeId = DealRegRecTypeId;
            noRepAcct.LeadSource = 'Deal Registration';
            noRepAcct.FirstName = 'first';
            noRepAcct.LastName = 'last';
            noRepAcct.Email = 'a@b.com';
            noRepAcct.City = 'mapleton';
            noRepAcct.State = 'IL';
            noRepAcct.PostalCode = '12345';
            noRepAcct.Company = 'test';
            noRepAcct.Deal_Registration_Status__c = 'Submitted';
            noRepAcct.Deal_Product__c = 'B800i';
            noRepAcct.Deal_Registration_Date__c = date.today();
            noRepAcct.deal_exp_close_date__c = date.today().addDays(30);
            noRepAcct.Preferred_Reseller__c = 'testReseller';
            noRepAcct.Reseller_Sales_Person__c = 'Test Rep';
            noRepAcct.Reseller_Phone_Number__c = '123-123-1234';
            noRepAcct.Registered_Partner_Rep_Email__c = 'tr@tp.com';
            noRepAcct.Distributor__c = 'Ingram Micro';
            noRepAcct.deal_unit_qty__c = 5;
        insert noRepAcct;
       
        Lead acctNoRep = new Lead();
            acctNoRep.RecordTypeId = DealRegRecTypeId;
            acctNoRep.LeadSource = 'Deal Registration';
            acctNoRep.FirstName = 'first';
            acctNoRep.LastName = 'last';
            acctNoRep.Email = 'a@b.com';
            acctNoRep.City = 'mapleton';
            acctNoRep.State = 'IL';
            acctNoRep.PostalCode = '12345';
            acctNoRep.Company = 'test';
            acctNoRep.Deal_Registration_Status__c = 'Submitted';
            acctNoRep.Deal_Product__c = 'B800i 8TB';
            acctNoRep.Deal_Registration_Date__c = date.today();
            acctNoRep.deal_exp_close_date__c = date.today().addDays(30);
            acctNoRep.Preferred_Reseller__c = 'testReseller';
            acctNoRep.Reseller_Sales_Person__c = 'Test Rep';
            acctNoRep.Reseller_Phone_Number__c = '123-123-1234';
            acctNoRep.Registered_Partner_Rep_Email__c = 'tr@partner.com';
            acctNoRep.Distributor__c = 'Ingram Micro';
            acctNoRep.deal_unit_qty__c = 5;
        insert acctNoRep;
       
        Lead acctRep = new Lead();
          acctRep.RecordTypeId = DealRegRecTypeId;
            acctRep.LeadSource = 'Deal Registration';
            acctRep.FirstName = 'first';
            acctRep.LastName = 'last';
            acctRep.Email = '1@b.com';
            acctRep.City = 'mapleton';
            acctRep.State = 'IL';
            acctRep.PostalCode = '12345';
            acctRep.Company = 'test';
            acctRep.Deal_Registration_Status__c = 'Submitted';
            acctRep.Deal_Product__c = 'B800i';
            acctRep.Deal_Registration_Date__c = date.today();
            acctRep.deal_exp_close_date__c = date.today().addDays(30);
            acctRep.Preferred_Reseller__c = 'testReseller';
            acctRep.Reseller_Sales_Person__c = 'Test Rep';
            acctRep.Reseller_Phone_Number__c = '123-123-1234';
            acctRep.Registered_Partner_Rep_Email__c = 'pard@partner.com';
            acctRep.Distributor__c = 'Ingram Micro';
            acctRep.deal_unit_qty__c = 5;
        insert acctRep;
       
        system.assertEquals(acctNoRep.Partner_Status__c, NULL);
        system.assertEquals(acctRep.Partner_Status__c, NULL);
        system.assertEquals(noRepAcct.Partner_Status__c, NULL);
       
        Set<id> dealRegIds = new Set<id>();
        dealRegIds.add(acctRep.id);
       
        setRegPartner.setPartnerLookUp(dealRegIds);
        acctRep.Deal_Registration_Status__c = 'Approved';
        update acctRep;

       
    List<Lead> testLeads = new List<Lead>();
    testLeads.add(acctRep);
   
    convertLead c = new convertLead();
    c.convertLeads(testLeads);
    List<Lead> convLead = [SELECT id, Distributor__c, ConvertedOpportunityId FROM
                Lead WHERE id = :acctRep.id];
               
    Quote q = [SELECT id, Distributor__c FROM Quote WHERE OpportunityId = :convLead[0].ConvertedOpportunityId];
   
    c.sendDistyEmail(q);
   
    acctNoRep.Deal_Registration_Status__c = 'Approved';
        update acctNoRep;
       
    List<Lead> testLeads2 = new List<Lead>();
    testLeads2.add(acctNoRep);
   
    convertLead d = new convertLead();
    d.convertLeads(testLeads2);
    List<Lead> convLead2 = [SELECT id, Distributor__c, ConvertedOpportunityId FROM
                Lead WHERE id = :acctNoRep.id];
               
    Quote q2 = [SELECT id, Distributor__c FROM Quote WHERE OpportunityId = :convLead2[0].ConvertedOpportunityId];
    List<QuoteLineItem> qlis = [SELECT id FROM QuoteLineItem WHERE QuoteID = :q2.id];
        system.debug('test code qlis size is>>>'+qlis.size());
    system.assertEquals(qlis.size(), 1);
   
    }
}

I'm using an @future (callout=true) method to make a callout to a webservice for an xml file. If I remove the @future annotation and make the method not static it compiles with no problem and calls the readResponse method. If I keep it as a static method, I'm unable to call the readResponse or the getValueFromTag method. I know I'm missing something obvious but am just not finding it in the documentation, hoping   

My code is using the example posted on the developer relations blog this summer at http://blogs.developerforce.com/developer-relations/2013/08/integrating-force-com-using-xml-in-apex.html

public class parseExample{
    public Policy_Information__c polInfo{get;set;}
    public List<Policy_Information__c> polInfoToInsert = new List<Policy_Information__c>();
   
    @future(callout=true)
    public static void requestIvans(){
        Http h = new Http();
      HttpRequest req = new HttpRequest();
  HttpResponse res = new HttpResponse();
        String url = 'https://s3.amazonaws.com/XXX/XXXX.xml';
        req.setEndPoint(url);
        req.setMethod('GET');
  res = h.send(req);
        String response = res.getBody();
  XmlStreamReader reader = new XmlStreamReader(response);
        system.debug('reader response is>>>'+response.left(25));
     readResponse(reader);  
    }

    public void readResponse(XmlStreamReader reader) {
     // Is there any element next?
        while (reader.hasNext()) {
            // Is the next element an opening tag?
            if (reader.getEventType() == XmlTag.START_ELEMENT) {
                // Set Account Details
                if ('CommercialName' == reader.getLocalName()) {
                    // if opening tag of account is found initialize polInfo Record
                    polInfo = new Policy_Information__c();
                } else if ('CommercialName' == reader.getLocalName()) {
                    polInfo.Insured_Name__c = getValueFromTag(reader);
                } else if ('Addr1' == reader.getLocalName()) {
                    polInfo.Address1__c = getValueFromTag(reader);
                }else if ('City' == reader.getLocalName()){
                    polInfo.City__c = getValueFromTag(reader);
                } else if('StateProvCd' == reader.getLocalName()){
                    polInfo.State__c = getValueFromTag(reader);
                }else if('PostalCode' == reader.getLocalName()){
                    polInfo.Zip__c = getValueFromTag(reader);
                }
                system.debug('polInfo record details>>>'+polInfo);
                //set policy information
               
            } else if (reader.getEventType() == XmlTag.END_ELEMENT) {
                // Is the next element an end tag? If yes is it an Account or an Accounts tag?
                if ('PolicyDetail' == reader.getLocalName()) {
                    // If you find end tag called account, push the account record in list
                    polInfoToInsert.add(polInfo);
                    system.debug('number of polstoInsert>>>'+polInfoToInsert.size());
                } else if ('IVANSExtract' == reader.getLocalName()) {
                    // We have reached end of file, just exit
                    break;
                }
            }
        }
          insert polInfoToInsert;
    }

// This is an extra function to read data between opening and closing tag.
// It will return the string of value from between tags
public string getValueFromTag(XMLStreamReader reader) {
    String DataValue;

    while (reader.hasNext()) {
        if (reader.getEventType() == XmlTag.END_ELEMENT) {
            break;
        } else if (reader.getEventType() == XmlTag.CHARACTERS) {
            DataValue = reader.getText();
        }
        reader.next();
    }

    return DataValue;
}
}


I have a class that is loading a csv file and processing it through the system to update opportunity records. 

 

Most of the time, I have no problem with the csv files that we are using to run the updates, however, every so often one comes through that returns a "BLOB is not a valid UTF-8 string" error. I can't find the issue that is causing this - 

 

any ideas? 

 

 

I'm working my way through the Heroku workbook and have hit a roadblock early in the process. I have installed Ruby and the Heroku toolbelt and am trying to set up a Gemfile as documented in the workbook. 

 

I can run the $gem install bundler command, but when I try to execute the next step, $bundle install - I get the following error: 

Bundler: GemfileNotFound

 

Any suggestions? I have a file called Gemfile.rb in the workbook directory. What am I missing? 

 

Thanks,

 

I'm working on a solution to convert leads automatically to Account/Contacts/Opportunities. The process is as follows: 

 

1. Lead with Lead Source = "Deal Registration" inserted (Trigger after insert puts them into set<id> and passes to class/static method. 

2. Query Opportunity object, looking for existing open opportunity for company name/city/state combination

3. If none exists, query Account object looking for matching account/city/state combination 

4. If Account exists, look for matching contact, if none exists insert new contact

5. If Account exists, insert opportunity for account and if contact exists set as contact role on opportunity,

         ELSE insert Account and Contact and insert opportunity 

 

I can get the lead convert working and can add the opportunity to the account if the account name matches exactly. I know I need to use a SOSL query to look for a matching account to my lead, however, I can only figure out how to do this one record at a time - I can't figure out how to bulkify this. Any help you can offer me would be greatly appreciated!

 

My setup code is below: 

 

/**************************
Use to determine if the deal reg is valid, then call convertLead to do the conversion work
**************************/

public class dealRegHandling{
    
    public static void dealRegProcess(Set<id> dealRegIds){
     	List<Lead> dealRegs = [SELECT id, Name, FirstName, LastName, Email, Phone, Registered_Partner_Preferred_Partner__c,
                               Registering_Rep__c, Registering_Rep_Email__c, Registering_Rep_Name__c,Deal_Registration_Status__c,
                               Deal_Registration_Product__c, Deal_Registration_Expiration_Date__c, City, State, PostalCode,
                               Company
                               FROM Lead WHERE id IN :dealRegIds];
        
        List<Opportunity> regdOpptys = [SELECT id, AccountId, Account.Name, Account.BillingState, Account.BillingCity, 
                                        Registered_Partner_Preferred_Partner__c, Registering_Rep__c, Registering_Rep_Email__c, 
                                        Deal_Registration_Status__c, Deal_Registration_Product__c, 
                                        Deal_Registration_Expiration_Date__c 
                                        FROM Opportunity WHERE isClosed = False
                                        AND Registered_Partner_Preferred_Partner__c != NULL];
        
        Map<String, Opportunity> openOpptys = new Map<String, Opportunity>();
        for(Opportunity o : regdOpptys){
            String opptyKey = o.Account.Name.remove(' ').toLowerCase() + o.Account.BillingCity + o.Account.BillingState;
            system.debug('opportunity search key>>>'+opptyKey);
            openOpptys.put(opptyKey, o);
		}
        List<Lead> leadsToConvert = new List<Lead>();
        List<Lead> leadsToUpdate = new List<Lead>();
        map<id, boolean> leadToWhat = new map<Id, boolean>();
        for(Lead l : dealRegs){
            String leadKey = l.Company.remove(' ').toLowerCase() +  l.City + l.State;
            system.debug('lead search key is >>>'+leadKey);
            system.debug('lead search result is>>>'+openOpptys.get(leadKey));
            Boolean matchedDR = false;
            if(openOpptys.get(leadKey) == NULL){
                matchedDR = false;
                l.Deal_Registration_Status__c = 'Approved';
                leadToWhat.put(l.id, matchedDR);
                leadsToUpdate.add(l);
                leadsToConvert.add(l);
            } else {
                matchedDR = true;
                l.Deal_Registration_Status__c = 'Denied';
                leadToWhat.put(l.id, matchedDR);
                leadsToUpdate.add(l);
            }
        }
        update leadsToUpdate;
        convertLead con = new convertLead();
        con.convertLeads(leadToWhat, leadsToConvert);
    }
}

 My conversion code is here: 

public class convertLead{

    public void convertLeads(map<id, boolean> matchedAcct, List<Lead> leadsToConvert){
        
        for(Lead l : leadsToConvert){
            
            Database.leadConvert lc = new Database.LeadConvert();
                lc.setLeadId(l.id);
                
                LeadStatus convertStatus = [SELECT id, MasterLabel FROM LeadStatus WHERE IsConverted = True LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
                Date close = date.today().addDays(30);
                lc.setOpportunityName(l.Registered_Partner_Preferred_Partner__c + ' - ' + l.Name + ' - ' + close);
                
            if(matchedAcct.get(l.id) == true){
                Id acctId = [SELECT id, Name FROM Account WHERE Name LIKE :l.Company AND BillingState = :l.State].id;
                lc.setAccountId(acctId);
                Id contactId = [SELECT id FROM Contact WHERE LastName like :l.LastName AND Email = :l.email].id;
                lc.setContactId(contactId);
            }
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            system.assert(lcr.isSuccess());
            system.debug('lead converted>>>'+lcr.isSuccess());
            }
    }
}

 

Hi All,

 

I have a requirement to create a VF page showing Leads and Contacts that have a hand-off date from the marketing team to the sales team in a specific time range in a table similar to what is described in the Force.com Cookbook http://developer.force.com/cookbook/recipe/selectable-sobjects-for-use-with-datatables-and-checkboxes.

 

I'm not sure how to bring both leads and contacts into the same view - I understand how to select the leads/contacts but I'm not clear how to get them both into the same list and how to put a date range selector (I can use relative dates such as last week, last month as well as specific date ranges) for the user to select what items they want to see. 

 

I have a query that finds the leads and contacts I'm looking for and puts them into a list, but am not sure how to access the for the records? 

 

Here is the code I have so far: 

public with sharing class leadContactCombinedView{
	private SObject record;
	public Boolean selected{get; set;}
    public List<leadContactCombinedView> listLeadContact {get;set;}
	
        // Universal constructor for any SalesForce object type
	public leadContactCombinedView(SObject obj)
	{
		record = obj;
		selected = false;
	}
    public leadContactCombinedView(){
    }
	
        // Getter for Lead
	public Lead getLead()
	{
		return (Lead)record;
	}
	
        // Getter for Contact
	public Contact getContact()
	{
		return (Contact)record;
	}
	
public List<leadContactCombinedView> generateListLeadContact(){
        
         for(Lead l : [SELECT id, Website, Title, Street, Status, State, PostalCode, Phone, NumberOfEmployees, MobilePhone, LeadSource, LastName, Industry, HasOptedOutOfEmail, FirstName, Email, Description, Country, Company, City, OwnerID, Primary_Campaign__c, Hand_off_Date__c FROM Lead WHERE  Status = 'Open'])
{ leadContactCombinedView leadItem = new leadContactCombinedView(l); this.ListLeadContact.add(leadItem); } for(Contact c : [SELECT id, Account.Website, Title, Account.BillingStreet, Contact_Status__c, Account.BillingState, Account.BillingPostalCode, Phone, account.NumberOfEmployees, MobilePhone, LeadSource, LastName, Account.Industry, HasOptedOutofEmail, FirstName, Email, Account.Description, Account.BillingCountry, Account.Name, Account.BillingCity, OwnerId, Primary_Campaign__c, Hand_off_Date__c, AccountId FROM Contact WHERE Contact_Status__c = 'Open']){ leadContactCombinedView contactItem = new leadContactCombinedView(c); this.ListLeadContact.add(contactItem); } return listLeadContact; } public List<leadContactCombinedView> getListLeadContact(){ return listLeadContact; } }

 

 

I'm calling a static method from a trigger. I had all the of the methods in one originally, but had to change it to support bulk processing.  I'm using a design pattern I've used elsewhere successfully, however for some reason, I'm not getting past the initial queries in the method. I'm not seeing why that's happening and am hoping someone has a suggestion. 

 

Thanks!

JoAnn

 

Trigger: 

trigger notifyPtnrOfNewLead on Lead (after insert, after update) {
    	List<Lead> leadsInTrigger = new List<Lead>();
    	String[] ptnrs= new List<String>();

    
    if(!controlTriggerRecursion.hasAlreadyLooped()){
        
        for(Lead l: trigger.new){
               if(l.Preferred_Partner_for_Tech_Purchases__c.length()>0){
                   leadsIntrigger.add(l);
                   ptnrs.add(l.Preferred_Partner_for_Tech_Purchases__c);
                    }
        }
    }
    		controlTriggerRecursion.setHasAlreadyLooped();
        	ptrCampaignHandling.findPtrCampaign(leadsInTrigger,ptnrs);
       
}

 

 

Class & Method: 

 

public class ptrCampaignHandling{
    
    public static void findPtrCampaign(List<Lead> ptrLead, String[] cmpaignPtr){

Map<String, Campaign> ptnrCampaignMap = new Map<String, Campaign>(); //This Query and the one for Accounts below are looping, but I'm not understanding why...
List<Campaign> camps = [SELECT id, Name, Campaign_Partner__c, Primary_Partner_Contact__c, Email_Template_Name__c, isActive, StartDate, EndDate, Type, Primary_Partner_Contact__r.Email FROM Campaign WHERE Type = 'Partners' AND IsActive = True]; for(Campaign cmp : camps){ ptnrCampaignMap.put(cmp.Name,cmp); } Map<String, Id> cmpPartnerId = new Map<String, Id>(); List<Account> ptrAccts = [SELECT id, Name FROM Account WHERE Type = 'Partner' AND Partner_Status__c = 'Agreement Signed' ORDER by CreatedDate DESC]; for(Account pa: ptrAccts){ cmpPartnerId.put(pa.Name, pa.id); } Map<Lead, Id> cmsToCreate = new Map<Lead, Id>(); List<Lead> newCampaignsToCreate = new List<Lead>(); for(Lead newLead : ptrLead){ String campName = newLead.pi_campaign__c + ' - ' + newLead.Preferred_Partner_for_Tech_Purchases__c; Campaign ptnrCampaign = ptnrCampaignMap.get(campName); if(ptnrCampaign != NULL){ cmsToCreate.put(newLead, ptnrCampaign.id); } else { newCampaignsToCreate.add(newLead); } } insertCamp(newCampaignsToCreate, cmpPartnerId); createNewCampMembers(cmsToCreate); } public static void insertCamp(Lead[] newCampsToCreate, Map<String, Id> cmptrList){ List<Campaign> newCampsToInsert = new List<Campaign>(); String[] CampaignPartners; for(Lead l : newCampsToCreate){ String campName = l.pi_campaign__c + ' - ' + l.Preferred_Partner_for_Tech_Purchases__c; Campaign newPtnrCampaign = new Campaign(); newPtnrCampaign.Name = campName; newPtnrCampaign.Type = 'Partners'; newPtnrCampaign.StartDate = date.today(); newPtnrCampaign.EndDate = date.today().addMonths(3); newPtnrCampaign.Campaign_Partner__c = newPtnrCampaign.Primary_Partner_Contact__c = cmptrList.get(l.Preferred_Partner_for_Tech_Purchases__c); newPtnrCampaign.isActive = true; newPtnrCampaign.Email_Template_Name__c = l.pi_campaign__c + ' - Lead Notification'; newcampsToInsert.add(newPtnrCampaign); campaignPartners.add(cmptrList.get(l.Preferred_Partner_for_Tech_Purchases__c)); } insert newCampsToInsert; findPtrCampaign(newCampsToCreate, campaignPartners); } public static void createNewCampMembers(Map<Lead, Id> newCM){ CampaignMember cm = new CampaignMember(); List<CampaignMember> cmsToInsert = new List<CampaignMember>(); for(Lead l : newCM.keySet()){ cm.CampaignId = newCM.get(l); cm.LeadId = l.id; cm.Status = 'Responded'; cmsToInsert.add(cm); } insert cmsToInsert; } }

 

 

Hoping someone can point me in the right direction - I'm bumping against what I think is a logic issue here but can't see my way out of it.

 

I'm trying to create a map of accounts and domain names associated with the account.  The Domains field is a long text field and may have multiple domains listed separated by commas, i.e. bankofamerica.com, boa.com, bankamerica.com etc.

 

When a lead comes into the system, the email domain is parsed out and compared to the domains listed for each account and if a match is found, the lead type is set based on some values of the the account found.  I can get it working perfectly if there is only one domain listed, but as soon as there are multiple domains listed, I can't get the match to work.  

 

I have tried it using a SOSL query, however, I bump up against governor limits very quickly which is a problem when loading lists of leads. 

 

The lastest iteration takes a list of accounts with domains listed and puts them into a map<String, Account>. If there is more than one domain listed in the field, I'm parsing the domains into a list so I can put each domain in as a separate key for the account they belong to, however, I can't get the account to match up to the second domain when I loop through and am instead getting a null value for the account.  I have verified that the domain names are parsing out correctly and that the account remains in scope and the code loops through the generated list of domains for the account the right number of times, however, I can't get the account to go into the map the second time. 

 

My code is below - any suggestions/thoughts would be greatly appreciated!

 

public class setLeadType{

   public static void setLeadAccountType(Lead[] newLeads){
   	   List<String> typeValues = new List<String>();
       List<Account> accts = [SELECT Id, Name, Type, Partner_Status__c, Domains__c, Active_Subscription__c, 
                               		First_Subscription__c, Active_Funnel__c,Customer_Type_Subscription__c,Target_Category__c,
                                    Closed_Amount__c, Website, Closed_Subscription_Transactions__c
                               FROM Account 
                               WHERE Domains__c != NULL];
        map<String, Account> acctDomains = new Map<String,Account>();
       
 
        for(Account a : accts){
            if(a.Domains__c.containsNone(',')){
        		acctDomains.put(a.Domains__c, a);
            } else {
               	List<String> doms = a.Domains__c.split(',');
					for(String s : doms){
                 	   acctDomains.put(s, a);
//HERE IS WHERE I'M HAVING AN ISSUE - THE FIRST DOMAIN/ACCOUNT PAIR IS PUT INTO THE MAP, BUT THE SECOND IS NOT
               	}
           	}
         }
       
        for(Lead ls : newLeads){
            ls.Type_of_Lead__c = NULL;
            Account acct = new Account();
            acct = acctDomains.get(ls.Domain__c);
        	if(acct!=NULL){
                if(acct.Type == 'Partner' && string.isNotEmpty(acct.Partner_Status__c))
                    if(acct.Partner_Status__c != 'Prospect' || acct.Partner_Status__c  != 'Rejected' || 
                    acct.Partner_Status__c  != 'Terminated'){
                    typeValues.add('Existing Partner');
                }
                if(acct.Active_Subscription__c != False && acct.Closed_Subscription_Transactions__c>0){
                    typeValues.add('Active Subscription Customer');
                }    
            if(acct.Active_Funnel__c > 0){
                typeValues.add('Active Funnel');
            }
            if(acct.Active_Subscription__c == False && acct.Closed_Subscription_Transactions__c > 0){
                    typeValues.add('Previous Subscription Customer');
                } 
                if(acct.Closed_Amount__c > 0 && 
                   acct.Active_Subscription__c == False && 
                   acct.Closed_Subscription_Transactions__c == 0){
                    typeValues.add('Non-Subscription Purchase');
                } 
                if(string.isNotEmpty(acct.Target_Category__c) && acct.Target_Category__c == 'Data Warehouse'){
                    typeValues.add('Data Warehouse');
                } 
                if(string.isNotEmpty(acct.Target_Category__c)&& acct.Target_Category__c == 'Fortune/Forbes/Global'){
                     typeValues.add('Fortune/Global');
                }
            String lsType = string.join(typeValues, ';');
            ls.Type_of_Lead__c = lsType;
			
        	}
        }
    }
    public static void setLeadPersonalLeadType(Lead[] ignoreLeads){
        for(Lead l : ignoreLeads){
            l.Type_of_Lead__c = NULL;
        }
    }    
}

 

Thanks!

I have a VF Component that I need to include in a tabbed page - the name of the tab refers to the attribute I'm passing to the component to determine which record I want displayed in the panel.  

 

My component controller has a getter and setter for the component attribute and has a getter for the record but no data is being passed back unless I hard code the attribute value in the controller. 

 

Here is the controller: 

public class fcrCompetencyController{

  public Competency__c comp{get;set;}
  public String compType{get;set;}
  
  public fcrCompetencyController(){
      comp=[SELECT id, Description__c, Competency_Type__c, Name 
                      FROM Competency__c 
                      WHERE Active__c = True];
   }
 
  public Competency__c getComp() {
    return comp;
  } 
 
  public void setCompType(String s){
      compType = s;
      }
        
  public String getCompType(){
      return compType;
      }

}

 And my component is: 

<apex:component controller="fcrCompetencyController">
    <apex:attribute name="competency" assignTo="{!compType}" type="String" description="Compentency Displayed"/>
    <apex:outputField value="{!comp.Name}"/>
    <apex:outputField value="{!comp.Description__c}"/>
</apex:component>

 

This is the test page I'm using to try to get it displayed, the actual page is much longer: 

<apex:page controller="fcrCompetencyController">
<apex:pageBlock title="{!comp}">
<apex:outputText value="comptype is {!compType}"/>
<c:competencyDisplay competency="Pre/Post Call Analysis"/>
</apex:pageBlock>
</apex:page>

 I'm not sure where to go next, every example I can find and all the documentation I've found it seems I have everything covered, but am unable to get this working. 

 

I need to display the Description__c field as a field, not text as it is a rich text field on the object and needs to be displayed as created. 

 

Any ideas?

 

Thanks!

I'm running into this error: Invalid integer: common.apex.runtime.impl.ScalarList@b5144800 when executing the following code.  The code compiles with no problem.  I'm fairly certain I have my data types correct - not really sure what's causing this? Any ideas? 

 

   public Map<Target_HCP__c, Integer> targetsWithCalls = new Map<target_HCP__c, Integer>();
        
    public void updateCalls(){
            Map<Id, Integer> acctCalls = new Map<Id, Integer>();
            List<AggregateResult> r = [SELECT Account_vod__c acctid, COUNT(id) totalCalls
                           FROM Call2_vod__c 
                           WHERE Call_Date_vod__c =THIS_QUARTER
                           AND Status_vod__c = 'Submitted_vod'                            
                           GROUP BY Account_vod__c];
            for(AggregateResult i : r){
                acctCalls.put(String.valueOf(i.get('acctId')), integer.valueOf(i.get('totalCalls')));
                system.debug(' account>>> ' + i.get('acctid') + 'number of calls>>> '+i.get('totalCalls'));
            }  
           
   
         
         for(Target_HCP__c t : [SELECT id, Calls_Actual__c, Prescriber__c 
                                     FROM Target_HCP__c 
                                     WHERE Prescriber__c = :acctCalls.KeySet()]){
             targetsWithCalls.put(t, integer.valueOf(acctCalls.Values()));
             t.Calls_Actual__c += integer.valueOf(targetsWithCalls.Values());
             targetsToUpdate.add(t);
         }
            update targetsToUpdate;                     
         }

 

 

I'm trying to count a group of records and get the total records by account and then put the account id and the number of child records into a map.  I keep getting an "incompatible key type for map" on compile and I'm not sure why. Hopeing somone has an idea!

 

If I take the map out and just look at the debug, it's pulling out the Account id as  a string...

 

Map<String, Integer> acctCalls = new Map<String, Integer>();

List<AggregateResult> r = [SELECT Account_vod__r.Name acctid, COUNT(id) totalCalls
                           FROM Call2_vod__c  
                           GROUP BY Account_vod__r.Name];
for(AggregateResult i : r){
    acctCalls.put(i.get('acctid'), i.get('totalCalls'));

    system.debug(' account>>> ' + i.get('acctid') + 'number of calls>>> '+i.get('totalCalls'));
}                         
  

 Thanks,

JoAnn

I have a wrapper class that creates a line item record on a parent record. The VF page lists the available items to add with an input text field that sets a integer with the quantity ordered.  The method is creating the record as expected, but the quantity is not being set properly. I'm not seeing what I'm missing in the process to properly set the quantity in the child record. Any suggestions? 

 

public class materialOrderWrapperClassController{

    public List<cProducvod> productList {get; set;}
    public Material_Order__c record;
    public List<Product_vod__c> availableProducts= new List<Product_vod__c>();
    public List<Material_Order_line_Item__c> linesToAdd {get;set;}
    public List<Material_Order_line_Item__c> qtysToUpdate {get;set;}
    public List<cProducvod> selectedProducts{get;set;}
    public Boolean hasProdSelect{get;set;}
    public Integer qty {get;set;}   
    
    public materialOrderWrapperClassController(ApexPages.StandardController stdController){
        record = [SELECT id, Name, Date__c, Status__c, Notes__c
                    FROM Material_Order__c 
                    WHERE id =:ApexPages.currentPage().getParameters().get('id')];
        
        selectedProducts = new List<cProducvod>();
        
       
        availableProducts = [SELECT id, Name, Image__c, Product_Type_vod__c 
                                FROM Product_vod__c 
                                WHERE Product_type_vod__c = 'Order'
                                ORDER BY Name ASC];
            //productList = new List<cProducvod>();
            if(productList == null){
              productList = new List<cProducvod>();                                        
              for(Product_vod__c p : availableProducts) {
                productList.add(new cProducvod(p));
            }
        }                                
    }
    

    public List<cProducvod> getProductList() {
         return productList;
    }
        
     public void setQty(Integer q){
         qty=q;
         }
         
     public Integer getQty(){
         return qty;
         }
         
     public pageReference processSelected(){
         selectedProducts.clear();
          hasProdSelect = false;
            for(cProducvod cProd: getProductList()) {
                if(cProd.qty > 0) {
                    selectedProducts.add(cProd);
                    system.debug('cProd qty is >>>>'+cProd.qty);
                    }
              }
        
        linesToAdd = new List<Material_Order_Line_Item__c>();
         for(cProducvod prdct : selectedProducts){
            Material_Order_line_Item__c newLine = new Material_Order_line_Item__c();
            newLine.Products__c = prdct.cProductvod.id;
            system.debug('newLine product name is>>>'+newLine.Products__c);
            newLine.Quantity__c = qty;
            system.debug('newLine qty is >>>'+newLine.Quantity__c);
            newLine.Material_Order__c = record.id;
            linesToAdd.add(newLine);
         }
         insert linesToAdd;
         
         pageReference enterAmount = new pageReference('/'+record.id);
          //pageReference enterAmount = new pageReference('/apex/enterAmt?id='+record.id);
          return enterAmount; 
         }
}

 VF Code: 

<apex:page standardController="Material_Order__c" extensions="materialOrderWrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!productList}" var="c" id="table">
                <apex:column >
                    <apex:inputText value="{!c.qty}"/>
                </apex:column>
            <apex:column value="{!c.cProductvod.Name}" headerValue="Product"/>
            <apex:column value="{!c.cProductvod.Image__c}" headerValue="Image"/>   
            <apex:column value="{!c.cProductvod.id}"/> 
        </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 

I have a deep clone process executing on the opportunity object which writes the resulting new record link to the originating opportunity. The opporutnities are locked after an approval process before being set to closed won and the  clone doesn't happen until after the opportunity is set to won so the process is failing.  

 

I'm not seeing anything obvious that will allow me to unlock the record, make the update and then relock it - am I missing something or is it not possible? 

 

Thanks,

JoAnn

I'm sending an outbound email message and the code I'm using to select the email address is adding the address to the string array twice. I'm not seeing what this happening - any ideas? Ultimately, I need to be able to pass in either the personEmail to the string OR the Secondary_Email__c but am having this issue with the email address being passed in twice that I have to solve first. 

 

 

//some other code logic
//

public pageReference submitEmail(){

     
String[] toAddresses = new String[]{
                    [SELECT id, PersonEmail 
                     FROM Account 
                     WHERE id = :ApexPages.currentPage().getParameters().get('id')].PersonEmail
};

system.debug('email addresses are>>>>'+toAddresses);

emailHelper.sendEmail(toAddresses, acct.id, emailSelected, recipient.id); 


// Email Helper Class

Global class emailHelper {

public static void sendEmail(string[] toAddresses, id acct, String tempName, id recipient) {

    String usersName = userInfo.getFirstName()+' '+userInfo.getLastName();

  	//New instance of a single email message
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
	// Who you are sending the email to
   mail.setToAddresses(toAddresses);

   // The email template ID used for the email
   mail.setTemplateId([SELECT id, Name, Secondary_Email__c FROM EmailTemplate WHERE Name = :tempName].id);
          
   mail.setWhatId(acct);    
   mail.setBccSender(false);
   mail.setUseSignature(true);
   mail.setReplyTo([SELECT id, Email FROM User WHERE id = :UserInfo.getUserId()].email);
   mail.setSenderDisplayName(usersName);
   mail.setSaveAsActivity(true); 
   mail.setTargetObjectid(recipient); 
 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }  
}

 

Thanks for your help!

I am working on putting together a VF page that will export a parent record to the first worksheet in an excel document and a related list of child records to the second tab.  Using this great post from Neeraj Gupta, http://neerajgupta999.blogspot.in/2012/06/multisheet-excel-from-apex.html, I'm able to create the worksheet, but unable to write data to the worksheets.  I'm not well versed in XML so am having trouble seeing where the issue is. The VF Code and Controller Code I"m using as a proof of concept is below.    

 

VF Code: 

<apex:page id="pg" standardStylesheets="false" standardController="Account" extensions="controllerClass" contenttype="application/vnd.ms-excel#MultiSheetExcel.xls">
{!xmlheader}
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
  <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
      <Author></Author>
      <LastAuthor></LastAuthor>
      <Company></Company>
      <Version>11.6360</Version>
  </DocumentProperties>

  <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    <WindowHeight>8535</WindowHeight>
    <WindowWidth>12345</WindowWidth>
    <WindowTopX>480</WindowTopX>
    <WindowTopY>90</WindowTopY>
    <ProtectStructure>False</ProtectStructure>
    <ProtectWindows>False</ProtectWindows>
  </ExcelWorkbook>
 <Styles>
        <Style ss:ID="Default" ss:Name="Normal">
            <Alignment ss:Vertical="Bottom"/>
            <Borders/>
            <Font/>
            <Interior/>
            <NumberFormat/>
            <Protection/>
        </Style>
        <Style ss:ID="s23">
          <Font x:Family="Swiss" ss:Bold="1"/>
        </Style>
        <Style ss:ID="s22">
          <Alignment ss:Vertical="Bottom" ss:WrapText="1"/>
        </Style>
  </Styles>

  <Worksheet ss:Name="Account">
    <Table >
      
      
        
    <Row ss:StyleID="s23">
        <Cell><Data ss:Type="String">
                <apex:outputText escape="false" value="{!HTMLENCODE("Account Name")}"/>
              </Data></Cell>
    </Row>
 
 
 <!-- Repeat and create data -->
 <apex:repeat value="{!acct}" var="row">
      <Row>
        <Cell ss:StyleID="s22">
            <Data ss:Type="String">
                <apex:outputText escape="false" value="{!HTMLENCODE(row.Name)}"/>
            </Data>
        </Cell>
      </Row>
    </apex:repeat>
 
 
    </Table>
  </Worksheet>




  <Worksheet ss:Name="Contacts">
    <Table >
          
    <Row ss:StyleID="s23">
        <Cell><Data ss:Type="String"><apex:outputText escape="false" value="{!HTMLENCODE("First Name")}"/></Data></Cell> 
        <Cell><Data ss:Type="String"><apex:outputText escape="false" value="{!HTMLENCODE("Last Name")}"/></Data></Cell> 
    </Row>
 
 <!-- Repeat and create rows-->
    <!-- <apex:repeat value="{!cs}" var="2row">-->
    <Row>
     <Cell ss:StyleID="s22"><Data ss:Type="String"><apex:outputText escape="false" value="{!HTMLENCODE(2row.FirstName)}"/></Data></Cell>
     <Cell ss:StyleID="s22"><Data ss:Type="String"><apex:outputText escape="false" value="{!HTMLENCODE(2row.LastName)}"/></Data></Cell>
    </Row>
    <!--</apex:repeat>-->
   </Table>
  </Worksheet>
  </Workbook>
<apex:outputText value="{!endfile}" escape="false"/>
</apex:page>

  Controller: 

public without sharing class controllerClass{
  public string xmlheader {get;set;}
  public string endfile{get;set;}
  public Account acct{get;set;}
  public List<Contact> cs{get;set;}
 
  //-------------------------------------------------------------------------------------------------------------------------------
  //Constructor
  //-------------------------------------------------------------------------------------------------------------------------------
  public controllerClass() {
    //VF page gives some issues directly using the below code there, so wrap up in variable
    xmlheader ='<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?>';
    endfile = '</Workbook>';
  }
  
     public controllerClass(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }
    
    public Account getAcct(){
        return acct;
    }
    
    public List<Contact> getCs(){
        cs = [SELECT id, FirstName, LastName, Email, AccountId FROM Contact WHERE AccountId = :acct.id];
        return cs;
    }
 
}

 

I have a page that is giving the user the option to add line items to a catalog order. I'm able to display the catalog items, my debug code is showing that the setter is getting the integer entered into the input field, but either no line items get added or all items are added, not just the ones that have a value entered in the field.  I'm not seeing the issue and am hoping that the community sees something I"m missing. 

 

Here is my controller: 

public with sharing class selectableProduct {

    public Material_Order__c record;
    public Integer amount{get; set;}
    public Product_vod__c prod{get;set;}
    public List<Product_vod__c> productList=new List<Product_vod__c>();
    public List<Material_Order_Line_Item__c> linesToAdd=new List<Material_Order_Line_Item__c>();

    //set current material order in focus
    public selectableProduct(ApexPages.StandardController stdController){
        record = [SELECT id, Name, Date__c, Status__c, Notes__c
                    FROM Material_Order__c 
                    WHERE id =:ApexPages.currentPage().getParameters().get('id')];

    }
    
    //get list of available products to order
    public List<Product_vod__c> getProductList(){
        productList = [SELECT id, Name, Image__c FROM Product_vod__c WHERE Product_Type_vod__c = 'Order' ORDER BY Name ASC];
        return productList;
    }
    
    public Integer getAmount(){
        return amount;
      }
   public void setAmount(Integer a){
       this.amount = a;
       }
    
    //set amounts of selected items and insert line items on material order
    public pageReference placeOrder(){
    
        pageReference orderQtys = new PageReference('/'+record.id);
 
        for(Product_vod__c ps : productList){

            Material_Order_Line_Item__c newLine = new Material_Order_Line_Item__c();
          
           if((amount != NULL) || (amount != 0)){
            newLine.Products__c = ps.id;
            newLine.Quantity__c = amount;
            newLine.Material_Order__c = record.id;

            linesToAdd.add(newLine);
            }
        }
        insert linesToAdd;
        return orderQtys;
    }
    
}

 

And here is the VF Code: 

<apex:page standardController="Material_Order__c" extensions="selectableProduct">
<apex:form >
<apex:pageBlock title="Products">
  <apex:pageBlockButtons >
    <apex:commandButton action="{!placeOrder}" value="Submit"/>
  </apex:pageBlockButtons>
<apex:pageBlockSection title="Available Line Items" columns="1">
  <apex:dataTable value="{!productList}"  var="prod" width="95%" cellpadding="5">
    <apex:column width="10%" headerValue="Amount">
      <apex:facet name="header"/>
      <apex:inputText value="{!amount}"/>
    </apex:column>
    <apex:column width="20%">
      <apex:facet name="header">Product</apex:facet>
      <apex:outputText value="{!prod.Name}"/>
    </apex:column>
    <apex:column width="70%">
      <apex:facet name="header">Image</apex:facet>
      <apex:outputField value="{!prod.Image__c}"/>
    </apex:column>
  </apex:dataTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

 

Thanks for your help in advance!

JoAnn

I have a list I need to sort by a primary key as well as a secondary key - I tried ORDER BY fieldName AND fieldNAME as well as ORDER BY fieldName AND BY fieldName - neither one compiled on save. 

 

Any ideas? 

 

Thanks!

 

JoAnn

Hi All,

I'm working on some test code for a trigger that flags a check box is the owner's user role and the invitee user role are part of a list defined in a custom setting. The trigger works as expected, however, when testing the trigger, I am not getting the isGroupEvent flag to populate. I've found several posts around this issue, but the solutions posted have not worked for me. Below is the code, any suggestions would be VERY appreciated.
 
@isTest
private class testEventUpdateTrigger {
    
    private testMethod static void testEventTrigger(){
        //find users with appropriate roles to generate joint meeting flag
        User BHFAUser = [SELECT id, UserRoleId, UserRole.Name FROM User WHERE UserRole.Name = 'Financial Advisor BHFA - Arizona FA' LIMIT 1];
        User preferredUser = [SELECT id, UserRoleId, UserRole.Name FROM User WHERE UserRole.Name = 'Preferred - AZ Premier Bankers' LIMIT 1];
        
        //test 1 - insert an event & verify that the joint meeting flag was set to false.
        system.runAs(BHFAUser){
            Event e1 = new Event(Subject='Test', StartDateTime = date.today(), DurationInMinutes = 60);
            insert e1;
            system.assert(!e1.Joint_Meeting__c);
            
            //Add an Event Relation Record
            EventRelation er1 = new EventRelation(EventId = e1.id, RelationId = preferredUser.id, IsInvitee=true,
                                                 Status='New');
            insert er1;
           	
            e1.Description = 'invited new user';
            update e1;

            system.debug('is group event flag>>>'+e1.IsGroupEvent);
            
            //this assert is failing
            system.assert(e1.Joint_Meeting__c);
            
        }
    }
    

}

 
Hi,

I need to render the background color of a cell based on the value in the cell. The value is retrieved from the a map generated by the controller. The background color will be one of seven colors based on the value retrieved. I have a method written that sets the value of the color as a string and takes the value of the rendered double as an arguement.

It's returning an error "Unknown property 'heatMapController.color'. I figured out from other posts in the forum about this error  that the system is looking at the statement:

style="{!color(defendNTAPNum[o.id])}"

as a function instead of a method call, but how do I call the method and pass the value in?  The method signature is:  String getColor(Double Val)

Here is the method:
public string getColor(Double val){
        color = '';
        if(val >= 0 && val < 25){
            color='background-color:#FF0000;';
        }
        if(val >= 25 && val < 50){
            color='background-color:#FF1493;';
        }
        if(val >= 50 && val < 75){
            color='background-color:#FFB6C1;';
        }
        if(val >= 75 && val < 85){
            color='background-color:#FFFF00;';
        }
        if(val >= 85 && val < 95){
            color='background-color:#ADFF2F;';
        }
        if(val >= 95 && val < 100){
            color='background-color:#9ACD32;';
        }
        if(val == 100){
            color='background-color:#228B22;';
        }
        return color;
    }


And this is how I'm calling it:

<apex:column headervalue="SitNum" style="{!color(defendNTAPNum[o.id])}">



Thank you for your feedback!
Hi, I have a trigger in place that updates the product schedule dates if the Opportunity close date changes.  The trigger works exactly as expected, however, I'm unable to test it adequately. The test logic does not insert the default product schedules automatically, so I'm trying to insert them manually so I can generate adequate coverage. However, the code fails on insert when I try to insert the OpportunityProductSchedule record, the error is: 

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

When I looked up the Object reference for OpportunityLineItemSchedule, it shows as createable so I'm not sure what the issue is - anyone been able to test product schedules? All of the posts I found it looks like other people are having the same issues and am not finding any resolutions posted. 

APEX Trigger and Class: 
trigger updateProdScheduleTrigger on Opportunity (after update) {
   
    Set<id> olisIds = new Set<id>();
    Set<id> opptyIds = new Set<id>();
   
    for(Opportunity o : trigger.new){
        if(o.CloseDate != trigger.oldMap.get(o.id).CloseDate){
     opptyIds.add(o.id);
        }
    }
    if(!opptyIds.isEmpty()){
    List<OpportunityLineItem> oli = [SELECT id FROM OpportunityLineItem WHERE OpportunityId IN :opptyIds AND HasRevenueSchedule = TRUE];
        if(!oli.isEmpty()){
            for(OpportunityLineItem olis : oli){
                olisIds.add(olis.id);
            }
        }
        updateProductSchedule.updateSchedule(olisIds);
    }

}

public class updateProductSchedule{
   
   
    public static void updateSchedule(Set<id> olisIds){
       
        List<OpportunityLineItem> olis = [SELECT id, OpportunityId, Opportunity.CloseDate, UnitPrice
                                          FROM OpportunityLineItem
                                          WHERE Id IN :olisIds];
        Map<String, Date> lineCloseDate = new Map<String, Date>();
        for(OpportunityLineItem o : olis){
            lineCloseDate.put(o.id, o.Opportunity.CloseDate);
        }
       
        List<OpportunityLineItemSchedule> oliSchedules = new List<OpportunityLineItemSchedule>();
       
  oliSchedules = [SELECT id, ScheduleDate, OpportunityLineItemId, Quantity, Revenue, Type, OpportunityLineItem.UnitPrice,
                        OpportunityLineItem.OpportunityId, OpportunityLineItem.Opportunity.CloseDate
                        FROM OpportunityLineItemSchedule
                        WHERE OpportunityLineItemId IN :olisIds ORDER BY ScheduleDate ASC];
      
        for(OpportunityLineItemSchedule os : oliSchedules){
            system.debug('current os schedule date>>>'+os.ScheduleDate +  ' and revenue>>>'+os.Revenue);
        }
   List<OpportunityLineItemSchedule> olischedToUpdate = new List<OpportunityLineItemSchedule>();       
       
       
        Date newStartSchedDate = oliSchedules[0].OpportunityLineItem.Opportunity.CloseDate;
        Decimal newREvScheduleAmt = oliSchedules[0].OpportunityLineItem.UnitPrice / 12;
        for(Integer i = 0; i<oliSchedules.size(); i++){
            oliSchedules[i].Revenue = newRevScheduleAmt;
            oliSchedules[i].ScheduleDate = newStartSchedDate.addMonths(i);
            olischedToUpdate.add(oliSchedules[i]);
            system.debug('current os schedule date>>>'+oliSchedules[i].ScheduleDate +  ' and revenue>>>'+oliSchedules[i].Revenue);
        }
        update olischedToUpdate;
      
    }

}

TEST Code: 

@istest (seeAlldata=True)
public class testUpdateProdSchedule{
    private testmethod static void testUpdateSched(){
       
        List<Account> accts = new List<Account>();
        for(integer i=0; i<200; i++){           
            Account a = new Account(Name='test'+i);
            accts.add(a);
        }
        insert accts;
       
        List<Opportunity> opptys = new List<Opportunity>();
        for(integer i=0; i<200; i++){
            Opportunity o = new Opportunity(Name='test'+i, AccountId = accts[i].id, CloseDate=date.today().addMonths(12),
                                            Amount=0, StageName='Proposed');
            opptys.add(o);
        }
        insert Opptys;
        Set<id> opptyIds = new Set<Id>();
        for(Opportunity o : opptys){
            opptyIds.add(o.id);
        }
        PricebookEntry pbe = [SELECT id, UnitPrice, Product2.NumberOfRevenueInstallments FROM PriceBookEntry
                              WHERE isActive=True
                              AND Product2.NumberOfRevenueInstallments = 12 LIMIT 1];
       
        system.debug('number of rev installments for pbe>>>'+pbe.Product2.NumberOfRevenueInstallments);
       
        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
        for(integer i=0; i<200; i++){
         OpportunityLineItem oli = new OpportunityLineItem();
            oli.OpportunityId=opptys[i].id;
            oli.PricebookEntryId=pbe.id;
            oli.Quantity=1;
            oli.UnitPrice=1200000;
            olis.add(oli);
        }
        insert olis;
        OpportunityLineItem line = [SELECT id FROM OpportunityLineItem WHERE PriceBookEntryId=:pbe.id LIMIT 1];
        List<OpportunityLineItemSchedule> oliSchedToInsert = new List<OpportunityLineItemSchedule>();
        for(integer i=0; i<12; i++){
            OpportunityLineItemSchedule s = new OpportunityLineItemSchedule();
            s.Revenue = 100000;
            s.ScheduleDate = date.today().addMonths(i);
            s.OpportunityLineItemId = line.id;
            s.type = 'Both';
            s.Quantity = 1;
           
            oliSchedToInsert.add(s);
        }
        insert oliSchedToInsert;
       
        List<OpportunityLineItemSchedule> oliSched = [SELECT id, Revenue, ScheduleDate,OpportunityLineItemId,
                                                      OpportunityLineItem.OpportunityId FROM OpportunityLineItemSchedule
                                                      WHERE OpportunityLineItem.OpportunityId IN : opptyIds];
       
        system.debug('size of schedule list>>>'+oliSched.size());
        //system.assertEquals(oliSched.size()>0, true);
        opptys[0].closeDate = date.today().addMonths(13);
        update opptys[0];
       
        List<Opportunity> opptysToUpdate = new List<Opportunity>();
       /* for(integer i=0;i<200; i++){
            opptys[i].CloseDate = date.today().addMonths(14);
            opptysToUpdate.add(opptys[i]);
        }
        update opptysToUpdate;*/
       
    }
}
I am building custom VF page for "Add Products". For most part it works fine, but it does create "OpportunityLineItemSchedule" records like standard "Add Products" screen.

What am I missing? Is there a way to set certain parameters to parent OpportunityLineItem object to achieve this? I found few examples on creating "OpportunityLineItemSchedule" records manually, but I would like to avoid that if Salesforce can do that automatically for me.

Thank you for your time.

regards
Mitesh
Hi Everyone, hoping there is someone that is seeing something I'm not.  I have the following trigger, setRegPartnerTrigger that calls the APEX Class setRegPartner. The test code is testSetRegPartner. The test code executes with no issues in sandbox, the test leads are inserted, updated and result in 95% plus coverage. When I try to deploy, the test code errors out telling me it can't insert the first lead. 

I have run the code from the trigger and the test lead insert in an execute anonomyous window successfully so am completely stumped.  Hoping someone sees something I'm missing. 

APEX CLASS: 
public class setRegPartner{

    public static void setPartnerLookUp(Set<Id> dealRegIds){
        system.debug('number of leads received by SetPartnerOnDealReg class>>>'+dealRegIds.size());
        List<Lead> dealRegs = new List<Lead>();
        //put the leads in the trigger into a list for processing
        dealRegs = [SELECT id, Name, FirstName, LastName, Email, Phone, City, State, PostalCode, Company,
                            Deal_Registration_Status__c, Deal_Product__c, Deal_Registration_Date__c, deal_exp_close_date__c,
                            Deal_Registration_Expiration__c, Registered_Reseller__c, Preferred_Reseller__c,
                            Reseller_Sales_Person__c, Reseller_Phone_Number__c, Registered_Partner_Rep_Email__c,
                            Reseller_Region__c, Distributor__c, Deal_Distributor__c, Reseller_Rep__c
                            FROM Lead WHERE id IN :dealRegIds];
        system.debug('Deal Reg '+dealRegs);
        system.debug('number of leads in dealRegs List>>>'+dealRegs.size());
        //put partner account and reps into maps for later retrieval
        Map<String, Account> ptnrAccts = new Map<String, Account>();
        Map<String, Contact> ptnrReps = new Map<String, Contact>();
        Map<string, Account> ptnrDomains = new map<String,Account>();
       
        Set<String> acctTypes = new Set<String>();
        acctTypes.add('Var- Other');
        acctTypes.add('Var- Preferred');
        acctTypes.add('DMR');
        acctTypes.add('Etail');
        List<Account> ptnrs = new List<Account>();
        ptnrs = [SELECT id, Name, Type, OwnerId, email_domain__c FROM Account WHERE
                 Type IN :acctTypes];

        system.debug('partner type VAR- Other'+ptnrs);
        set<id> ptnrAcctIds = new Set<id>();
        set<string> emailset = new set<string>();
       
            for(Account a : ptnrs){
                ptnrAccts.put(a.Id, a);
                ptnrAcctIds.add(a.id);
                if(string.isNotblank(a.email_domain__c)){
                    ptnrDomains.put(a.email_domain__c, a);
                }
            }
            List<Contact> repList = [SELECT id, AccountId, FirstName, LastName, Email,
                          Phone, Account.OwnerId FROM Contact
                          WHERE AccountId IN :ptnrAcctIds];
              
            for(Contact c : repList){
                    system.debug('email for rep>>>'+c.email);
                    ptnrReps.put(c.email, c);
                    emailset.add(c.email);
                }
           
            system.debug('contact emails----   '+emailset);
            List<Contact> contactsToInsert = new List<Contact>();
        for(Lead l : dealRegs)
        {
            if (emailset.contains(l.Registered_Partner_Rep_Email__c))
              system.debug('email exist');
              else
              system.debug('doesnt exist');
        }
        //system.debug('print partner Account'+ptnrAccts);
        //system.debug('print partner Contact'+ptnrReps);
       
       Map<String, Account> distyAccts = new Map<String, Account>();
   
    //put distributors accounts into map
       List<Account> distys = new List<Account>();
        distys = [SELECT id, Name, Type, OwnerId FROM Account WHERE Type = 'Distributor'];
            for(Account d : distys){
                distyAccts.put(d.Name, d);
                }

        list<Lead> leadsToUpdate = new List<Lead>();
       
        for(Lead l : dealRegs) {
          String email =  l.Registered_Partner_Rep_Email__c;
                list <String> extractEmail = email.split('@');
                system.debug('email array'+ extractEmail);
                email = extractEmail[1];
            if(emailset.contains(l.Registered_Partner_Rep_Email__c)) {
                           
                    string acctId = ptnrReps.get(l.Registered_Partner_Rep_Email__c).Accountid;
                    l.Reseller_Rep__c = ptnrReps.get(l.Registered_Partner_Rep_Email__c).id;
                    l.Registered_Reseller__c = acctId;
                    l.Deal_Distributor__c = distyAccts.get(l.Distributor__c).id;
                    l.OwnerId = ptnrReps.get(l.Registered_Partner_Rep_Email__c).Account.OwnerId;
                    leadsToUpdate.add(l);                        
               
            } else if(!emailset.contains(l.Registered_Partner_Rep_Email__c) && ptnrDomains.get(email) != NULL){
                system.debug('doesnt exist');
               
               
                        String fName = l.Reseller_Sales_Person__c.left(l.Reseller_Sales_Person__c.indexOf(' '));
                        String lName = l.Reseller_Sales_Person__c.right(l.Reseller_Sales_Person__c.length()-

            l.Reseller_Sales_Person__c.indexOf(' '));                                              
                       
                        Contact newContact = new Contact();
                        newContact.FirstName = fName;
                        newContact.LastName = lName;
                        newContact.Email =l.Registered_Partner_Rep_Email__c;
                        newContact.Phone = l.Reseller_Phone_Number__c;
                        newContact.AccountId = ptnrDomains.get(email).id;
                       
                        system.debug('insert contact ' +newContact);
                        insert newContact;
                      l.Reseller_Rep__c = newContact.id;
                      l.Registered_Reseller__c = newContact.AccountId;
                      l.Deal_Distributor__c = distyAccts.get(l.Distributor__c).id;
                      leadsToUpdate.add(l);
               
            } else {
                   l.Partner_Status__c = 'Not Found';
                    leadsToUpdate.add(l);                        
                }
            }
        update leadsToUpdate;
    }
}

TRIGGER: 
trigger setRegPartnerTrigger on Lead (after insert) {
  Set<id> leadIds = new Set<id>();

    for(Lead l : trigger.new){
         
        if(l.LeadSource == 'Deal Registration'){
              system.debug(l); 
            leadIds.add(l.id);
        }
    }
    system.debug('number of leads sent to setRegPartner class>>>'+leadIds.size());   
    setRegPartner.setPartnerLookUp(leadIds);
   
}

TEST CODE: 
@isTest (seeAllData=true)
public class testSetRegPartner{
 
    static testmethod void testRegPartner(){
       
       Account disty = new Account(Name='Ingram Micro', Type='Distributor', Customer_ID__c = 'ING4051', email_domain__c = 'ingram.com');
       insert disty;
       Account ptnr = new Account(Name='Partner', Type='VAR- Other', Customer_ID__c = 'other123', email_domain__c = 'partner.com');
       insert ptnr;
       Contact rep = new Contact(FirstName='Pard', LastName='Rep', Email = 'pard@partner.com', Accountid = ptnr.id);
         insert rep;
       Contact distyRep = new Contact(FirstName='disty', lastName='Rep', Email='disty@rep.com', Accountid=disty.id, Deal_Registration_Contact__c = 'yes');
        insert distyRep;
       
       String DealRegRecTypeId = [SELECT id FROM RecordType WHERE SobjectType = 'Lead' and Name ='Partner Deal Registrations'].id;
      Lead noRepAcct = new Lead();
          noRepAcct.RecordTypeId = DealRegRecTypeId;
            noRepAcct.LeadSource = 'Deal Registration';
            noRepAcct.FirstName = 'first';
            noRepAcct.LastName = 'last';
            noRepAcct.Email = 'a@b.com';
            noRepAcct.City = 'mapleton';
            noRepAcct.State = 'IL';
            noRepAcct.PostalCode = '12345';
            noRepAcct.Company = 'test';
            noRepAcct.Deal_Registration_Status__c = 'Submitted';
            noRepAcct.Deal_Product__c = 'B800i';
            noRepAcct.Deal_Registration_Date__c = date.today();
            noRepAcct.deal_exp_close_date__c = date.today().addDays(30);
            noRepAcct.Preferred_Reseller__c = 'testReseller';
            noRepAcct.Reseller_Sales_Person__c = 'Test Rep';
            noRepAcct.Reseller_Phone_Number__c = '123-123-1234';
            noRepAcct.Registered_Partner_Rep_Email__c = 'tr@tp.com';
            noRepAcct.Distributor__c = 'Ingram Micro';
            noRepAcct.deal_unit_qty__c = 5;
        insert noRepAcct;
       
        Lead acctNoRep = new Lead();
            acctNoRep.RecordTypeId = DealRegRecTypeId;
            acctNoRep.LeadSource = 'Deal Registration';
            acctNoRep.FirstName = 'first';
            acctNoRep.LastName = 'last';
            acctNoRep.Email = 'a@b.com';
            acctNoRep.City = 'mapleton';
            acctNoRep.State = 'IL';
            acctNoRep.PostalCode = '12345';
            acctNoRep.Company = 'test';
            acctNoRep.Deal_Registration_Status__c = 'Submitted';
            acctNoRep.Deal_Product__c = 'B800i 8TB';
            acctNoRep.Deal_Registration_Date__c = date.today();
            acctNoRep.deal_exp_close_date__c = date.today().addDays(30);
            acctNoRep.Preferred_Reseller__c = 'testReseller';
            acctNoRep.Reseller_Sales_Person__c = 'Test Rep';
            acctNoRep.Reseller_Phone_Number__c = '123-123-1234';
            acctNoRep.Registered_Partner_Rep_Email__c = 'tr@partner.com';
            acctNoRep.Distributor__c = 'Ingram Micro';
            acctNoRep.deal_unit_qty__c = 5;
        insert acctNoRep;
       
        Lead acctRep = new Lead();
          acctRep.RecordTypeId = DealRegRecTypeId;
            acctRep.LeadSource = 'Deal Registration';
            acctRep.FirstName = 'first';
            acctRep.LastName = 'last';
            acctRep.Email = '1@b.com';
            acctRep.City = 'mapleton';
            acctRep.State = 'IL';
            acctRep.PostalCode = '12345';
            acctRep.Company = 'test';
            acctRep.Deal_Registration_Status__c = 'Submitted';
            acctRep.Deal_Product__c = 'B800i';
            acctRep.Deal_Registration_Date__c = date.today();
            acctRep.deal_exp_close_date__c = date.today().addDays(30);
            acctRep.Preferred_Reseller__c = 'testReseller';
            acctRep.Reseller_Sales_Person__c = 'Test Rep';
            acctRep.Reseller_Phone_Number__c = '123-123-1234';
            acctRep.Registered_Partner_Rep_Email__c = 'pard@partner.com';
            acctRep.Distributor__c = 'Ingram Micro';
            acctRep.deal_unit_qty__c = 5;
        insert acctRep;
       
        system.assertEquals(acctNoRep.Partner_Status__c, NULL);
        system.assertEquals(acctRep.Partner_Status__c, NULL);
        system.assertEquals(noRepAcct.Partner_Status__c, NULL);
       
        Set<id> dealRegIds = new Set<id>();
        dealRegIds.add(acctRep.id);
       
        setRegPartner.setPartnerLookUp(dealRegIds);
        acctRep.Deal_Registration_Status__c = 'Approved';
        update acctRep;

       
    List<Lead> testLeads = new List<Lead>();
    testLeads.add(acctRep);
   
    convertLead c = new convertLead();
    c.convertLeads(testLeads);
    List<Lead> convLead = [SELECT id, Distributor__c, ConvertedOpportunityId FROM
                Lead WHERE id = :acctRep.id];
               
    Quote q = [SELECT id, Distributor__c FROM Quote WHERE OpportunityId = :convLead[0].ConvertedOpportunityId];
   
    c.sendDistyEmail(q);
   
    acctNoRep.Deal_Registration_Status__c = 'Approved';
        update acctNoRep;
       
    List<Lead> testLeads2 = new List<Lead>();
    testLeads2.add(acctNoRep);
   
    convertLead d = new convertLead();
    d.convertLeads(testLeads2);
    List<Lead> convLead2 = [SELECT id, Distributor__c, ConvertedOpportunityId FROM
                Lead WHERE id = :acctNoRep.id];
               
    Quote q2 = [SELECT id, Distributor__c FROM Quote WHERE OpportunityId = :convLead2[0].ConvertedOpportunityId];
    List<QuoteLineItem> qlis = [SELECT id FROM QuoteLineItem WHERE QuoteID = :q2.id];
        system.debug('test code qlis size is>>>'+qlis.size());
    system.assertEquals(qlis.size(), 1);
   
    }
}

I'm using an @future (callout=true) method to make a callout to a webservice for an xml file. If I remove the @future annotation and make the method not static it compiles with no problem and calls the readResponse method. If I keep it as a static method, I'm unable to call the readResponse or the getValueFromTag method. I know I'm missing something obvious but am just not finding it in the documentation, hoping   

My code is using the example posted on the developer relations blog this summer at http://blogs.developerforce.com/developer-relations/2013/08/integrating-force-com-using-xml-in-apex.html

public class parseExample{
    public Policy_Information__c polInfo{get;set;}
    public List<Policy_Information__c> polInfoToInsert = new List<Policy_Information__c>();
   
    @future(callout=true)
    public static void requestIvans(){
        Http h = new Http();
      HttpRequest req = new HttpRequest();
  HttpResponse res = new HttpResponse();
        String url = 'https://s3.amazonaws.com/XXX/XXXX.xml';
        req.setEndPoint(url);
        req.setMethod('GET');
  res = h.send(req);
        String response = res.getBody();
  XmlStreamReader reader = new XmlStreamReader(response);
        system.debug('reader response is>>>'+response.left(25));
     readResponse(reader);  
    }

    public void readResponse(XmlStreamReader reader) {
     // Is there any element next?
        while (reader.hasNext()) {
            // Is the next element an opening tag?
            if (reader.getEventType() == XmlTag.START_ELEMENT) {
                // Set Account Details
                if ('CommercialName' == reader.getLocalName()) {
                    // if opening tag of account is found initialize polInfo Record
                    polInfo = new Policy_Information__c();
                } else if ('CommercialName' == reader.getLocalName()) {
                    polInfo.Insured_Name__c = getValueFromTag(reader);
                } else if ('Addr1' == reader.getLocalName()) {
                    polInfo.Address1__c = getValueFromTag(reader);
                }else if ('City' == reader.getLocalName()){
                    polInfo.City__c = getValueFromTag(reader);
                } else if('StateProvCd' == reader.getLocalName()){
                    polInfo.State__c = getValueFromTag(reader);
                }else if('PostalCode' == reader.getLocalName()){
                    polInfo.Zip__c = getValueFromTag(reader);
                }
                system.debug('polInfo record details>>>'+polInfo);
                //set policy information
               
            } else if (reader.getEventType() == XmlTag.END_ELEMENT) {
                // Is the next element an end tag? If yes is it an Account or an Accounts tag?
                if ('PolicyDetail' == reader.getLocalName()) {
                    // If you find end tag called account, push the account record in list
                    polInfoToInsert.add(polInfo);
                    system.debug('number of polstoInsert>>>'+polInfoToInsert.size());
                } else if ('IVANSExtract' == reader.getLocalName()) {
                    // We have reached end of file, just exit
                    break;
                }
            }
        }
          insert polInfoToInsert;
    }

// This is an extra function to read data between opening and closing tag.
// It will return the string of value from between tags
public string getValueFromTag(XMLStreamReader reader) {
    String DataValue;

    while (reader.hasNext()) {
        if (reader.getEventType() == XmlTag.END_ELEMENT) {
            break;
        } else if (reader.getEventType() == XmlTag.CHARACTERS) {
            DataValue = reader.getText();
        }
        reader.next();
    }

    return DataValue;
}
}


I'm working my way through the Heroku workbook and have hit a roadblock early in the process. I have installed Ruby and the Heroku toolbelt and am trying to set up a Gemfile as documented in the workbook. 

 

I can run the $gem install bundler command, but when I try to execute the next step, $bundle install - I get the following error: 

Bundler: GemfileNotFound

 

Any suggestions? I have a file called Gemfile.rb in the workbook directory. What am I missing? 

 

Thanks,

 

Hi All,

 

I need help in Importing large CSV files via Batch Apex. Tried this link --> http://developer.financialforce.com/customizations/importing-large-csv-files-via-batch-apex/ .But I am unable to implement it.

 

Kindly help.

I'm calling a static method from a trigger. I had all the of the methods in one originally, but had to change it to support bulk processing.  I'm using a design pattern I've used elsewhere successfully, however for some reason, I'm not getting past the initial queries in the method. I'm not seeing why that's happening and am hoping someone has a suggestion. 

 

Thanks!

JoAnn

 

Trigger: 

trigger notifyPtnrOfNewLead on Lead (after insert, after update) {
    	List<Lead> leadsInTrigger = new List<Lead>();
    	String[] ptnrs= new List<String>();

    
    if(!controlTriggerRecursion.hasAlreadyLooped()){
        
        for(Lead l: trigger.new){
               if(l.Preferred_Partner_for_Tech_Purchases__c.length()>0){
                   leadsIntrigger.add(l);
                   ptnrs.add(l.Preferred_Partner_for_Tech_Purchases__c);
                    }
        }
    }
    		controlTriggerRecursion.setHasAlreadyLooped();
        	ptrCampaignHandling.findPtrCampaign(leadsInTrigger,ptnrs);
       
}

 

 

Class & Method: 

 

public class ptrCampaignHandling{
    
    public static void findPtrCampaign(List<Lead> ptrLead, String[] cmpaignPtr){

Map<String, Campaign> ptnrCampaignMap = new Map<String, Campaign>(); //This Query and the one for Accounts below are looping, but I'm not understanding why...
List<Campaign> camps = [SELECT id, Name, Campaign_Partner__c, Primary_Partner_Contact__c, Email_Template_Name__c, isActive, StartDate, EndDate, Type, Primary_Partner_Contact__r.Email FROM Campaign WHERE Type = 'Partners' AND IsActive = True]; for(Campaign cmp : camps){ ptnrCampaignMap.put(cmp.Name,cmp); } Map<String, Id> cmpPartnerId = new Map<String, Id>(); List<Account> ptrAccts = [SELECT id, Name FROM Account WHERE Type = 'Partner' AND Partner_Status__c = 'Agreement Signed' ORDER by CreatedDate DESC]; for(Account pa: ptrAccts){ cmpPartnerId.put(pa.Name, pa.id); } Map<Lead, Id> cmsToCreate = new Map<Lead, Id>(); List<Lead> newCampaignsToCreate = new List<Lead>(); for(Lead newLead : ptrLead){ String campName = newLead.pi_campaign__c + ' - ' + newLead.Preferred_Partner_for_Tech_Purchases__c; Campaign ptnrCampaign = ptnrCampaignMap.get(campName); if(ptnrCampaign != NULL){ cmsToCreate.put(newLead, ptnrCampaign.id); } else { newCampaignsToCreate.add(newLead); } } insertCamp(newCampaignsToCreate, cmpPartnerId); createNewCampMembers(cmsToCreate); } public static void insertCamp(Lead[] newCampsToCreate, Map<String, Id> cmptrList){ List<Campaign> newCampsToInsert = new List<Campaign>(); String[] CampaignPartners; for(Lead l : newCampsToCreate){ String campName = l.pi_campaign__c + ' - ' + l.Preferred_Partner_for_Tech_Purchases__c; Campaign newPtnrCampaign = new Campaign(); newPtnrCampaign.Name = campName; newPtnrCampaign.Type = 'Partners'; newPtnrCampaign.StartDate = date.today(); newPtnrCampaign.EndDate = date.today().addMonths(3); newPtnrCampaign.Campaign_Partner__c = newPtnrCampaign.Primary_Partner_Contact__c = cmptrList.get(l.Preferred_Partner_for_Tech_Purchases__c); newPtnrCampaign.isActive = true; newPtnrCampaign.Email_Template_Name__c = l.pi_campaign__c + ' - Lead Notification'; newcampsToInsert.add(newPtnrCampaign); campaignPartners.add(cmptrList.get(l.Preferred_Partner_for_Tech_Purchases__c)); } insert newCampsToInsert; findPtrCampaign(newCampsToCreate, campaignPartners); } public static void createNewCampMembers(Map<Lead, Id> newCM){ CampaignMember cm = new CampaignMember(); List<CampaignMember> cmsToInsert = new List<CampaignMember>(); for(Lead l : newCM.keySet()){ cm.CampaignId = newCM.get(l); cm.LeadId = l.id; cm.Status = 'Responded'; cmsToInsert.add(cm); } insert cmsToInsert; } }

 

 

Hoping someone can point me in the right direction - I'm bumping against what I think is a logic issue here but can't see my way out of it.

 

I'm trying to create a map of accounts and domain names associated with the account.  The Domains field is a long text field and may have multiple domains listed separated by commas, i.e. bankofamerica.com, boa.com, bankamerica.com etc.

 

When a lead comes into the system, the email domain is parsed out and compared to the domains listed for each account and if a match is found, the lead type is set based on some values of the the account found.  I can get it working perfectly if there is only one domain listed, but as soon as there are multiple domains listed, I can't get the match to work.  

 

I have tried it using a SOSL query, however, I bump up against governor limits very quickly which is a problem when loading lists of leads. 

 

The lastest iteration takes a list of accounts with domains listed and puts them into a map<String, Account>. If there is more than one domain listed in the field, I'm parsing the domains into a list so I can put each domain in as a separate key for the account they belong to, however, I can't get the account to match up to the second domain when I loop through and am instead getting a null value for the account.  I have verified that the domain names are parsing out correctly and that the account remains in scope and the code loops through the generated list of domains for the account the right number of times, however, I can't get the account to go into the map the second time. 

 

My code is below - any suggestions/thoughts would be greatly appreciated!

 

public class setLeadType{

   public static void setLeadAccountType(Lead[] newLeads){
   	   List<String> typeValues = new List<String>();
       List<Account> accts = [SELECT Id, Name, Type, Partner_Status__c, Domains__c, Active_Subscription__c, 
                               		First_Subscription__c, Active_Funnel__c,Customer_Type_Subscription__c,Target_Category__c,
                                    Closed_Amount__c, Website, Closed_Subscription_Transactions__c
                               FROM Account 
                               WHERE Domains__c != NULL];
        map<String, Account> acctDomains = new Map<String,Account>();
       
 
        for(Account a : accts){
            if(a.Domains__c.containsNone(',')){
        		acctDomains.put(a.Domains__c, a);
            } else {
               	List<String> doms = a.Domains__c.split(',');
					for(String s : doms){
                 	   acctDomains.put(s, a);
//HERE IS WHERE I'M HAVING AN ISSUE - THE FIRST DOMAIN/ACCOUNT PAIR IS PUT INTO THE MAP, BUT THE SECOND IS NOT
               	}
           	}
         }
       
        for(Lead ls : newLeads){
            ls.Type_of_Lead__c = NULL;
            Account acct = new Account();
            acct = acctDomains.get(ls.Domain__c);
        	if(acct!=NULL){
                if(acct.Type == 'Partner' && string.isNotEmpty(acct.Partner_Status__c))
                    if(acct.Partner_Status__c != 'Prospect' || acct.Partner_Status__c  != 'Rejected' || 
                    acct.Partner_Status__c  != 'Terminated'){
                    typeValues.add('Existing Partner');
                }
                if(acct.Active_Subscription__c != False && acct.Closed_Subscription_Transactions__c>0){
                    typeValues.add('Active Subscription Customer');
                }    
            if(acct.Active_Funnel__c > 0){
                typeValues.add('Active Funnel');
            }
            if(acct.Active_Subscription__c == False && acct.Closed_Subscription_Transactions__c > 0){
                    typeValues.add('Previous Subscription Customer');
                } 
                if(acct.Closed_Amount__c > 0 && 
                   acct.Active_Subscription__c == False && 
                   acct.Closed_Subscription_Transactions__c == 0){
                    typeValues.add('Non-Subscription Purchase');
                } 
                if(string.isNotEmpty(acct.Target_Category__c) && acct.Target_Category__c == 'Data Warehouse'){
                    typeValues.add('Data Warehouse');
                } 
                if(string.isNotEmpty(acct.Target_Category__c)&& acct.Target_Category__c == 'Fortune/Forbes/Global'){
                     typeValues.add('Fortune/Global');
                }
            String lsType = string.join(typeValues, ';');
            ls.Type_of_Lead__c = lsType;
			
        	}
        }
    }
    public static void setLeadPersonalLeadType(Lead[] ignoreLeads){
        for(Lead l : ignoreLeads){
            l.Type_of_Lead__c = NULL;
        }
    }    
}

 

Thanks!

Hi All,

        

I have create custom User lookup field in Account,Field Name is SalesRep.When i select user name(John) and save the account.  Opportunity Owner name chanege as (john) on Opportunity in the Account

 

I can't deploy it to production because I'm not able to create a test class for it... . The code is below, can someone help me build a test class for it? 

 

trigger Opportunity_SalesRep on Account(after update) {
     List<Id> accIds = new List<Id>(); 
     for(Account acc : trigger.New){
         //check if salesrep changed
         if(acc.EXO_Sales_Rep__c != trigger.oldMap.get(acc.Id).EXO_Sales_Rep__c){
              accIds.add(acc.Id);
         }
     }
    //query all the matching opps
    List<Opportunity > oppList = [SELECT Id,AccountId FROM Opportunity WHERE AccountId IN:accIds];

    for(Opportunity opp : oppList ){
    if(trigger.NewMap.containsKey(opp.AccountId)&&
trigger.NewMap.get(opp.AccountId).EXO_Sales_Rep__c != null){
          opp.OwnerId = trigger.NewMap.get(opp.AccountId).EXO_Sales_Rep__c;
          }
 }
     
 update oppList; 
}

I have a VF Component that I need to include in a tabbed page - the name of the tab refers to the attribute I'm passing to the component to determine which record I want displayed in the panel.  

 

My component controller has a getter and setter for the component attribute and has a getter for the record but no data is being passed back unless I hard code the attribute value in the controller. 

 

Here is the controller: 

public class fcrCompetencyController{

  public Competency__c comp{get;set;}
  public String compType{get;set;}
  
  public fcrCompetencyController(){
      comp=[SELECT id, Description__c, Competency_Type__c, Name 
                      FROM Competency__c 
                      WHERE Active__c = True];
   }
 
  public Competency__c getComp() {
    return comp;
  } 
 
  public void setCompType(String s){
      compType = s;
      }
        
  public String getCompType(){
      return compType;
      }

}

 And my component is: 

<apex:component controller="fcrCompetencyController">
    <apex:attribute name="competency" assignTo="{!compType}" type="String" description="Compentency Displayed"/>
    <apex:outputField value="{!comp.Name}"/>
    <apex:outputField value="{!comp.Description__c}"/>
</apex:component>

 

This is the test page I'm using to try to get it displayed, the actual page is much longer: 

<apex:page controller="fcrCompetencyController">
<apex:pageBlock title="{!comp}">
<apex:outputText value="comptype is {!compType}"/>
<c:competencyDisplay competency="Pre/Post Call Analysis"/>
</apex:pageBlock>
</apex:page>

 I'm not sure where to go next, every example I can find and all the documentation I've found it seems I have everything covered, but am unable to get this working. 

 

I need to display the Description__c field as a field, not text as it is a rich text field on the object and needs to be displayed as created. 

 

Any ideas?

 

Thanks!

I'm trying to count a group of records and get the total records by account and then put the account id and the number of child records into a map.  I keep getting an "incompatible key type for map" on compile and I'm not sure why. Hopeing somone has an idea!

 

If I take the map out and just look at the debug, it's pulling out the Account id as  a string...

 

Map<String, Integer> acctCalls = new Map<String, Integer>();

List<AggregateResult> r = [SELECT Account_vod__r.Name acctid, COUNT(id) totalCalls
                           FROM Call2_vod__c  
                           GROUP BY Account_vod__r.Name];
for(AggregateResult i : r){
    acctCalls.put(i.get('acctid'), i.get('totalCalls'));

    system.debug(' account>>> ' + i.get('acctid') + 'number of calls>>> '+i.get('totalCalls'));
}                         
  

 Thanks,

JoAnn

I have a wrapper class that creates a line item record on a parent record. The VF page lists the available items to add with an input text field that sets a integer with the quantity ordered.  The method is creating the record as expected, but the quantity is not being set properly. I'm not seeing what I'm missing in the process to properly set the quantity in the child record. Any suggestions? 

 

public class materialOrderWrapperClassController{

    public List<cProducvod> productList {get; set;}
    public Material_Order__c record;
    public List<Product_vod__c> availableProducts= new List<Product_vod__c>();
    public List<Material_Order_line_Item__c> linesToAdd {get;set;}
    public List<Material_Order_line_Item__c> qtysToUpdate {get;set;}
    public List<cProducvod> selectedProducts{get;set;}
    public Boolean hasProdSelect{get;set;}
    public Integer qty {get;set;}   
    
    public materialOrderWrapperClassController(ApexPages.StandardController stdController){
        record = [SELECT id, Name, Date__c, Status__c, Notes__c
                    FROM Material_Order__c 
                    WHERE id =:ApexPages.currentPage().getParameters().get('id')];
        
        selectedProducts = new List<cProducvod>();
        
       
        availableProducts = [SELECT id, Name, Image__c, Product_Type_vod__c 
                                FROM Product_vod__c 
                                WHERE Product_type_vod__c = 'Order'
                                ORDER BY Name ASC];
            //productList = new List<cProducvod>();
            if(productList == null){
              productList = new List<cProducvod>();                                        
              for(Product_vod__c p : availableProducts) {
                productList.add(new cProducvod(p));
            }
        }                                
    }
    

    public List<cProducvod> getProductList() {
         return productList;
    }
        
     public void setQty(Integer q){
         qty=q;
         }
         
     public Integer getQty(){
         return qty;
         }
         
     public pageReference processSelected(){
         selectedProducts.clear();
          hasProdSelect = false;
            for(cProducvod cProd: getProductList()) {
                if(cProd.qty > 0) {
                    selectedProducts.add(cProd);
                    system.debug('cProd qty is >>>>'+cProd.qty);
                    }
              }
        
        linesToAdd = new List<Material_Order_Line_Item__c>();
         for(cProducvod prdct : selectedProducts){
            Material_Order_line_Item__c newLine = new Material_Order_line_Item__c();
            newLine.Products__c = prdct.cProductvod.id;
            system.debug('newLine product name is>>>'+newLine.Products__c);
            newLine.Quantity__c = qty;
            system.debug('newLine qty is >>>'+newLine.Quantity__c);
            newLine.Material_Order__c = record.id;
            linesToAdd.add(newLine);
         }
         insert linesToAdd;
         
         pageReference enterAmount = new pageReference('/'+record.id);
          //pageReference enterAmount = new pageReference('/apex/enterAmt?id='+record.id);
          return enterAmount; 
         }
}

 VF Code: 

<apex:page standardController="Material_Order__c" extensions="materialOrderWrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!productList}" var="c" id="table">
                <apex:column >
                    <apex:inputText value="{!c.qty}"/>
                </apex:column>
            <apex:column value="{!c.cProductvod.Name}" headerValue="Product"/>
            <apex:column value="{!c.cProductvod.Image__c}" headerValue="Image"/>   
            <apex:column value="{!c.cProductvod.id}"/> 
        </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>