• jhenning
  • SMARTIE
  • 579 Points
  • Member since 2009

  • Chatter
    Feed
  • 22
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 98
    Replies

i am having trouble finding examples to test something like this...

 

	 	if ( searchStr.length() < 2 ) {
	 		ApexPages.addMessage( new ApexPages.Message(
	 			ApexPages.Severity.INFO, 'Search requires more characters'));
	 		return null;
	 	}

 

thank you.

Hi all,

 

I am writing an after insert trigger on an object called EBD__c.

 

The idea of the trigger is as follows: There is an EBD for each month/location combo.  EBDs are loaded via data loader one month at a time.  The users may not load 1 EBD for every month for every location, they load as many as needed and for every location an EBD is not entered for that month, a new one is created.  So lets say the user is going to load 20 EBDs and there are 125 locations.  We would be updating 20 EBDs and inserting 105 new EBDS.  Unfortunately you cant insert more than 100 things via trigger.  So I start chunking up my list that is greater than size 100 into blocks of 100 and calling future methods to upsert these blocks, and this is where things get ugly.  Future methods only take primitives.  Creating a static instance variable with the list I want the future method to upsert doesnt work either, the data seems to go poof when it goes out of scope.  My only idea is to create a list of strings that contain all the data I need to pass to the future method, but that seems arduous, and stupid.

 

Any ideas?

Thanks

  • August 10, 2010
  • Like
  • 0

Hi all,

 

 I have a bit of a problem that probably shouldn't be a problem...I'm trying to do something that should be alot easier than it has been so far:

 

 I have a field being populated by a formula and the field is either a 1 or a 0 depending on the outcome of the formula. All I want is for a picklist to change value when the field's value changes.

 

Here is my trigger:

 

trigger CompanyGoalUpdate on Company_Goal__c (after insert, after update) {
	Company_Goal__c cmp = [SELECT Upcoming_Goal__c, Use_on_Company__c, LastModifiedDate FROM Company_Goal__c WHERE Id =: trigger.new[0].Id];
	
	if(cmp.Upcoming_Goal__c == 1)
		cmp.Use_on_Company__c = 'Use';
	else
		cmp.Use_on_Company__c = 'Do Not Use';
	
	DateTime RightNow = System.now();
	
	if(cmp.LastModifiedDate < RightNow.addMinutes(-30))
		update cmp;
}

 

Any thoughts?

 

Hello,

 

I am relatively new to Apex and Visualforce and need some guidance.

 

I have 2 objects: Billing Account and Line Items. For every Account, there can be multiple Billing Accounts each of which can have multiple Line Items. I want to return a List from a function that will give me all the Line Items of all Billing Accounts in one single list. This code compiles but on running the code, it gives me an error

 

System.NullPointerException: Attempt to de-reference a null object at line

totallines.addAll(lines);
Please help my cause by suggesting what may be causing this problem. Thanks !!

 

Here is my apex class snippet: 

 

List<Line_Items__c> l, lines, totallines;
List<Billing_Account__c> billacc;   
public List<Line_Items__c> getLineItems()
    {
        if(invoice.Billing_Account__c != null) 
        {
            l = [select id, name, Plan__c, Rate__c, Quantity__c, Total_Value__c, Activation_Date__c, Plan_Name__c, Street__c,
Unit__c, City__c from Line_Items__c where Service_Account__c =: invoice.Billing_Account__c and Status__c =: 'Active'];
           
return l;
                       
        }
        else
        { 
            billacc = [select id, Bill_Street__c, Bill_Unit_Number__c, Bill_City__c, Bill_State__c, Bill_Postal_Code__c from Billing_Account__c 
                                    where Account__c =: invoice.Account__c];
            
            integer z = 0;  
            if(billacc.size() > 0)
            {                      
                for(integer k =0; k < billacc.size(); k++)
                {
                   lines = [select id, name, Plan__c, Rate__c, Quantity__c, Total_Value__c, Activation_Date__c, Plan_Name__c,
Street__c, Unit__c, City__c from Line_Items__c where Service_Account__c =: billacc[k].id and Status__c =: 'Active'];

                   for( integer h = 0; h < lines.size(); h++)
                   {
                       totallines.addAll(lines);
                       z++;
                   }

                }
                 
                 return totallines;
             }
             
             return null;
             
         } 
                                      
    }

I am learning to code APEX as I go and piecing together how to test and deploy as well. Through trial and error I was able to write a trigger that chooses the pricebook of an opportunity based upon what is selected in the drop down Lead Source:

 

