• KitagawaSan85
  • NEWBIE
  • 50 Points
  • Member since 2012

  • Chatter
    Feed
  • 2
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 14
    Replies

Hello, 

 

I have a custom object that is a child to the opportunity object. There is a trigger on that custom object that updates a field on the opportunity if a checkbox is marked as true. 

 

The trigger appears to be working when I do manual testing, but the test class system.asserts are failing. 

 

I can't figure out why the trigger is not functioning properly in the testClass, but works correctly in the UI. 

 

Any help would be greatly appreciated!!! 

 

Trigger

trigger UpdateOpptyLeadBusCon on Business_Consultant__c (before update, before insert, before delete) {

//Get the Business Consultant & Opportunity records
set<id> opportunitiesid = new set<id>();

//Set trigger.new or trigger.old depending on if isUpdate / isInsert / isDelete
if(trigger.isUpdate || trigger.isInsert){
    for(Business_Consultant__c buscon: Trigger.New) {
        opportunitiesid.add(buscon.Opportunity__c);
        }
    }else{
    for(Business_Consultant__c buscon: Trigger.Old) {
        opportunitiesid.add(buscon.Opportunity__c);
        }
}

//Create the lists of opportunities        
    List<Opportunity> updatelst = new List<Opportunity>();
    List<Opportunity> lstopp =[select id, Lead_bus_consultant__c from Opportunity where id IN:opportunitiesid];

 
//If isInsert && lead_consultant__c = True, then set the opportunity lead_bus_consultant__c
if(trigger.isInsert){
    for(Business_Consultant__c buscon:Trigger.New) {
        if(buscon.Lead_Consultant__c == TRUE) {
            for(Opportunity opp:lstopp) {
                 if(opp.id == buscon.opportunity__c) {
                     opp.Lead_bus_consultant__c = buscon.consultant__c;
                      updatelst.add(opp);
                 }
            }
        }
    }
}

//If isUpdate check to see if it is changed
if(trigger.isUpdate){
    
    for(Business_Consultant__c buscon:Trigger.New){
    Business_Consultant__c oldBusCon = Trigger.oldMap.get(buscon.Id);
    //If the checkbox has changed position and is no longer true, clear out the opportunity.lead_bus_consultant__c field
    if(Trigger.isUpdate && buscon.Lead_Consultant__c != oldBusCon.Lead_Consultant__c  && buscon.Lead_Consultant__c != TRUE){
        for(Opportunity opp:lstopp){
            if(opp.id == buscon.opportunity__c){
                opp.Lead_bus_consultant__c = null;
                    updatelst.add(opp);
            }
        } 
    }else{
    //Otherwise if the checkbox is checked, set the opportunity.lead_bus_consultant__c field as the consultant from the connector
    if(buscon.Lead_Consultant__c == TRUE) {
 
        for(Opportunity opp:lstopp) {
                 if(opp.id == buscon.opportunity__c) {
 
                     opp.Lead_bus_consultant__c = buscon.consultant__c;
                      updatelst.add(opp);
                }
        }
    }
    }
    }
} 
//If isDelete set the opportunity.lead_bus_consultant__c to null 
else {
if(trigger.isDelete){

    for(Business_Consultant__c buscon:Trigger.Old){
        Business_Consultant__c oldBusCon = Trigger.oldMap.get(buscon.Id);
        if(Trigger.isDelete && buscon.Lead_Consultant__c == TRUE){
            for(Opportunity opp:lstopp){
                if(opp.id == buscon.opportunity__c){
                    opp.Lead_bus_consultant__c = null;
                        updatelst.add(opp);
                }
            } 
        } 
    } 
} 
}
//Update the list of opportnities
update updatelst;
}

 

 

 

Test Class