trigger setPriceBook on Opportunity (before insert) {    
    ID PRICEBOOK_YOUCAN = '01s300000002kelAAA';    
    ID PRICEBOOK_QBPP = '01s300000002kZ2AAI';    
    ID PRICEBOOK_B2B = '01s300000002kZCAAY';    
    ID PRICEBOOK_DATAREF = '01s300000002kZ7AAI'; 
    ID PRICEBOOK_STANDARD = '01s300000006i5xAAA' ; 
    ID PRICEBOOK_WINBACK = '01s300000002kegAAA'  ;  
    String SOURCE_YOUCAN = 'YouCan';        
    String SOURCE_QBPP = 'QBPP';    
    String SOURCE_B2B = 'B2B';    
    String SOURCE_DATAREF = 'Data Referral';   
    String SOURCE_WINBACK = 'WinBack' ; 
    for( Opportunity oppty : trigger.new ) {                
        if ( oppty.LeadSource == SOURCE_YOUCAN ) {            
            oppty.Pricebook2Id = PRICEBOOK_YOUCAN;        
        }        
        else if ( oppty.LeadSource == SOURCE_QBPP ) {                       
            oppty.Pricebook2Id = PRICEBOOK_QBPP;        
        }        
        else if ( oppty.LeadSource == SOURCE_B2B ) {            
            oppty.Pricebook2ID = PRICEBOOK_B2B;        
        }        
        else if (oppty.LeadSource == SOURCE_DATAREF ) {            
            oppty.Pricebook2ID = PRICEBOOK_DATAREF;        
        } 
        else if (oppty.LeadSource == SOURCE_WINBACK ) {
            oppty.PriceBook2ID = PRICEBOOK_WINBACK;
        }
        else {
            oppty.Pricebook2ID = PRICEBOOK_STANDARD;
        }      
    }
}

 

Probably not the cleanest code ever...but it worked.

 

My problem is when I wrote my test class, which is even dirtier. It initially compiled and tested clean with 80% coverage. I thought I was ready to go until I realised that I had left out a variable in the trigger. When that got saved it took me to under 75% so I had to add more test cases in. I have no idea how I got so messed up, but as a result of all my trial and error, I can't even figure out what originally worked:

 

@isTEST
private class setPriceBookTest {
    static testMethod void testsetPriceBookYouCan () {
    //Create new YouCan Opportunity 
    Opportunity oppYouCan = new Opportunity ();
    oppYouCan.Description = 'TestYouCan';
    oppYouCan.LeadSource = 'YouCan';
    oppYouCan.StageName = 'New';
    oppYouCan.Name = 'YouCanTest2';
    oppYouCan.CloseDate = System.Today();
    insert oppYouCan;
    //Select the pricebook 
    Opportunity YouCanPriceBook = [SELECT Pricebook2ID
                                    FROM Opportunity
                                    WHERE Name = 'YouCanTest2'
                                    LIMIT 1];
    ID PriceBookYouCan = '01sQ00000008bamIAA';
    //Verify Price book
    System.assertNotEquals(null, YouCanPriceBook);
    //Create new QBPP Opportunity
    Opportunity oppQBPP = new Opportunity () ;
    oppQBPP.Description = 'TestQBPP';
    oppQBPP.LeadSource = 'QBPP';
    oppQBPP.StageName = 'New';
    oppQBPP.Name = 'QBPPTest2';
    oppQBPP.CloseDate = System.Today() ;
    Database.insert (oppQBPP);
    //Select the pricebook
    Opportunity QBPPPriceBook = [SELECT Pricebook2ID
                                    FROM Opportunity
                                    WHERE Name = 'QBPPTest2'
                                    LIMIT 1];
    ID PriceBookQBPP = '01sQ00000008bahIAA';
    //Verify Price book
    System.assertNotEquals (null, QBPPPriceBook);
    //Create new WinBack Opportunity
    Opportunity oppWinBack = new Opportunity () ;
    oppWinBack.Description = 'TestWinBack';
    oppWinBack.LeadSource = 'WinBack';
    oppWinBack.StageName = 'New';
    oppWinBack.Name = 'WimBackTest2';
    oppWinBack.CloseDate = System.Today() ;
    Database.insert (oppWinBack);
    //Select the pricebook
    Opportunity WinBackPriceBook = [SELECT Pricebook2ID
                                    FROM Opportunity
                                    WHERE Name = 'WinBackTest2'
                                    LIMIT 1];
    //Verify Price book
    System.assertNotEquals (null, WinBackPriceBook);

    }
 }

 

The error that I currently get when I run the test is:

 

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

 

I have read quite a few pages that make it sound like this is a permissions problem, however I believe I am running this test as a System Administrator who would have access to any accounts.

 

Any help would be appreciated as I have been at this for over a week and still feel like I am going in circles.

  • August 09, 2010
  • Like
  • 0

     Im new to salesforce, and my company recently installed a new package from the appexchange called "project and issue management" the package came with some custom objects, one in particular is the "project" object, which I am trying to write a trigger for, but it seems that for some reason the object is not recognized.  the following very simple code errors out:

 

trigger ProjectAutoFill on SFDC_Project__c (before insert) {

SFDC_Project_c tempProject;

}

 

the error is:

 

Error: Compile Error: Invalid type: SFDC_Project_c at line 3 column 1

If anybody could help me understand what's going on here it would be greatly appreciated

Hi

 

I have an student application, there is a college website with a page for request information.A student enters the info in the page , submits it and then the data is sent to database.I do not have to do anything here.Now, an email is sent from an email address of the database to the admission office with the student info which he entered while ago...like first name , last name email address...etc....I need to write an email to apex...such that..if the student record is present create a task , if not present create a record and task...Here , student record is the contact record....Now, can we do this using email to apex...if yes how...??/ If no, then how can I do this..?? Any ideas, suggestions are welcome....

 

 