public class testUpdateOpptyLeadBusCon {
    static testMethod void testUpdateOpptyLeadBusCon() {

//Create test profile 
Profile p = [select id from profile where name='System Administrator'];

//Create Users 
    User User1 = new User(alias = 'u1', email='u1@testorg.com',
      emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      timezonesidkey='America/Los_Angeles', username='u1@testorg.com');
    insert User1;

    User User2 = new User(alias = 'u2', email='u2@testorg.com',
      emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      timezonesidkey='America/Los_Angeles', username='u2@testorg.com');
    insert User2;

//Create Q-Scan Opportunity 
    Opportunity op = new Opportunity (owner=User1, name='Q-Scan Opportunity', Type='Q-Scan', stageName='Targeted Accounts', closeDate=system.today(), LeadSource='Vision');
    insert op;

//Test isInsert portion of code
//Create Business_Consultant__c 'BC1' (lead = false)
    Business_Consultant__c BC1 = new Business_Consultant__c(Consultant__c = User1.id, Opportunity__c = op.id, Lead_Consultant__c = FALSE); 
    insert BC1; 

//Create Business_Consultant__c 'BC2' (lead = true)
    Business_Consultant__c BC2 = new Business_Consultant__c(Consultant__c = User2.id, Opportunity__c = op.id, Lead_Consultant__c = TRUE); 
    insert BC2; 

    //Test that opportunity.Lead_bus_Consultant__c = User2
        //THIS FAILS
System.assertEquals(User2.id , op.Lead_Bus_Consultant__c); //Test isUpdate portion of code //Uncheck the lead designation on BC2 BC2.Lead_Consultant__c = False; update BC2; //Test that lead business consultant = null system.assertEquals(op.Lead_Bus_Consultant__c, null); //Set Lead_Bus_Consultant=TRUE on BC1 BC1.Lead_Consultant__c = True; update BC1; //Test that lead business consultant = User1 //THIS FAILS
system.assertEquals(op.Lead_Bus_Consultant__c, User1.id); //Delete BC1 delete BC1; //Test that lead business consultant = null system.assertEquals(op.Lead_Bus_Consultant__c, null); } }

 

 

We have created a custom many-to-many connection record between the standard Opportunity object the User object called 'business_consultant__c'. There is a checkbox on the connection record that shows records if it is the 'lead' consultant or not. 

 

I am trying to write a trigger on create / save of 'business_consultant__c' that will check to see if the record is a lead consultant, and if so, update another lookup on the opportunity to the users called "Lead_Bus_Consultant__c". 

 

The requirement here is to have the lead business consultant listed on the actual opportunity record. 

 

I am trying to piece this together... 

//Get Ids of lead = true business_consultant__c records that were updated for bulk (just grab the first 1 if there are multiple)

Set<Id> opportunityIds - new Set<Id>();
for (Business_Consultant__c busCon : trigger.new){
   opportunityIds.add(busCon.Opportunity__c);
}

//Check to see if it is the lead
if(busCon.Lead_Consultant__c == TRUE){

//Get Ids of related Opportunities 
List<opportunity> relatedOpportunities = 
[SELECT Opportunity__c FROM Business_Consultant__c WHERE Id in: opportunityIds];

//Set the 'Lead_Bus_Consultant__c' on the Opportunity to the consultant__c field on the connection record. 
for(Opportunity opp : relatedOpportunities){
opp.Lead_Bus_Consultant__c = busCon.Consultant__c;
}else{ //NOTHING
}

 

Is there an easier way of accomplishing this? The field on the Opportunity does not have to be a lookup, it could be a text field with just a name, although user would provide additional functionality. 

 

Any help is greatly appreciated!!

Hi, 

 

I have been trying to improve the load times of our account records and am finding that one of our inline visual force pages is taking some time to load. Is is possible to load the standard detail page and the vf page independently from eachother? 

 

I know part of the issue is the controller extention that runs to gather some additional information, but any pointers in the right direction would be greatly appreciated! 

 

Controller Extension: 

public class AccountExt {

    private final Account acc;
    
    public AccountExt(ApexPages.StandardController stdController) {
        this.acc = (account)stdController.getRecord();
    }
    
    public integer getOpenTasks() {
        return [SELECT count() FROM task WHERE whatid = :acc.id and IsClosed=false];
    }  
    
    public decimal getParFunnel() { 
    	if(acc.Rep_Site_18_Accnt_ID__c == null){
    		AggregateResult at = [SELECT Sum(Lic_Revenue__c)t FROM opportunity WHERE Account.Ultimate_Parent_ID__c = :acc.Ultimate_Parent_ID__c and IsClosed = false and Lic_Revenue__c > 0];
        	if ( at.get('t') == null) {return 0;} else {return (decimal)at.get('t');}
        }else{
        	AggregateResult at = [SELECT Sum(Lic_Revenue__c)t FROM opportunity WHERE Account.Rep_Site_18_Accnt_ID__c = :acc.Rep_Site_18_Accnt_ID__c and IsClosed = false and Lic_Revenue__c > 0];
        	if ( at.get('t') == null) {return 0;} else {return (decimal)at.get('t');}
        }
    }
    
    public decimal getParUsers() {
        AggregateResult au = [SELECT Sum(Std_User_Count__c)u FROM account WHERE Rep_Site_18_Accnt_ID__c = :acc.Rep_Site_18_Accnt_ID__c and Rep_Site_18_Accnt_ID__c != null  and Status__c = 'Active' and Std_User_Count__c > 0];
        if ( au.get('u') == null) {return 0;} else {return (decimal)au.get('u');}
    }
}

 

I keep getting a null object error on this part of my controller but can't figure out why... 

 

I am trying to determine the age of the opportunity as CloseDate - CreateDate for closed opportunities and Today - Created Date for open opportunities. I can't quite figure out how any of these could be null... and in anycase I tried to account for that in the code but is still haunting me... 

 

 public integer getAge() {
    	date close;
    		if( opp.CloseDate == null) {close = system.today();} else {close = opp.CloseDate;}
    	integer openAge = date.valueof(opp.CreatedDate).daysbetween(opp.CloseDate);
    	integer closeAge = date.valueof(opp.CreatedDate).daysBetween(system.today());
        if(opp.isClosed == true && closeAge != null && openAge != null) { return closeAge; } else {return openAge;} 
    }   

Any pointers are greatly appreciated!

 

Pretty new to this and hoping somebody can help... 

 

I want to have a controller do some calculations for me. 

 

for example, I want to return a weighting %  based on age of the opportunity. 

 

I have defined the age as such: 

 public integer getAge() {
        if(opp.isClosed == false) 
return Date.valueof(opp.CreatedDate).daysBetween(date.today());
return Date.valueof(opp.CreatedDate).daysbetween(opp.CloseDate); }

 

However, I now want to build a decimal based on that, but cant seem to be able to access the Age value that I just created even thought it is public. 

 

decimal weight = if(age<10)
{.10;}else{.30;}

 Does not work as it appears I cant use an if statment to define a variable. I get the error Expression cannot be a statement. 

 

What is the proper way to do this? 

 

I am working on a trigger that will sum some of the values from the opportunityLineItems and update a field on the opportunity. These are custom fields that do not automatically sum and our org has already used 100% of available roll-up summary fields and there are existing integration pieces that rely on these fields. 

 

Currently they are updated via s-control that has to be manually envoked from a link on each record. 

 

I have some experience with Apex Trigger, but am hoping somebody may be able to help me get started... 

 

So far I have:

trigger Calculate_Products on OpportunityLineItem (after delete, after insert, after undelete, 
after update) {

	//Set the OpportunityID
	Set<id> Ids = new Set<id>();
     for (OpportunityLineItem oli : Trigger.new) {
         Ids.add(oli.OpportunityId);
        }
        
	//Query the OpportunityLineItems
	List<aggregateResult> results = [select sum(margin__c)m from opportunityLineItem where OpportunityId in :Ids];
   
    for (OpportunityLineItem oli : Trigger.new) 
    {     
   	Opportunity Opp = opptys.get(oli.OpportunityId);
    Opp.Margin_Total__c = results.get('m');
    }    
     
	update opp;
} 

 

 but I am not quite sure how to I can sum the margin__c field and update the opportunity total_margin__c field... or how to ensure the trigger is bulk friendly. 

 

Thanks in advance for any help! 

 

 

Is it possible to show the chatter feedItems for multiple entities? 

 

We post relevant news stories to chatter on the account record, but would like the ability to show all Chatter posting for that greater account hierarchy... 

 

I have a controller extension to get the chatter postings:

public integer getChatter() {
       List<Account> Accounts = [SELECT ID from Account WHERE Rep_Site_ID__c = :acc.Rep_Site_ID__c];
       List<ID> Chatters = new List<ID>();{
           for( FeedItem FI : [SELECT ID,Body FROM feedItem WHERE parentID IN :Accounts and (type='TextPost' or type='linkpost')]) {
               if( FI.body.toUpperCase().contains('#CRTNEWS')) {
                   Chatters.add(FI.id);
                   }}}
       if( acc.NA_Code_EU__c == null ) 
           {return [SELECT count() from AccountFeed WHERE ParentID = :acc.ID];}
           else
           if( Accounts == null && Chatters == null) 
              {return 0;} 
              else 
              {return [SELECT count() FROM AccountFeed WHERE ParentID  IN :Accounts and ID IN :Chatters];}
        
    }

 This just returns the # of postings, but I am not quite sure how I would display this in VF. 

 

the <chatter:feed> tag can only show a single entity... any ideas? 

 

I am working on a controller extention to create some values for a visualforce page but and running into an issue when trying to count the number of chatter posts for a given account hierarchy that have a certain tag. 

 

I can get it to return the total feeditems for an account using an SOQL query, but run into an issue when I try to pull in the feeds for multiple accounts using 'WHERE ParentID IN :ListOfAccounts'. 

 

Can anybody see if I am missing something?

List<FeedItem> Chatters = new List<FeedItem>();{
    for(FeedItem FI : [SELECT ID,body from FeedItem]) {
        if(FI.Body.contains('#CRTNEWS')) {
          Chatters.add(FI);
        }}}
        
    List<account> accts = [SELECT Id FROM Account WHERE NA_Code_EU__c = :acc.NA_Code_EU__c]; 
    
    public integer getChatter() {
        return [SELECT count() FROM AccountFeed WHERE ParentID IN :accts AND ID IN:Chatters];
    } 

 

 

I am a bit new to writing visualforce classes so any help is greatly appreciated... 

 

I have written a visualforce page and controller extention that are working in my sandbox, but now I have to create the test class. 

 

Controller Extension which pretty much just creates some values for me:  

public class OpportunityExt {

    private final Opportunity opp;
    
    public OpportunityExt(ApexPages.StandardController stdController) {
        this.opp = (opportunity)stdController.getRecord();
    }
    

    public integer getOpenTasks() {
        return [SELECT count() FROM task WHERE whatid = :opp.id and IsClosed=false];
    } 

   
    public decimal getFunnel() {
        AggregateResult ar = [SELECT Sum(Lic_Revenue__c)s FROM opportunity WHERE ownerid = :opp.ownerid and Close_FQ__c = :opp.Close_FQ__c];
        decimal d1, dec;  
        if (ar.get('s') != null){
            dec = opp.Lic_Revenue__c / (decimal)ar.get('s') * 100;
            }
            else {
            dec = 0.00;}
            
        return d1.round();
    }
    
    public decimal getProposalScore() {
        AggregateResult ar2 = [SELECT AVG(total_score__c)a FROM Proposal__c WHERE Opportunity__c = :opp.id];
        decimal p1 = (decimal)ar2.get('a');
        return p1;
    }
     
     
    public string getShortID() {
        string longid = opp.id;
        return longid.substring(0,15);
        }
}

 

 
Visualforce Page which displays them: 

 

<apex:page showHeader="false"  standardStylesheets="true" sidebar="true" standardController="Opportunity" extensions="OpportunityExt">

<table align='center'  width="90%">
    <tr>

    <td align="center" style='border-right:1px solid black;'>
        <span  style="font-size: 20pt" align='center'>
            <apex:outputText value="{!CASE(opportunity.StageName,"Targeted Accounts","Target","Marketing Qualified", "Qualifed", "Auditor Communicating UCA Results","UCA","Channel Communicating UCA Results","UCA","Sales Rep Communicating UCA Results","UCA","1 - Determine interest in QAD","1","2 - Go/No Go Checkpoint","2","3 - Identify Sponsor/Create Vision Stmt","3","4 - Detailed Discovery","4","5 - Solution Confirmation","5","6 - Create Proposal","6","7 - On Hold","7","8 - Notification of Verbal Selection","8","Win","Win!","Loss","Loss","Invoiced Win","Win!","Qualified Out","QO","Lead Qualified Out","QO","Error")}" id="stage" />
        </span>
        <br/>
        Stage
    </td>
  
    <td align='center' style='border-right:1px solid black;'>
        <span  style="font-size: 20pt" align='center'>
            <apex:outputField value="{!opportunity.Lic_Revenue__c}"/>
        </span>
        <br/>
        <apex:outputText >License</apex:outputText>
    </td>
    
    <td align='center' style='border-right:1px solid black;'>
        <span  style="font-size: 20pt">
            <apex:outputField value="{!opportunity.Age_Custom__c}"/>
        </span>
        <br/>
        <apex:outputText >Days Open</apex:outputText>
    </td>
    
    <td align='center' style='border-right:1px solid black;'>

 

For the test class I have this so far, but I'm not sure I am moving in the right direction: 

public class testMyPage {
static testMethod void OpportunityExt()
{
//Test converage for the myPage visualforce page
PageReference pageRef = Page.OpportunityQuickView;
Test.setCurrentPageReference(pageRef);

//Create Account
Account ac = new Account (name='XYZ Organization');
insert ac;


//Create Opportunity
Opportunity op = new Opportunity (name='test opportunity');
op.Account = ac;
op.Type = 'New Users';
op.Lic_Revenue__c = 5; 
op.StageName = 'Win'; 
op.Push_Count_FQ__c = 2; 
op.CloseDate = system.today();
insert op;


ApexPages.StandardController sc = new ApexPages.standardController(op);
// create an instance of the controller
OpportunityExt myPageOpp = new OpportunityExt(sc);

//try calling methods/properties of the controller in all possible scenarios
// to get the best coverage.
integer OpenTasks = myPageOpp.GetOpenTasks();
decimal Funnel = myPageOpp.GetFunnel();
decimal ProposalScore = myPageOpp.GetProposalScore();
string ShortID = myPageOpp.GetShortID();
}
} 

Currently, when I run the test I get a 'System.QueryException: List has no rows for assignment to SObject' error and 18% coverage in my controller. 

 

Is there a better way I can test this? I have never written a visualforce controller test class before... 

 

Thanks!

I am trying to create a visualforce page that will show what % of a sales reps total funnel is represented by a given opportunity. 

 

I have been working on the controller for this, but keep getting an error: 

Error: Compile Error: Return value must be of type: Decimal at line 14 column 9

 

public class OpportunityExt {

    private final Opportunity opp;
    
    public OpportunityExt(ApexPages.StandardController stdController) {
        this.opp = (Opportunity)stdController.getRecord();
    }

    public integer getOpenTasks() {
        return [SELECT count() FROM task WHERE whatid = :opp.id and IsClosed=false];
    } 
    
    public decimal getFunnel() {
        return [SELECT Sum(Amount) FROM opportunity WHERE ownerid = :opp.ownerid];
    }
}

 I have also tried Integer, but I was under the impression that currency fields were stored as decimal... 

 

Has anybody run into something like this before? 

I am working on a trigger that will sum some of the values from the opportunityLineItems and update a field on the opportunity. These are custom fields that do not automatically sum and our org has already used 100% of available roll-up summary fields and there are existing integration pieces that rely on these fields. 

 

Currently they are updated via s-control that has to be manually envoked from a link on each record. 

 

I have some experience with Apex Trigger, but am hoping somebody may be able to help me get started... 

 

So far I have:

trigger Calculate_Products on OpportunityLineItem (after delete, after insert, after undelete, 
after update) {

	//Set the OpportunityID
	Set<id> Ids = new Set<id>();
     for (OpportunityLineItem oli : Trigger.new) {
         Ids.add(oli.OpportunityId);
        }
        
	//Query the OpportunityLineItems
	List<aggregateResult> results = [select sum(margin__c)m from opportunityLineItem where OpportunityId in :Ids];
   
    for (OpportunityLineItem oli : Trigger.new) 
    {     
   	Opportunity Opp = opptys.get(oli.OpportunityId);
    Opp.Margin_Total__c = results.get('m');
    }    
     
	update opp;
} 

 

 but I am not quite sure how to I can sum the margin__c field and update the opportunity total_margin__c field... or how to ensure the trigger is bulk friendly. 

 

Thanks in advance for any help! 

 

 

Hello, 

 

I have a custom object that is a child to the opportunity object. There is a trigger on that custom object that updates a field on the opportunity if a checkbox is marked as true. 

 

The trigger appears to be working when I do manual testing, but the test class system.asserts are failing. 

 

I can't figure out why the trigger is not functioning properly in the testClass, but works correctly in the UI. 

 

Any help would be greatly appreciated!!! 

 

Trigger

trigger UpdateOpptyLeadBusCon on Business_Consultant__c (before update, before insert, before delete) {

//Get the Business Consultant & Opportunity records
set<id> opportunitiesid = new set<id>();

//Set trigger.new or trigger.old depending on if isUpdate / isInsert / isDelete
if(trigger.isUpdate || trigger.isInsert){
    for(Business_Consultant__c buscon: Trigger.New) {
        opportunitiesid.add(buscon.Opportunity__c);
        }
    }else{
    for(Business_Consultant__c buscon: Trigger.Old) {
        opportunitiesid.add(buscon.Opportunity__c);
        }
}

//Create the lists of opportunities        
    List<Opportunity> updatelst = new List<Opportunity>();
    List<Opportunity> lstopp =[select id, Lead_bus_consultant__c from Opportunity where id IN:opportunitiesid];

 
//If isInsert && lead_consultant__c = True, then set the opportunity lead_bus_consultant__c
if(trigger.isInsert){
    for(Business_Consultant__c buscon:Trigger.New) {
        if(buscon.Lead_Consultant__c == TRUE) {
            for(Opportunity opp:lstopp) {
                 if(opp.id == buscon.opportunity__c) {
                     opp.Lead_bus_consultant__c = buscon.consultant__c;
                      updatelst.add(opp);
                 }
            }
        }
    }
}

//If isUpdate check to see if it is changed
if(trigger.isUpdate){
    
    for(Business_Consultant__c buscon:Trigger.New){
    Business_Consultant__c oldBusCon = Trigger.oldMap.get(buscon.Id);
    //If the checkbox has changed position and is no longer true, clear out the opportunity.lead_bus_consultant__c field
    if(Trigger.isUpdate && buscon.Lead_Consultant__c != oldBusCon.Lead_Consultant__c  && buscon.Lead_Consultant__c != TRUE){
        for(Opportunity opp:lstopp){
            if(opp.id == buscon.opportunity__c){
                opp.Lead_bus_consultant__c = null;
                    updatelst.add(opp);
            }
        } 
    }else{
    //Otherwise if the checkbox is checked, set the opportunity.lead_bus_consultant__c field as the consultant from the connector
    if(buscon.Lead_Consultant__c == TRUE) {
 
        for(Opportunity opp:lstopp) {
                 if(opp.id == buscon.opportunity__c) {
 
                     opp.Lead_bus_consultant__c = buscon.consultant__c;
                      updatelst.add(opp);
                }
        }
    }
    }
    }
} 
//If isDelete set the opportunity.lead_bus_consultant__c to null 
else {
if(trigger.isDelete){

    for(Business_Consultant__c buscon:Trigger.Old){
        Business_Consultant__c oldBusCon = Trigger.oldMap.get(buscon.Id);
        if(Trigger.isDelete && buscon.Lead_Consultant__c == TRUE){
            for(Opportunity opp:lstopp){
                if(opp.id == buscon.opportunity__c){
                    opp.Lead_bus_consultant__c = null;
                        updatelst.add(opp);
                }
            } 
        } 
    } 
} 
}
//Update the list of opportnities
update updatelst;
}

 

 

 

Test Class

public class testUpdateOpptyLeadBusCon {
    static testMethod void testUpdateOpptyLeadBusCon() {

//Create test profile 
Profile p = [select id from profile where name='System Administrator'];

//Create Users 
    User User1 = new User(alias = 'u1', email='u1@testorg.com',
      emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      timezonesidkey='America/Los_Angeles', username='u1@testorg.com');
    insert User1;

    User User2 = new User(alias = 'u2', email='u2@testorg.com',
      emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      timezonesidkey='America/Los_Angeles', username='u2@testorg.com');
    insert User2;

//Create Q-Scan Opportunity 
    Opportunity op = new Opportunity (owner=User1, name='Q-Scan Opportunity', Type='Q-Scan', stageName='Targeted Accounts', closeDate=system.today(), LeadSource='Vision');
    insert op;

//Test isInsert portion of code
//Create Business_Consultant__c 'BC1' (lead = false)
    Business_Consultant__c BC1 = new Business_Consultant__c(Consultant__c = User1.id, Opportunity__c = op.id, Lead_Consultant__c = FALSE); 
    insert BC1; 

//Create Business_Consultant__c 'BC2' (lead = true)
    Business_Consultant__c BC2 = new Business_Consultant__c(Consultant__c = User2.id, Opportunity__c = op.id, Lead_Consultant__c = TRUE); 
    insert BC2; 

    //Test that opportunity.Lead_bus_Consultant__c = User2
        //THIS FAILS
System.assertEquals(User2.id , op.Lead_Bus_Consultant__c); //Test isUpdate portion of code //Uncheck the lead designation on BC2 BC2.Lead_Consultant__c = False; update BC2; //Test that lead business consultant = null system.assertEquals(op.Lead_Bus_Consultant__c, null); //Set Lead_Bus_Consultant=TRUE on BC1 BC1.Lead_Consultant__c = True; update BC1; //Test that lead business consultant = User1 //THIS FAILS
system.assertEquals(op.Lead_Bus_Consultant__c, User1.id); //Delete BC1 delete BC1; //Test that lead business consultant = null system.assertEquals(op.Lead_Bus_Consultant__c, null); } }

 

 

We have created a custom many-to-many connection record between the standard Opportunity object the User object called 'business_consultant__c'. There is a checkbox on the connection record that shows records if it is the 'lead' consultant or not. 

 

I am trying to write a trigger on create / save of 'business_consultant__c' that will check to see if the record is a lead consultant, and if so, update another lookup on the opportunity to the users called "Lead_Bus_Consultant__c". 

 

The requirement here is to have the lead business consultant listed on the actual opportunity record. 

 

I am trying to piece this together... 

//Get Ids of lead = true business_consultant__c records that were updated for bulk (just grab the first 1 if there are multiple)

Set<Id> opportunityIds - new Set<Id>();
for (Business_Consultant__c busCon : trigger.new){
   opportunityIds.add(busCon.Opportunity__c);
}

//Check to see if it is the lead
if(busCon.Lead_Consultant__c == TRUE){

//Get Ids of related Opportunities 
List<opportunity> relatedOpportunities = 
[SELECT Opportunity__c FROM Business_Consultant__c WHERE Id in: opportunityIds];

//Set the 'Lead_Bus_Consultant__c' on the Opportunity to the consultant__c field on the connection record. 
for(Opportunity opp : relatedOpportunities){
opp.Lead_Bus_Consultant__c = busCon.Consultant__c;
}else{ //NOTHING
}

 

Is there an easier way of accomplishing this? The field on the Opportunity does not have to be a lookup, it could be a text field with just a name, although user would provide additional functionality. 

 

Any help is greatly appreciated!!

I keep getting a null object error on this part of my controller but can't figure out why... 

 

I am trying to determine the age of the opportunity as CloseDate - CreateDate for closed opportunities and Today - Created Date for open opportunities. I can't quite figure out how any of these could be null... and in anycase I tried to account for that in the code but is still haunting me... 

 

 public integer getAge() {
    	date close;
    		if( opp.CloseDate == null) {close = system.today();} else {close = opp.CloseDate;}
    	integer openAge = date.valueof(opp.CreatedDate).daysbetween(opp.CloseDate);
    	integer closeAge = date.valueof(opp.CreatedDate).daysBetween(system.today());
        if(opp.isClosed == true && closeAge != null && openAge != null) { return closeAge; } else {return openAge;} 
    }   

Any pointers are greatly appreciated!

 

Pretty new to this and hoping somebody can help... 

 

I want to have a controller do some calculations for me. 

 

for example, I want to return a weighting %  based on age of the opportunity. 

 

I have defined the age as such: 

 public integer getAge() {
        if(opp.isClosed == false) 
return Date.valueof(opp.CreatedDate).daysBetween(date.today());
return Date.valueof(opp.CreatedDate).daysbetween(opp.CloseDate); }

 

However, I now want to build a decimal based on that, but cant seem to be able to access the Age value that I just created even thought it is public. 

 

decimal weight = if(age<10)
{.10;}else{.30;}

 Does not work as it appears I cant use an if statment to define a variable. I get the error Expression cannot be a statement. 

 

What is the proper way to do this? 

 

I am working on a controller extention to create some values for a visualforce page but and running into an issue when trying to count the number of chatter posts for a given account hierarchy that have a certain tag. 

 

I can get it to return the total feeditems for an account using an SOQL query, but run into an issue when I try to pull in the feeds for multiple accounts using 'WHERE ParentID IN :ListOfAccounts'. 

 

Can anybody see if I am missing something?

List<FeedItem> Chatters = new List<FeedItem>();{
    for(FeedItem FI : [SELECT ID,body from FeedItem]) {
        if(FI.Body.contains('#CRTNEWS')) {
          Chatters.add(FI);
        }}}
        
    List<account> accts = [SELECT Id FROM Account WHERE NA_Code_EU__c = :acc.NA_Code_EU__c]; 
    
    public integer getChatter() {
        return [SELECT count() FROM AccountFeed WHERE ParentID IN :accts AND ID IN:Chatters];
    } 

 

 

I am a bit new to writing visualforce classes so any help is greatly appreciated... 

 

I have written a visualforce page and controller extention that are working in my sandbox, but now I have to create the test class. 

 

Controller Extension which pretty much just creates some values for me:  

public class OpportunityExt {

    private final Opportunity opp;
    
    public OpportunityExt(ApexPages.StandardController stdController) {
        this.opp = (opportunity)stdController.getRecord();
    }
    

    public integer getOpenTasks() {
        return [SELECT count() FROM task WHERE whatid = :opp.id and IsClosed=false];
    } 

   
    public decimal getFunnel() {
        AggregateResult ar = [SELECT Sum(Lic_Revenue__c)s FROM opportunity WHERE ownerid = :opp.ownerid and Close_FQ__c = :opp.Close_FQ__c];
        decimal d1, dec;  
        if (ar.get('s') != null){
            dec = opp.Lic_Revenue__c / (decimal)ar.get('s') * 100;
            }
            else {
            dec = 0.00;}
            
        return d1.round();
    }
    
    public decimal getProposalScore() {
        AggregateResult ar2 = [SELECT AVG(total_score__c)a FROM Proposal__c WHERE Opportunity__c = :opp.id];
        decimal p1 = (decimal)ar2.get('a');
        return p1;
    }
     
     
    public string getShortID() {
        string longid = opp.id;
        return longid.substring(0,15);
        }
}

 

 
Visualforce Page which displays them: 

 

<apex:page showHeader="false"  standardStylesheets="true" sidebar="true" standardController="Opportunity" extensions="OpportunityExt">

<table align='center'  width="90%">
    <tr>

    <td align="center" style='border-right:1px solid black;'>
        <span  style="font-size: 20pt" align='center'>
            <apex:outputText value="{!CASE(opportunity.StageName,"Targeted Accounts","Target","Marketing Qualified", "Qualifed", "Auditor Communicating UCA Results","UCA","Channel Communicating UCA Results","UCA","Sales Rep Communicating UCA Results","UCA","1 - Determine interest in QAD","1","2 - Go/No Go Checkpoint","2","3 - Identify Sponsor/Create Vision Stmt","3","4 - Detailed Discovery","4","5 - Solution Confirmation","5","6 - Create Proposal","6","7 - On Hold","7","8 - Notification of Verbal Selection","8","Win","Win!","Loss","Loss","Invoiced Win","Win!","Qualified Out","QO","Lead Qualified Out","QO","Error")}" id="stage" />
        </span>
        <br/>
        Stage
    </td>
  
    <td align='center' style='border-right:1px solid black;'>
        <span  style="font-size: 20pt" align='center'>
            <apex:outputField value="{!opportunity.Lic_Revenue__c}"/>
        </span>
        <br/>
        <apex:outputText >License</apex:outputText>
    </td>
    
    <td align='center' style='border-right:1px solid black;'>
        <span  style="font-size: 20pt">
            <apex:outputField value="{!opportunity.Age_Custom__c}"/>
        </span>
        <br/>
        <apex:outputText >Days Open</apex:outputText>
    </td>
    
    <td align='center' style='border-right:1px solid black;'>

 

For the test class I have this so far, but I'm not sure I am moving in the right direction: 

public class testMyPage {
static testMethod void OpportunityExt()
{
//Test converage for the myPage visualforce page
PageReference pageRef = Page.OpportunityQuickView;
Test.setCurrentPageReference(pageRef);

//Create Account
Account ac = new Account (name='XYZ Organization');
insert ac;


//Create Opportunity
Opportunity op = new Opportunity (name='test opportunity');
op.Account = ac;
op.Type = 'New Users';
op.Lic_Revenue__c = 5; 
op.StageName = 'Win'; 
op.Push_Count_FQ__c = 2; 
op.CloseDate = system.today();
insert op;


ApexPages.StandardController sc = new ApexPages.standardController(op);
// create an instance of the controller
OpportunityExt myPageOpp = new OpportunityExt(sc);

//try calling methods/properties of the controller in all possible scenarios
// to get the best coverage.
integer OpenTasks = myPageOpp.GetOpenTasks();
decimal Funnel = myPageOpp.GetFunnel();
decimal ProposalScore = myPageOpp.GetProposalScore();
string ShortID = myPageOpp.GetShortID();
}
} 

Currently, when I run the test I get a 'System.QueryException: List has no rows for assignment to SObject' error and 18% coverage in my controller. 

 

Is there a better way I can test this? I have never written a visualforce controller test class before... 

 

Thanks!

I am trying to create a visualforce page that will show what % of a sales reps total funnel is represented by a given opportunity. 

 

I have been working on the controller for this, but keep getting an error: 

Error: Compile Error: Return value must be of type: Decimal at line 14 column 9

 

public class OpportunityExt {

    private final Opportunity opp;
    
    public OpportunityExt(ApexPages.StandardController stdController) {
        this.opp = (Opportunity)stdController.getRecord();
    }

    public integer getOpenTasks() {
        return [SELECT count() FROM task WHERE whatid = :opp.id and IsClosed=false];
    } 
    
    public decimal getFunnel() {
        return [SELECT Sum(Amount) FROM opportunity WHERE ownerid = :opp.ownerid];
    }
}

 I have also tried Integer, but I was under the impression that currency fields were stored as decimal... 

 

Has anybody run into something like this before?