thank you

 

 

  • April 15, 2010
  • Like
  • 0

Hi,

 

I am trying to update a field value on standard object after there has been a change on a custom object field.

 

The standard Object is Account and custom object is  Accountsinaction(Account_in_action__c).

Both objects are related via a Lookup relationship. The field is Account__c on Custom Object.

 

Also, the custom object has another field called Account_Status__c. If there is a change to this value, a trigger has to fire and update the change in corresponding Standard Account Object.

 

Trigger Code so far:

 

trigger Update_Account_Status on Account_In_Action__c (after Update) 
{
      List<Account> accts_toUpdate=new List<Account>();
      Set<Id> accsId =new Set<Id>();
      
      for(Account_In_Action__c ia : Trigger.New)
          accsId.add(ia.Account__c);
          
      Map<Id,Account> AccountMap=new Map<Id,Account>([Select Status from Account where Id in :accsId]);
      List<Account_In_Action__c> account_Action= [select Account_Status__c from Account_In_Action__c where id in :Trigger.new];
      
      for(Integer i=0;i<account_Action.size();i++)
      {
        Account toupdate=new Account();
        accountMap.get(account_Action[i].idea__c).Status=account_Action[i].account_status__c;
        accts_toUpdate.add(toupdate);
      }
      
      if(accts_toUpdate.size()>0)
          Update accts_toUpdate;
}

 It gives following error msg:

 

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account_In_Action__c.Account__c: Trigger.Update_Account_Status:

 

Can anyone help me with this.

 

Thanks in advance !

 

sales4ce

 

Hello

I have developped a trigger on account "before insert"

If I import account through DataLoader, will this trigger be called ? If no, does "after insert" close work ?

If I import account through Bulk API, will this trigger be called ? If no, does "after insert" close work ?

Thanks for your help

Hi

 

I have a custom object. When user will click New button to create new record of custom object and then click Save button I'd like to redirect him not to Details page but to other page. Is it possible?

Is it possible to allow some records to be inserted but not others on a trigger?

 

The records are coming in via the API so i have no way to checking them before hand or overriding with vf and using the opt_allOrNone option on the database.insert method.

  • March 23, 2010
  • Like
  • 0

hi all

 

 

i have a question.

 

now i develop a calculating application by using visualforce.

 

in a page, i get two random numbers, click "add" button and then add them in a next page.

 

but i can't keep random numbers in a next page.

 

how can i keep random numbers in a next page?

 

 

now this is code.

 

「add page(visualforce)」

<apex:page Controller="MathController">
    
          {!RandomNumber1} + {!RandomNumber2} = <br/>

          <apex:form >
               <apex:commandButton value="answer" action="{!Answer}" />
          </apex:form>
                    
</apex:page>

 

「MathController」

public class MathController {

     public double getRandomNumber1() {

          double ran1 = Math.round(Math.random()*100);
         
          return ran1;
           
     }
    
     public double getRandomNumber2() {

          double ran2 = Math.round(Math.random()*100);
         
          return ran2;
           
     }
 
     public PageReference Answer() {
    
          PageReference secondPage = Page.answer;
    
          secondPage.setRedirect(true);
    
          return secondPage;
    
     }
    
     public double getAddNumber() {

 

    //this AddNumber method has not been completed.

 

          double ans = ran1 + ran2;

 

          return ans;

 

     }

}

 

 

「answer page(visualforce)」

<apex:page Controller="MathController">
    
     The answer is {!AddNumber}.<br/>
    
</apex:page>

  • October 30, 2009
  • Like
  • 0

Hi,

 

I'm having a bit of trouble unit testing the following:

 

Class:

 

public class leadConverternoOpp {

public class applicationException extends Exception {}

public Lead leadToConvert {get; private set;}

public Lead getLead() {

Id leadId = ApexPages.currentPage().getParameters().get('leadId');
leadToConvert = (leadId == null) ? new Lead() : [select id, Contact__c, Status, Account__r.Name ,Account__c,Opportunity__c, Name, LeadSource
from Lead where id = :leadId];

return leadToConvert;

}


/**
* Constructor fetches the lead
*/

public leadConverternoOpp(ApexPages.StandardController controller) {

this.leadToConvert = (Lead)controller.getRecord();

}


public PageReference cancel() {

PageReference retUrl = new PageReference ('/' + leadToConvert.Id);
return (retUrl);
}

public PageReference convertLeadNoOpp_1() {

return Page.leadConverterNoOpp;
}



public PageReference convertLeadNoOpp_2() {

Savepoint sp = Database.setSavepoint();


if (leadToConvert.Opportunity__c == null
&& leadToConvert.Status == 'Part of an Existing Opportunity') {

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,
'Please include the Opportunity below'));
return Apexpages.currentPage();
}

else if (leadToConvert.Opportunity__c != null
&& leadToConvert.Status != 'Part of an Existing Opportunity'){

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,
'"Part of an Existing Opportunity" was not chosen but an Opportunity was supplied'));
return Apexpages.currentPage();

} else {

try {

database.Leadconvert lc = new database.Leadconvert();
lc.setLeadId(leadToConvert.Id);
lc.setAccountId(leadToConvert.account__c);
lc.setContactId(leadToConvert.contact__c);
lc.setDoNotCreateOpportunity(true); // There's no opportunity to create
lc.setOverwriteLeadSource(false);
lc.setSendNotificationEmail(false);
lc.setConvertedStatus(leadToConvert.status);


database.leadConvertResult lcr = Database.convertLead(lc);
system.assert(lcr.isSuccess());
PageReference retUrl = new PageReference ('/' + lcr.getContactId());
return (retUrl);
}
catch (exception e ) {
ApexPages.addMessages(e);
system.debug(e + ' got an error on the try-catch.');
Database.rollback(sp);
return null;
}
}
}

}

 

 

 

 

 

Unit Test so far:

 

 

@isTest
private class unitTest_leadConverter {

static testMethod void leadConverter_noOpp_test() {

Account testAccount = [select Id, Name from Account limit 1];
system.debug(testAccount);

Contact testContact = new Contact(
Firstname = 'Test',
Lastname = 'Test',
Email = 'Test1@xyz.com',
AccountId = testAccount.Id);

insert testContact;

Lead insertLead = new Lead(
Firstname = 'Test',
Lastname = 'Test',
Company = 'TestCo',
Email = 'Test1@xyz.com',
Account__c = testAccount.Id,
Contact__c = testContact.Id);

insert insertLead;
system.assertNotEquals(insertLead.Account__c,null);
system.debug('insertLead.Id:' +insertLead.Id);


// call the page and add the lead Id
PageReference p2 = Page.leadConverterNoOpp;
system.debug('PageReference p2:' + p2);
Test.setCurrentPage(p2);
ApexPages.currentPage().getParameters().put('leadId', insertLead.Id);

ApexPages.Standardcontroller sc;
leadConverternoOpp controller = new leadConverternoOpp(sc);

PageReference nextPage = controller.convertLeadNoOpp_2();

system.debug('nextPage:' + nextPage);


}

}

 

The unit test creates a lead, then adds that lead to the URL so that the class can pull up the lead and then convert it.  The problem is that this line is returning a null pointer exception.

leadConverternoOpp controller = new leadConverternoOpp(sc);

 

Message:

System.NullPointerException: Attempt to de-reference a null object

 

Stack Trace:

Class.leadConverternoOpp.<init>: line 25, column 42 Class.unitTest_leadConverter.leadConverter_noOpp_test: line 93, column 37

 

 

Is this code majorly ill or just slightly ill?

 

Any kind of help is appreciated as this is giving me more gray hair!!

 

Thanks!!

 

Message Edited by Ron-LON on 09-18-2009 06:03 PM
Message Edited by Ron-LON on 09-18-2009 06:04 PM
  • September 18, 2009
  • Like
  • 0

Ok, I'm just getting started in SF, and I'm under a time crunch.  Normally for a basic problem like this I would spend the time to RTFM before asking this, but right now I just need help getting this done.

 

We have leads that are coming in two ways, entered directly into SF, and by filling out a form on our website.  I want to create an insert trigger that sends a welcome email IF the 'send_welcome_email' flag is set on the user.  Then I want to clear the flag.

 

So far, I have nothing.  The only thing I DO have is the force IDE set up so I can put triggers on my leads (I'm not working on the sandbox, but the real thing.)  I've done a blank trigger just to make sure, and it is installing.

 

Does anyone have an example of what this trigger should look like? 

Thanks!

 

Not that it matters, but my experience is in PHP. 

In trying to enforce our account naming standard, I would like to write a trigger that checks for the existance of the "Billing City" in the new account name a user is trying to create. Our account naming convention is "Accout Name - Billing City", so my trigger needs to check for the existance of a hyphen (" - ") and Billing City in the name.

 

A correct account name would be: IBM - San Francisco or HP - San Diego.

 

Can this be done with a trigger?

 

Thanks!

I created a trigger that would not let an user create a record if a record exist for that child object.

But Can I link it to a new button. So when the user clicks new, it will fire the trigger off to check if a record is created and not let the user create another record?

Thanks

MMA

Hey guys,

 

 I'm trying to understand what is going wrong with my custom controller method for about 2 hours and just now I realize that the following code is probably my problem:

 

 

act.Private__c = boolean.valueOf(Apexpages.currentPage().getParameters().get('private'));

 

 Private__c is a checkbox (boolean) field type and I was trying to parse a form field string with a 'false'/'true' value.

 

 The problem here was I didn't get any error messages in any place. I turned on the Apex Debug Log and it shows status 'Sucess' and nothing else more. To find that this line is probably my problem I had to put a System.debug() line after every single code line that I wrote!

 I mean, I can't spend 2 hours to find an error for every problem I have!! And I can't put a System.debug() line for every single code line I have. This way I'll take 100 years to finish my project... :(

 

 Another problem is this thing to have to reset my debug log every 20 time... I'm using a development org, so I'll need it every time. Is there any way to change it?

 

 At last, the debug output is soooo large and difficult to read. I saw that someone developed this tool to filter debug logs output, but it works only in Windows and I use Mac (lucky me :) ). Any tips here?

 

 Thank you in advance for any help!! 

 

 Best regards

 

 PH

 

 

 

I have this custom formula field on the task object. 

 

Formula is;

HYPERLINK("/"& WhatId, 'Detail Link')

 

Displayed as

Link: Detail Link 

 

I want to display the actual account name instead of "Detail Link" 

Is there any way to change the script to achieve this?

  • September 15, 2009
  • Like
  • 0

I'm attempting to create a Validation Rule for an Opportunity based on an Opportunity Split. Basically, we can have up to 3 reps own an Opportunity and each gets a % of the Amount. I want to create a rule that will validate that the 3 % fields = 100% and that the Calculated Value for each portion of the Split = the Amount.

 

Here are the Formulas that I created:

 

 X2nd_Rep__c + X3rd_Rep__c + Primary_Rep__c ==100

 

This throws no errors when I check the Syntax, but the rule doesn't seem to do what I want it to. I can enter in 100% for each Sales Rep % field and no error is thrown, I can also enter in values that total to less than 100 and still no error is thrown.

 

The other formula I have is to verify that the Sum of the Rep Splits = the Amount. Here is the formula:

 

Primary_Rep_Bookings_Amount__c  +  X2nd_Rep_s_Booking_Amount__c  +  X3rd_Rep_s_Booking_Amount__c  == Amount

 

Please let me know what I'm doing wrong or if there is a better way to do this.

 

 

  • September 14, 2009
  • Like
  • 0

Hi, I have a customer who is using the html script to enter requests to sales force from directly from their site.

 

They are complaining that once that you fill in the information on the site and click on submit that the screen goes blank.

 

How can I add a redirection so that after clicking on submit, it will load a thank you page? 

  • September 14, 2009
  • Like
  • 0

i am having trouble finding examples to test something like this...

 

	 	if ( searchStr.length() < 2 ) {
	 		ApexPages.addMessage( new ApexPages.Message(
	 			ApexPages.Severity.INFO, 'Search requires more characters'));
	 		return null;
	 	}

 

thank you.

I am working on a visualforce tool that displays all of the open opportunities a user is involved with.  At our company, that may mean they own the opportunity or they are the Sales Manager or Account Manager on the opportunity.  In the controller I am querying the opportunities for anything that is open that the current user is the owner of OR they are listed as the account manager or the sales manager.

 

We have sharing rules set up to share opportunities owned by someone in a district with everyone else in the district.

 

The visualforce tool is displaying all of the opportunities in a pageblocktable using inputFields to allow for quick updates to multiple opportunities at once.

 

The issue is that the query to get the opportunities may bring back opportunities that the user cannot actually edit, but because the visualforce page uses inputfields the user could try to edit the record, click save and get an error.  This happens when the opportunitiy is created by somebody outside of the users district and the owner is not changed to within the district.  (This is not something I designed and I know that this could be reimplemented in a differnent way, but that is not a battle I can fight right now).

 

I tried to alleviate this problem by querying the OpportunityShare table to determine the proper access, however, since some of the access is granted by the role hierarchy, I am unsure how to determine if a user has edit access on the opportunity.  If the users ID shows up in the UserOrGroupId Column this is easy, but if they are part of a group whose ID is in the UserOrGroupId column then I am not sure how to proceed.

 

My question boils down to: How can I determine if a user has access to a record so that I can exclude those that can't be edited from being displayed?

  • August 11, 2010
  • Like
  • 0

Hi all,

 

I am writing an after insert trigger on an object called EBD__c.

 

The idea of the trigger is as follows: There is an EBD for each month/location combo.  EBDs are loaded via data loader one month at a time.  The users may not load 1 EBD for every month for every location, they load as many as needed and for every location an EBD is not entered for that month, a new one is created.  So lets say the user is going to load 20 EBDs and there are 125 locations.  We would be updating 20 EBDs and inserting 105 new EBDS.  Unfortunately you cant insert more than 100 things via trigger.  So I start chunking up my list that is greater than size 100 into blocks of 100 and calling future methods to upsert these blocks, and this is where things get ugly.  Future methods only take primitives.  Creating a static instance variable with the list I want the future method to upsert doesnt work either, the data seems to go poof when it goes out of scope.  My only idea is to create a list of strings that contain all the data I need to pass to the future method, but that seems arduous, and stupid.

 

Any ideas?

Thanks

  • August 10, 2010
  • Like
  • 0

Hi all,

 

 I have a bit of a problem that probably shouldn't be a problem...I'm trying to do something that should be alot easier than it has been so far:

 

 I have a field being populated by a formula and the field is either a 1 or a 0 depending on the outcome of the formula. All I want is for a picklist to change value when the field's value changes.

 

Here is my trigger:

 

trigger CompanyGoalUpdate on Company_Goal__c (after insert, after update) {
	Company_Goal__c cmp = [SELECT Upcoming_Goal__c, Use_on_Company__c, LastModifiedDate FROM Company_Goal__c WHERE Id =: trigger.new[0].Id];
	
	if(cmp.Upcoming_Goal__c == 1)
		cmp.Use_on_Company__c = 'Use';
	else
		cmp.Use_on_Company__c = 'Do Not Use';
	
	DateTime RightNow = System.now();
	
	if(cmp.LastModifiedDate < RightNow.addMinutes(-30))
		update cmp;
}

 

Any thoughts?

 

I am using the salesforce partner WSDL and my requirement is to get the RecordType Description from the Case Object. My code is as below

 

SoapBindingStub binding=sf.getBindingBySessionId(sessionId, sfURL);
String soql="Select c.RecordTypeId From Case c where c.Id='"+caseId+"'";
QueryResult qr2=binding.query(soql);
for (int j = 0; j < qr2.getSize(); j++) {
	SObject record1 = qr2.getRecords()[j];
	MessageElement[] elements1 = record1.get_any();
	if (null != elements1) {
		for (int k = 0; k < elements1.length; ++k) {
			if (elements1[k].getName() == "RecordTypeId") {
				recordTypeId=((String) elements1[k].getValue() == null ? ""
								: (String) elements1[k].getValue());
				break;
			}
		}
	}

}

String soql1="Select r.Description From RecordType r where r.Id='"+recordTypeId+"'";
QueryResult qr=binding.query(soql1);
for (int j = 0; j < qr.getSize(); j++) {
	SObject record1 = qr.getRecords()[j];
	MessageElement[] elements1 = record1.get_any();
	if (null != elements1) {
		for (int k = 0; k < elements1.length; ++k) {
			System.out.println(elements1[k].getName());
			if (elements1[k].getName() == "Description") {
				caseType=((String) elements1[k].getValue() == null ? ""
								: (String) elements1[k].getValue());
			}
		}
	}

}

 

 I am ending up doing 2 queries instead of a single query as RecordType is lookup for the case object.Here when i do a RecordType.Description in my first Query i get only the RecordType object and i am not able to extract Description out of it and hence using the additional second query.

 

Is there way to use a single query and get the result. I am new to Salesforce and maybe i am missing some Syntax here.Looked up online but could not get any such examples.

Hello,

 

I am relatively new to Apex and Visualforce and need some guidance.

 

I have 2 objects: Billing Account and Line Items. For every Account, there can be multiple Billing Accounts each of which can have multiple Line Items. I want to return a List from a function that will give me all the Line Items of all Billing Accounts in one single list. This code compiles but on running the code, it gives me an error

 

System.NullPointerException: Attempt to de-reference a null object at line

totallines.addAll(lines);
Please help my cause by suggesting what may be causing this problem. Thanks !!

 

Here is my apex class snippet: 

 

List<Line_Items__c> l, lines, totallines;
List<Billing_Account__c> billacc;   
public List<Line_Items__c> getLineItems()
    {
        if(invoice.Billing_Account__c != null) 
        {
            l = [select id, name, Plan__c, Rate__c, Quantity__c, Total_Value__c, Activation_Date__c, Plan_Name__c, Street__c,
Unit__c, City__c from Line_Items__c where Service_Account__c =: invoice.Billing_Account__c and Status__c =: 'Active'];
           
return l;
                       
        }
        else
        { 
            billacc = [select id, Bill_Street__c, Bill_Unit_Number__c, Bill_City__c, Bill_State__c, Bill_Postal_Code__c from Billing_Account__c 
                                    where Account__c =: invoice.Account__c];
            
            integer z = 0;  
            if(billacc.size() > 0)
            {                      
                for(integer k =0; k < billacc.size(); k++)
                {
                   lines = [select id, name, Plan__c, Rate__c, Quantity__c, Total_Value__c, Activation_Date__c, Plan_Name__c,
Street__c, Unit__c, City__c from Line_Items__c where Service_Account__c =: billacc[k].id and Status__c =: 'Active'];

                   for( integer h = 0; h < lines.size(); h++)
                   {
                       totallines.addAll(lines);
                       z++;
                   }

                }
                 
                 return totallines;
             }
             
             return null;
             
         } 
                                      
    }

I am learning to code APEX as I go and piecing together how to test and deploy as well. Through trial and error I was able to write a trigger that chooses the pricebook of an opportunity based upon what is selected in the drop down Lead Source:

 

trigger setPriceBook on Opportunity (before insert) {    
    ID PRICEBOOK_YOUCAN = '01s300000002kelAAA';    
    ID PRICEBOOK_QBPP = '01s300000002kZ2AAI';    
    ID PRICEBOOK_B2B = '01s300000002kZCAAY';    
    ID PRICEBOOK_DATAREF = '01s300000002kZ7AAI'; 
    ID PRICEBOOK_STANDARD = '01s300000006i5xAAA' ; 
    ID PRICEBOOK_WINBACK = '01s300000002kegAAA'  ;  
    String SOURCE_YOUCAN = 'YouCan';        
    String SOURCE_QBPP = 'QBPP';    
    String SOURCE_B2B = 'B2B';    
    String SOURCE_DATAREF = 'Data Referral';   
    String SOURCE_WINBACK = 'WinBack' ; 
    for( Opportunity oppty : trigger.new ) {                
        if ( oppty.LeadSource == SOURCE_YOUCAN ) {            
            oppty.Pricebook2Id = PRICEBOOK_YOUCAN;        
        }        
        else if ( oppty.LeadSource == SOURCE_QBPP ) {                       
            oppty.Pricebook2Id = PRICEBOOK_QBPP;        
        }        
        else if ( oppty.LeadSource == SOURCE_B2B ) {            
            oppty.Pricebook2ID = PRICEBOOK_B2B;        
        }        
        else if (oppty.LeadSource == SOURCE_DATAREF ) {            
            oppty.Pricebook2ID = PRICEBOOK_DATAREF;        
        } 
        else if (oppty.LeadSource == SOURCE_WINBACK ) {
            oppty.PriceBook2ID = PRICEBOOK_WINBACK;
        }
        else {
            oppty.Pricebook2ID = PRICEBOOK_STANDARD;
        }      
    }
}

 

Probably not the cleanest code ever...but it worked.

 

My problem is when I wrote my test class, which is even dirtier. It initially compiled and tested clean with 80% coverage. I thought I was ready to go until I realised that I had left out a variable in the trigger. When that got saved it took me to under 75% so I had to add more test cases in. I have no idea how I got so messed up, but as a result of all my trial and error, I can't even figure out what originally worked:

 

@isTEST
private class setPriceBookTest {
    static testMethod void testsetPriceBookYouCan () {
    //Create new YouCan Opportunity 
    Opportunity oppYouCan = new Opportunity ();
    oppYouCan.Description = 'TestYouCan';
    oppYouCan.LeadSource = 'YouCan';
    oppYouCan.StageName = 'New';
    oppYouCan.Name = 'YouCanTest2';
    oppYouCan.CloseDate = System.Today();
    insert oppYouCan;
    //Select the pricebook 
    Opportunity YouCanPriceBook = [SELECT Pricebook2ID
                                    FROM Opportunity
                                    WHERE Name = 'YouCanTest2'
                                    LIMIT 1];
    ID PriceBookYouCan = '01sQ00000008bamIAA';
    //Verify Price book
    System.assertNotEquals(null, YouCanPriceBook);
    //Create new QBPP Opportunity
    Opportunity oppQBPP = new Opportunity () ;
    oppQBPP.Description = 'TestQBPP';
    oppQBPP.LeadSource = 'QBPP';
    oppQBPP.StageName = 'New';
    oppQBPP.Name = 'QBPPTest2';
    oppQBPP.CloseDate = System.Today() ;
    Database.insert (oppQBPP);
    //Select the pricebook
    Opportunity QBPPPriceBook = [SELECT Pricebook2ID
                                    FROM Opportunity
                                    WHERE Name = 'QBPPTest2'
                                    LIMIT 1];
    ID PriceBookQBPP = '01sQ00000008bahIAA';
    //Verify Price book
    System.assertNotEquals (null, QBPPPriceBook);
    //Create new WinBack Opportunity
    Opportunity oppWinBack = new Opportunity () ;
    oppWinBack.Description = 'TestWinBack';
    oppWinBack.LeadSource = 'WinBack';
    oppWinBack.StageName = 'New';
    oppWinBack.Name = 'WimBackTest2';
    oppWinBack.CloseDate = System.Today() ;
    Database.insert (oppWinBack);
    //Select the pricebook
    Opportunity WinBackPriceBook = [SELECT Pricebook2ID
                                    FROM Opportunity
                                    WHERE Name = 'WinBackTest2'
                                    LIMIT 1];
    //Verify Price book
    System.assertNotEquals (null, WinBackPriceBook);

    }
 }

 

The error that I currently get when I run the test is:

 

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

 

I have read quite a few pages that make it sound like this is a permissions problem, however I believe I am running this test as a System Administrator who would have access to any accounts.

 

Any help would be appreciated as I have been at this for over a week and still feel like I am going in circles.

  • August 09, 2010
  • Like
  • 0

Hi,

 

I have an object called meeting note and a child object called attendee.

 

When you create a meeting you can add as many attendees as you want.

 

What I would like to happen is when you add an attendee and hit save you are returned not to the attendee record but to the linked meeting note.

 

Thanks

 

Ross

     Im new to salesforce, and my company recently installed a new package from the appexchange called "project and issue management" the package came with some custom objects, one in particular is the "project" object, which I am trying to write a trigger for, but it seems that for some reason the object is not recognized.  the following very simple code errors out:

 

trigger ProjectAutoFill on SFDC_Project__c (before insert) {

SFDC_Project_c tempProject;

}

 

the error is:

 

Error: Compile Error: Invalid type: SFDC_Project_c at line 3 column 1

If anybody could help me understand what's going on here it would be greatly appreciated

Issue in apex trigger while retrieving the information from user object.

 

string uid = userinfo.getUserId();

 

User[] user = [select name from User where u.Id = uid];

 

 

for this i am getting an exception in apex trigger as:

 

Too many SOQL queries: 21

I tried using sets but how do we get total collection of userInfo to iterate in for loop and add ids of users to set .

please let me know if any soln.

 

 

hI i had an asynchronous class contains two methods.so i used to @future calls for those. i am posting my trigger code and asynchronous class.could you please help me.

Thanks in Advance

trigger code

trigger open120 on Opportunity (before insert, after update) 
{

 if(trigger.isinsert){
list<String> OpportunityAccountIds = new list<String>(); 
for(opportunity opp:trigger.new)
{OpportunityAccountIds.add(opp.Accountid);}
opp120.opp120Method(OpportunityAccountIds);}

else{
list<String> OpportunityAccountIds = new list<String>(); 
list<String> OpportunityOldAccountIds = new list<String>(); 
for(opportunity opp:trigger.new)
{OpportunityAccountIds.add(opp.Accountid);}
for(opportunity opp:trigger.old)
{OpportunityOldAccountIds.add(opp.Accountid);}

opp120.opp120Method(OpportunityAccountIds);  //getting error too many future calls:11 at this line
opp120.opp120OldMethod(OpportunityOldAccountIds);}


}

 

 

asynchronous class

public class opp120{
@future(callout=true) 
public static void opp120Method(list<String> OpportunityAccountIds){ 
list<Opportunity>lstOpp =[select Id, StageName,Expiry_Date__c from Opportunity where AccountId IN :OpportunityAccountIds];  

for(Account ac:[select id,No_of_Open_Deals_in_Next_120_Days__c from Account where id in :OpportunityAccountIds])
{
integer i=0;
 for(Integer j = 0; j < lstOpp.size(); j++)  {
if((lstopp[j].StageName=='Prospecting'||lstopp[j].StageName=='Renewal'||lstopp[j].StageName=='Submission')&&(lstopp[j].Expiry_Date__c>=System.today()+120))
{
i++;
}
ac.No_of_Open_Deals_in_Next_120_Days__c=i;
}update ac;
}
}
@future(callout=true)
public static void opp120OldMethod(list<String> OpportunityOldAccountIds){ 
list<Opportunity>lstOpp = [select Id, StageName,Expiry_Date__c from Opportunity where AccountId IN :OpportunityOldAccountIds];  

for(Account ac:[select id,No_of_Open_Deals_in_Next_120_Days__c from Account where id in :OpportunityOldAccountIds])
{
integer i=0;
 for(Integer j = 0; j < lstOpp.size(); j++)  {
if((lstopp[j].StageName=='Prospecting'||lstopp[j].StageName=='Renewal'||lstopp[j].StageName=='Submission'||lstopp[j].StageName=='ClosedLost'||lstopp[j].StageName=='ClosedWon')&&(lstopp[j].Expiry_Date__c>=System.today()+120))
{
i++;
}
ac.No_of_Open_Deals_in_Next_120_Days__c=i;

}update ac;
}
}

}

 

 

Hi Friends,

 

Anyone can tell me how to make a trigger work for bulk update and online update?  I code below to update contact from Campaign Member.  It only works if less than 10 records are added to Campaign Member, no matter is from Add to Campaign function or dataloader.

 

trigger UpdateContact1stSamplingDataafterinsertCampaignMember on CampaignMember (after insert) {   
     Map<Id, List<CampaignMember>> CampaignMembersByContactId = new Map<Id, List<CampaignMember>>();
     for (CampaignMember campmem : trigger.new) {
         if(campmem.Contact_Type__c == 'First Contact'){
               List<CampaignMember> temp = new List<CampaignMember>();            
                temp.add(campmem);            
                CampaignMembersByContactId.put(campmem.ContactId, temp); 
         }//end if
     }//end for
     Map<Id, Contact>  ContactsById = new Map<Id, Contact>([SELECT Id FROM Contact WHERE Id in :CampaignMembersByContactId.keySet()]);
     for(Id ContactId : CampaignMembersByContactId.keyset()) {  
         if(CampaignMembersByContactId.get(contactId).get(0).stage__c == '1' ) {
             ContactsById.get(contactId).Stage_1_Date__c = CampaignMembersByContactId.get(contactId).get(0).Created_Date__c;
              ContactsById.get(contactId).stage_1_Status__c = CampaignMembersByContactId.get(contactId).get(0).Status;
           }//end if

     }//end for
     update(ContactsById.values());

If I were to need to call a external webservice on the save() of a object, how would I go about doing that?  The service needs to take in some of the new data for the object, and return a string that needs to be saved to a field inside the custom object.

 

I know that I can't use a trigger, since my callout needs to return data.

I've tried creating a Controller Extension, but don't know how to call that from the standard edit layout.

I've read that I might need to write custom VisualForce pages to replace the edit pages, but I don't need to change anything about the page other than the save call.

 

Is there a better way to do this that I don't know of?  Am I on the right track?  If so, how can my custom page easily contain the same info as the standard page does?  

 

Thanks

I am trying to come up with a way to Trigger Child Records to be created once the Parent is created based on certain criteria.

 

For example:

I create a Timesheet for the begin date of 5/10/2010 and end date of 5/25/2010.  I want to create a Time Entry(child record) for each date inside of that range.

 

Does anyone know if this is possible?  I know I could trigger a child record but wasn't sure if I could based on criteria.

 

Thanks for any help!

I have a trigger that updates 1 field on the opportunity that is a summary of several fields on a custom object that has a lookup relation.  I cannot change this to a master-detail relationship, because the custom object needs exposure in the customer portal.  The problem I am running into that there are several validation rules running on the opportunity that disallow saving.  I cannot figure out how to get this field updated on the opportunity while leaving the validation rules in place.  Any ideas?  Its like I want to tell the valuation rule to ignore the rule if the update is due to the trigger.