• chubsub
  • NEWBIE
  • 25 Points
  • Member since 2010

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 57
    Replies

I've overridden the edit button with a redirect link that directs users to a visualforce edit page.  Using this link below:

 

<apex:page standardController="Guest_Card__c" showheader="false" sidebar="false">

<meta http-equiv="REFRESH" content="0;url=../apex/editguestcard?id={!Guest_Card__c.Id}&mode=edit&returl=%2F{!Guest_Card__c.Id}" />

</apex:page>

 

The custom edit page has a standard controller with sharing.  So, when a user tries to edit a record they do not have access too, it will not let them save.  How can I make it so the user doesn't even get redirected to the edit page as it would be confusing for them to allow them to fill the page out, but not let them save.  

 

Is there a way to detect the permissions of the user on the redirect page, and if they have permission to edit the record to direct them to the edit page, but if not, direct them to another page that displays an error?

 

 

Thanks for any suggestions!

Is there any way to find out why the class is failing to load when I go to package an app that needs it?  The class has about 800 lines of code including http callouts and about 80 variables. Could any of this be the reason it is not loading in the package?

 

Thanks!

I keep getting the following error when trying to create this query:

 

System.QueryException: expecting a right parentheses, found '('

 

Any Ideas? I've tried every way possible.  Thanks in advance!

 

public static String checkGCQuery = 'select Id from Guest_Card__c where Initial_Lead_Type__c = \'Independent Lead Source\' '
+ 'AND ((Move_In_Date__c != Null AND LastModifiedDate >= :system.Today().addDays(-30)) '
+ 'OR (Move_In_Date__c = Null AND LastModifiedDate >= :system.Today().addDays(-60)))';

I'm trying to run a scheduled class and I need help with building the list of records that I need to update.  Below is my class, which will be referenced by a scheduled class: 

 

I'm getting an error : Save error: Initial term of field expression must be a concrete SObject: LIST<Guest_Card__c>

 

global class GuestCardsCheck {


/*
Purpose: - On a nightly basis, any Guest Cards that meet certain conditions will be
automatically changed to "Inactive" status. A scheduled class will call this
class method to perform this check.

*/

public static String checkGCQuery = 'select Id from Guest_Card__c where Inactive_Reason__c = "Independent Lead Source" AND ((Move_In_Date__c != Null AND LastModifiedDate >= Today.addDays(-30)) OR(Move_In_Date__c = Null AND LastModifiedDate >= Today.addDays(-60)))';

public static void checkGuestCards ()
{

//collect a list of records that need to be inactivated

List <Guest_Card__c> InactiveGCs = Database.query(checkGCQuery);

InactiveGCs.Status__c = 'Inactive';

update InactiveGCs;


}

 

 

Is there a way to move trigger logic into an apex class?  I want to add a few lines into a current trigger that references an apex class that does the logic.  I'm running into trouble when trying to replicate the trigger in a class, mainly when I get to the Trigger.new method, can this be called into an apex class, as well as the Trigger.oldmap?

 

Here is the logic in the trigger, which works fine, it creates a record into a related list if a field changes.

 

Any advise?  Will the logic be possible to put into a class and how would I use the trigger.oldmap and Trigger.New methods?

 

Below is the trigger and then below this is the class I am trying to move it too:

 

trigger FieldChangeTrigger on QuoteLineItem (after update) {

 

List <QLI_History_Tracking__c> history = new List <QLI_History_Tracking__c>();

for (QuoteLineItem qli : Trigger.new) {

if(qli.UnitPrice != Null && qli.UnitPrice != trigger.oldMap.get(qli.Id).UnitPrice)
{
history.add(new QLI_History_Tracking__c (
Quote_Line_Item__c = qli.Id,
Sales_Price_From__c = trigger.oldMap.get(qli.Id).UnitPrice,
Sales_Price_To__c = qli.UnitPrice
));
}

if(history.size() >0)
{
insert history;
}

}

 

 

 

Here is what I will be changing the trigger into:

 


trigger FieldChangeTrigger on QuoteLineItem (after update) {

//need to copy all relevant fields so they will always pick up previous values when one is changed
//object wil be called pricing history

if(Trigger.isUpdate && Trigger.isAfter){

managePricingHistory.afterupdate(Trigger.New);

}

 

 

 

An then the above trigger will reference this class

 

public with sharing class managePricingHistory {


public static list<QuoteLineItem> afterUpdate(list<QuoteLineItem> qli) {

List <QLI_History_Tracking__c> history = new List <QLI_History_Tracking__c>();

 

for (QuoteLineItem qlit : Trigger.new) {  

// I'm getting an error message here that says "Loop variable must be of type SObject


}

if(history.size() >0)
{
insert history;
}

return qli;
}

}

 

 

 

 

I'm trying to get 100% coverage on by Apex Batch, so I had to remove this method and put it in it's own class, but I'm struggling as how to cover this method which calls the batch

 

//class to run batch from VS page


public static void runBatchJOB()
{
batchReferrals batchCls = new batchReferrals();
// 2 is size of batch
if (!test.isRunningTest())
database.executebatch(batchCls , 2);
}

 

 

static testmethod void testrunBatchJob()
{

 

//what can i put here to cover the runBatchJob()?

}

How can I call the Contact records I'm creating in my test class?  How can I write a systeAssertEquals on the records that are inserted after the batch is ran?  Below is my test class, but it's throwing an error message that says the variable testcon does not exist when I try to query the contact that it is in the test class:

 

@istest
private class testBatchReferrals {

/*
Purpose: - This is the test method to test the batchReferrals class to ensure it runs properly
- Within this test class
- an account and 2 contacts are created.
- referral entry records are created based off the amount of similar Referral Physicians and MRN's there are in that month
- the batch process takes place
- the result will be 2 new referral entry summary records created that count the similar records for each month.


*/

static testmethod void testBatch(){
Test.startTest();

list<Account> accs = new list<Account>();
Account a1 = new Account(Name = 'test account1');
accs.add(a1);

list<Contact> testcon = new list<Contact>();
Contact c1 = new Contact(FirstName = 'test contact1',  AccountId = a1.Id);
Contact c2 = new Contact(FirstName = 'test contact2', AccountId = a1.Id);
testcon.add(c1);
testcon.add(c2);

list<Referral_Entry__c> testrefent = new list<Referral_Entry__c>();
Referral_Entry__c r1c1 = new Referral_Entry__c (Name = 'test referral 1 con 1', Referring_Physician_del__c = c1.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r2c1 = new Referral_Entry__c (Name = 'test referral 2 con 1', Referring_Physician_del__c = c1.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r1c2 = new Referral_Entry__c (Name = 'test referral 1 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r2c2 = new Referral_Entry__c (Name = 'test referral 2 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c exsum = new Referral_Entry__c (Name = 'test summary referral 1 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), Count_of_MRN__c = Decimal.Valueof('2'));
testrefent.add(r1c1);
testrefent.add(r2c1);
testrefent.add(r1c2);
testrefent.add(r2c2);
testrefent.add(exsum);


batchReferrals batch = new batchReferrals();
batch.contactquery = 'select Id from Contact where Id in :testcon';
ID jobId = Database.executeBatch(batch, 2);
Integer t = [Select count() from Referral_Entry__c where Count_of_MRN__c != Null Id in :testrefent];
system.AssertEquals(0, t);  - The size of this should be 6 (4 of the existing Referr_Entry__c records plus the 2 new summary Referral_Entry__c records.  The existing summary record listed above will be deleted since there is a value in the Count_of_MRN__c field.
Test.stopTest();

 

}

}

 

 

 

I'm getting 75% coverage, but I want to do some system asserts on the Referral Entry object to ensure there are actually 2 records created that have a value in the Count_of_MRN__c field once the batch is complete.

This should be simple, but I can complete this class that inserts records from a Map

 

I've filed up a map that contains Contact ID's, Dates and a Unique Number called MRN__c.  Now I am trying to insert records that are filled with in the map into the Referral_Entry__c object at the end of this class.  

 

Any suggestions? I highlighted where I am having issues below:

 

 

//map to store key month. only including one date for now that corresponds with the one records

//list contact from query above
list<Contact> cons = (list<Contact>)scope;
set<Id> conids = new set<Id>();
for (Contact con : cons) conids.add(con.Id);

list<Contact> fullcontacts = [select Id, LastName,
(select Service_Date__c, MRN__c from Referral_Entries_del__r)
from Contact where Id in :conids];

map<Id, map<Date, set<Decimal>>> conid2datemapmap = new map<Id, map<Date, set<Decimal>>>();
for (Id conid : conids)
{
conid2datemapmap.put(conid, new map<Date, set<Decimal>>());
}

for (Contact con : fullcontacts)
{
//get con map to set of MRNs
//run refe loop

//- set of MRN's for individual Physician for that month
map<Date, set<Decimal>> mrns = conid2datemapmap.get(con.Id);

list<Referral_Entry__c> refs = con.Referral_Entries_del__r;

/*
[Select Id, Service_Date__c, Referring_Physician_del__c, MRN__c
FROM Referral_Entry__c
Where Referring_Physician_del__c = :cons[0].Id])
*/
for (Referral_Entry__c refe : refs)
{

totalprocessed ++;

//Find first of month
Date StartOfMonth = refe.Service_Date__c.toStartOfMonth();

//get MRNs already entered for this month
set<Decimal> theseMRNs = mrns.get(StartOfMonth);

//If there are no MRNs already entered for this month
if (theseMRNs == null)
theseMRNs = new set<Decimal>();

//Add this MRN to set of MRNs for this month
if (refe.MRN__c != null)
theseMRNs.add(refe.MRN__c);

//put set in map
mrns.put(StartOfMonth, theseMRNs);
}

//put map back into con2mrnmap
conid2datemapmap.put(con.Id, mrns);

//set up debug log
debuglog += '<br/>new contact ' + con.Id;
for (Date d : mrns.keyset())
{
debuglog += '<br/>' + d + ' ' + mrns.get(d);
}
} //end for Contact con : fullcontacts


//Delete existing Summary records, which are records without Null values in the Count of MRN field

List<Referral_Entry__c> sumrectodelete = [Select Id, Service_Date__c, Referring_Physician_del__c, MRN__c, Count_of_MRN__c
FROM Referral_Entry__c
Where Count_of_MRN__c != Null];
delete sumrectodelete;

//Insert New Summary records

 

List<Referral_Entry__c> newsumrecords = new List<Referral_Entry__c>();

for (Contact con : fullcontacts)

{

for (Date d : mrns.keyset())  
{
newsumrecords.Referring_Physician_del__c = con.Id;
}

}

 

 

 

This is my first time creating Batch Apex.  I'm looking to count similar records in a custom object and create records within that object based of this count.  I'm looking to see if anyone can point me in the right direction to get started.  I've read a bunch on Batch Apex and seen the example of reassigning Account owners, but my scenario is a little different.

 

Below is my scenario:

 

Custom_Object__c - This is the object where there will be 200,000 records imported each month.

Number_Reference__c - This will be the field in which may have duplicate values

Contact_Reference__c - This will be the name of the Contact

Number_Count__c - This will be a sum field that will populate in a record after the Batch Apex is ran.

 

Month 1, the user imports records.  Let's say that 500 of these records have the same Contact_Reference__c and the same Number_Reference__c.  For example, there are 500 records where John Doe has the number 123 in the Number_Reference__c.  Now, when the user presses a button to run the Batch Apex, it will detect that John Doe has 500 identical records, (meaning records with the same Number_Reference__c and Contact_Reference__c fields), and will then create a record in the same object that equal the following fields:  

Contact_Reference__c = John Doe

Number_Reference__c = 123

Number_Count__c = 50

 

Thanks in advance for any guidance.

 

 

 

 

 

My goal here is to run a time-based workflow to update the Quote Status 30 days after the Quote as been approved.  It sounds like an easy requirement, when the status is changed to "Approved" via the approval process, a time-based workflow will update the status again 30 days after.  But, a workflow can not set off another workflow, meaning, once the workflow in the approval process that update the status to "Approved", that will not trigger another workflow to set it to another status of "Approved all the way" afterwards.  So,I thought I try a trigger.

 

My thought was to create a trigger to update a checkbox field called Recently_Approved__c when the Status on the Quote changes from "Draft" to "Approved".  Then, a workflow will update the Quote Status again to "Approved all the way" after the Recently_Approved__c checkbox is set to True. So, I created the trigger, and it worked, but only on Before Update, which did not trigger the workflow to update the status to "Approved all the way" when the Recently_Approved__c checkbox was checked via the trigger.

 

My main issue is my trigger is trying to update the Quote record after it has been approved.  So, when the user that needs to approve the record hits approved, a field update in the approval process will update the Status to "Approved", which should trigger the the Recently_Approved__c checkbox to True, but I get this error message:

execution of AfterUpdate caused by: System.FinalException: Record is read-only

 

So, I guess my question is how can I get around this by updating a field via a trigger on a record that is locked via an approval process?

 

Thanks in advance!

The following class is referenced in a trigger on the Quote.  I am trying to populate a field on the Quote called Tracking Number.  This tracking number will contain a number sequence to keep track of how many quotes have been created on an opportunity.  So, if the first Quote is created, the Tracking_Number__c will equal to 1, then, the second Quote is created, the number wil be 2.  I'm getting the System.NullPointerException: Attempt to de-reference a null object error message on the highlighted line.  Any ideas on how to fix it?

 

Thanks in advance for any suggestions. 

 

 

public static list<Quote> beforeInsert(list<Quote> quos) {
set<Id> oppids = new set<id>();
map<Id, Quote> oppid2quotemap = new map<Id, Quote>();

for (Quote q : quos)
{
oppids.add(q.OpportunityId);
oppid2quotemap.put(q.Opportunity.Id, q);
}

//query for Opps with Quotes attached
list<Opportunity> oppswquotes = [select Id, Name,
(select Id, Tracking_Number__c from Quotes order by CreatedDate)
from Opportunity
where Id in :oppids];

for (Opportunity o : oppswquotes)
{
Integer counter = 1;
for (Quote q : o.Quotes)
{

q.Tracking_Number__c = counter;

if (Trigger.newmap.containsKey(q.Id))
{
Quote thisquote = (Quote)Trigger.newmap.get(q.Id);
thisquote.Tracking_Number__c = counter;
counter ++;
}

//if IsInsert, use counter to set triggering Quote
//find triggering Quote from a map<Id, Quote>: Opportunity ID 2 Quote map

Quote thisquote = oppid2quotemap.get(o.Id);
if(oppswquotes.size()>0){
}
thisquote.Tracking_Number__c = counter;
}

//this will include the quotes we need to count

list<Quote> allquos = [select Id, OpportunityId, CreatedDate
from Quote
where OpportunityId in :oppids
order by OpportunityId, CreatedDate];

map<Id, Integer> quoid2seqnummap = new map<Id, Integer>();

//now go back through passed Quote list

for (Quote q :quos)
{
Integer seqnum = quoid2seqnummap.get(q.Id);
//TODO: populate Name field or store seq num somewhere

q.Tracking_Number__c = seqnum;
}

}
return quos;

}

I'm using a wrapper class on the Case object so that users can select multiple users to "tie" them to a case.  Upon selection, these additional users are inserted into the Case_Associate__c object, which is a detail to the Case.  

 

Here is a link to the full code: http://boards.developerforce.com/t5/Apex-Code-Development/Test-Method-to-cover-Wrapper-Class-only-covering-79/m-p/364981

 

How can I check to see if a record has already been created in the Case_Assoicate object in my Apex class, before inserting, to avoid duplicate Case Associate records that include the same case ID and user ID?  Below is the code snippet I need to expand on:

 

Thanks for any help!

 

public PageReference processSelected() {

 

//We create a new list of Users that we be populated only with Users if they are selected


List<User> selectedUsers = new List<User>();
List<Case_Associate__c> caseAss = new List<Case_Associate__c>();  //here is where I list out the records to set it up to check for dupes before inserting

 

//We will cycle through our list of cUsers and will check to see if the selected property is set to true, if it is we add the User to the selectedUsers list


for(cUser cUse: getUsers()) { 
if(cUse.selected == true && User.Id != Case_Associate__c.User.Id) {  // check for duplicates on the Case Associate object before adding the Users to the selectedUsers list
selectedUsers.add(cUse.use);
}
}

I'm only getting 79% coverage, the lines in red aren't cover, any ideas on how to increase my coverage?  Thanks!

 

Test Method:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@isTest
private class wrapperClassControllerTest {

static testmethod void wrapperClassController()
  
  {
  
 Profile p = [select id from profile where name='Standard User'];
  User user=new User(alias = 'test123', email='test123@noemail.com',
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, country='United States',
            timezonesidkey='America/Los_Angeles', username='test123@noemail.com');
        insert user;     

Account account = new Account();// specify all the required fields
account.name = 'testing';
insert account;
Contact contact = new Contact();// specify all the required fields
contact.lastname = 'test';
insert contact;
Case ca = new Case();
ca.accountId = account.Id;
ca.contactId = contact.Id;
insert ca;

 string userIndex=user.ID; 

        
        ApexPages.StandardController controller = new ApexPages.StandardController(ca);
        wrapperClassController sc = new wrapperClassController(controller);      
         Pagereference S = sc.processSelected();
         
 
 system.assertEquals(3,sc.userList.size());   
 
 sc.userList=sc.getUsers();  
 sc.userList[0].selected=true;    


       }

    }

 

 

 

Class:

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class wrapperClassController {

    public wrapperClassController(ApexPages.StandardController controller) {

    }
    
    //Our collection of the class/wrapper objects cUser 
    public List<cUser> userList {get; set;}



    //This method uses a simple SOQL query to return a List of Users
   
    public List<cUser> getUsers() {
        if(userList == null) {
            userList = new List<cUser>();
            for(User u: [select Id, Name, Email, Phone from User]) {
                // As each contact is processed we create a new cContact object and add it to the contactList
                userList.add(new cUser(u));
            }
        }
        return userList;
    }

    public PageReference processSelected() {

                //We create a new list of Users that we be populated only with Users if they are selected
        List<User> selectedUsers = new List<User>();
      

        //We will cycle through our list of cUsers and will check to see if the selected property is set to true, if it is we add the User to the selectedUsers list
        for(cUser cUse: getUsers()) {
            if(cUse.selected == true) {
                selectedUsers.add(cUse.use);
            }
        }

        // Now we have our list of selected users and can add them to the User notification object on Cases
       

      
      for(User us : selectedUsers) {
      
             // Create new Case Associate Record and Insert
         Case_Associate__c newCaseAssociateRecord = new Case_Associate__c();
         newCaseAssociateRecord.User__c =  us.ID;
         newCaseAssociateRecord.Case__c = (''+ApexPages.currentPage().getParameters().get('id'));
         
         insert newCaseAssociateRecord;  
   
      }
       // Redirect back to case record   
              
      return new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
        
    }
    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. 
    // In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
    
    public class cUser {
        public User use {get; set;}
        public Boolean selected {get; set;}

        //This is the contructor method. When we create a new cUser object we pass a User that is set to the 'use' property. We also set the selected value to false
        public cUser(User u) {
            use = u;
            selected = false;
        }
    }
    
  
    
}

Hello, my overall goal here is to copy multiple users on any case record. 

 

I've created a custom object called Case Associate, which is a master/detail to Case.  The records in this object will include a lookup field to the selected user. Once the record is created on this object, an workflow will send an email to the user specified in the record.

 

To automate this task, I've created a custom button on the Case object called "Select Users", which brings the user to a visualforce page, which has an extension to list and select multiple users.

 

Once the users selects multiple users and clicks "Processed Selected", I want the Case Associate records to automatically populate with the amount of Users the user selects.  So to be more clear, the user is on a Case, clicks a button and selects 5 different users, then clicks "process selected"  They will then be redirected to the Case record and will see 5 records appear in the related list of Case Associate object.  Each of these records will contain a lookup to the user that was selected.

 

I altered the following code to help create this page and class, but I'm struggling on the process request method:

http://wiki.developerforce.com/page/Wrapper_Class

 

Any ideas on the code needed to pass the ID of the selectedUser into each record of the Case_Associate?

 

Below is what I've tried so far, but I get an error message:

 

public PageReference processSelected() {

//We create a new list of Users that we be populated only with Users if they are selected
List<User> selectedUsers = new List<User>();

//We will cycle through our list of cUsers and will check to see if the selected property is set to true, if it is we add the User to the selectedUsers list
for(cUser cUse: getUsers()) {
if(cUse.selected == true) {
selectedUsers.add(cUse.use);
}
}

// Now we have our list of selected users and can add them to the Case Associate object on Cases
 for(User use: selectedUsers) {
Case_Associate__c caseA = new Case_Associate__c (User__c=selectedUsers.Id);

Compile Error: Initial term of field expression must be a concrete SObject: LIST<User> 

}

insert selectedUsers;

I'm getting this error message when referring to a variable in the query below:  The code works fine, but only throws this error message if there is a value in the SOF_Requested_Date field.  Whenever this is the case, nothing should happen, but if there is not any value in that field, another field is updated, which it does just fine.  

 

thanks for any advice!

 

list<Opportunity> allopps = [select Id, Daily_Tracking_Number__c, SOF_Requested_Date__c, AccountId, CreatedDate
from Opportunity
where AccountId in :accids
and (CreatedDate > :FirstDate.addDays(-1))  //This is the line that is causeing the error
and (CreatedDate < :LastDate.addDays(1))
order by AccountId, CreatedDate];

I'm scratching my head on this one.  What I'm trying to is update previous opportunity names in sequece by the date they were created and the account they were created for.  The trigger I am writing will update a field on the opportunity called Daily_Tracking_Number__c, but only if there is a date in the SOF_Requested_Date field.  

 

The daily tracking number field is then incorporated into a workflow that will update the opportunity name with the daily tracking number on the end "[OppName - Date - Daily Tracking Number".

 

For example:

Client A had 5 Opportunities created within the date range of 5/01/2010 and 6/01/2010.  Once these are updated, I'm trying to have the Daily_Tracking_Number__c field update in sequence by the CreatedDate.  Below is a chart of what I'm trying to explain:

 

Client A:

Opportunity created on 5/1 - Daily_Tracking_Number will = 1

Opportunity created on 5/4 - Daily_Tracking_Number will = 2

Opportunity created on 5/10 (but there is no date in the SOF Releasted Date - Daily_Tracking_Number will = 0

Opportunity created on 5/12 - Daily_Tracking_Number will = 3

 

Below is the code I have so far, but it does not work properly.  I'm not getting any error messages, but it's not updating the daily tracking number field:

 

Any ideas would be greatly appreciated!

 

Trigger:

 

trigger ManageOpportunitiesBeforeUpdate on Opportunity (before update) {   
    
        if(Trigger.isUpdate && Trigger.isBefore){

        ManageOpportunitiesBeforeUpdate.beforeUpdate(Trigger.New); 
    }   
} //end trigger

 

 

 

 

 

Class referenced by the trigger:

 

public static void beforeUpdate(list<Opportunity> optys)
{
set<Id> accids = new set<id>();
set<Date> createdDates = new set<Date>();

for (Opportunity o : optys)
{
if (o.SOF_Requested_Date__c == null)
{
accids.add(o.AccountId);
createdDates.add(o.CreatedDate.date());
}
}

//this will include the opps we need to count
Id thisaccid;
Date thisdate;
list<Opportunity> allopps = [select Id, AccountId, CreatedDate
from Opportunity
where Id in :accids
and CreatedDate in :createdDates
order by AccountId, CreatedDate];
map<Id, Integer> oppid2seqnummap = new map<Id, Integer>();

//reset placeholders: last Account, last Date, current counter - JS alerted 11/17 to check the size of the list before getting the value
if(allopps.size()>0){
thisaccid = allopps[0].AccountId;
thisdate = allopps[0].CreatedDate.date();
}
Integer counter = 0;


//keep track of all sequence numbers
for (Opportunity o : allopps)
{

//same account as the last one?
if (thisaccid == o.AccountID)
{
//same date as the last one?
if (thisdate == o.CreatedDate.date())
{
counter++;
}
else //new date
{
counter = 1;
}
}
else //new account
{
counter = 1;
}

//store counter for this Opp
oppid2seqnummap.put(o.Id, counter);

//reset to compare to next Opp
thisdate = o.CreatedDate.date();
thisaccid = o.AccountId;
}

//now go back through passed Opp list
for (Opportunity o :optys)
{
Integer seqnum = oppid2seqnummap.get(o.Id);
//TODO: populate Name field or store seq num somewhere

o.Daily_Tracking_Number__c = seqnum;

 


}

} //end before update


} //end class


 

Hello, I'm getting to following error message, any ideas? Thanks in advance!

 

System.ListException: List index out of bounds: 0: Class.ManageOpportunitiesBeforeUpdate.beforeUpdate: line 84, column 32

 

list<Opportunity> allopps = [select Id, AccountId, CreatedDate
from Opportunity
where Id in :accids
and CreatedDate in :createdDates
order by AccountId, CreatedDate];
map<Id, Integer> oppid2seqnummap = new map<Id, Integer>();

//reset placeholders: last Account, last Date, current counter
Id thisaccid = allopps[0].AccountId;
Date thisdate = allopps[0].CreatedDate.date();
Integer counter = 0;

 

 

I have a field called Daily_Tracking_Number__c on Opportunity.  This field will track the number of opportunities that have been submitted on an Account each day.  So, the first opportunity that is created today for Client A will be 1, then for another opportunity created that day, the field will update to 2.  Then, the next day, if an opportunity is created for Client A, it will reset back to 1.  

 

Now, the part I'm struggling with is narrowing it down per Account, so if an opportunity is created for Client A today, the field will be 1, then, if an opportunity is created for Client B, the field on that Opportunity will also be 1.  And if another opportunity is created the same day for Client A, the field will equal 2, and then the same for Client B. And then it will reset again the next day.

 

The code below will update the Daily Tracking Number field correctly and will reset every day, but it doesnt narrow it down by Account like I explained above.  What it does is give the Daily Tracking Number field a number that picks up where the last Opportunity was created, regardless of the Account.

 

Any ideas on binding this code to the Account?  Thanks!

 

This is the trigger and class that I have so far:

 



1
2
3
4
5
6
trigger ManageOpportunities on Opportunity (before insert) { 

    if(Trigger.isInsert && Trigger.isBefore){
        ManageOpportunities.beforeInsert(Trigger.New); 
    }     
} //end trigger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public with sharing class ManageOpportunities {


//Tracking Numbers are reset each day, so we'll query for the current number and add to it for the optys
public static void beforeInsert(Opportunity [] optys) {

Decimal todaystrackingnumber;
//get the current number - there might not be one, so we'll query into a list

Opportunity [] todaysoptys =  [Select Id, AccountId, Daily_Tracking_Number__c from Opportunity where CreatedDate = TODAY AND Daily_Tracking_Number__c != null order by Daily_Tracking_Number__c Desc];

//if there is a case, then use the first one, since it is ordered by number
    if (todaysoptys.size() > 0) {
        todaystrackingnumber = todaysoptys[0].Daily_Tracking_Number__c + 1;
    }
    else {
        todaystrackingnumber = 1;
    }

//Now loop through the new cases and allocate a number

for (Opportunity o: optys) {
o.Daily_Tracking_Number__c = todaystrackingnumber;
todaystrackingnumber ++;
}
    
} //end before insert


} //end class

Hello, I have a requirment to update the opportunity name based on the number of opportunities that have been created that day for that client.  I'm fairly new to apex triggers and wanted to find out how to get started constructing this, any advice or direction would be awesome.  Here is some more details:

 

Opportunity is created on 11/11/2011 for Client A.  The users enters "Big Wammy" into the Opportunity Name field.  Before Insert, the trigger will update the opportunity Name to  "Big Wammy - 11/11/2011 - 001"  Then, another opportunity is created on the same day for the same Account and the user enters "Small Deal" into the opportunity name field, now the trigger will update the name to "Small Deal - 11/11/2011 - 002". 

 

Now, the next day, on 11/12/2011, the user creates another opportunity for Client A and enteres "Big Deal" in the Opportunity Name field.  Now, the trigger will update the Name to "Big Deal - 11/12/2011 - 001".  The number on the end will need to reset back to 001 every day.  

 

My trigger will be on the Opportunity and will need to query for all opportunities created that day for that account, and put them in order.  

 

Any suggestions on how to get started?  Thanks in advance!

Is it possible to auto-generate a quote pdf based on changes to the quote line items.  For example, a quote and quote line items have already been create, and a quote pdf has been generated and attached to the quote and is shown in the quote pdf related list.  Now, the user goes back and changes values in the quote line items.  Is there a way to automatically generate a quote pdf after the user makes these changes to the line items?   Meaning, another quote pdf will appear in the related list based off the changes made to the line items?

 

I'm currently trying to see if it's possible to generate a Quote Document with a trigger on the Quote, below is some code for the trigger, but I'm stuck at specifying the template name, the only template I have access to is a template I created called "Testing"  :

 

Can this even be done? If so, how would I specify the template to use?

 

Thanks in advance!

 

trigger createQuotePDF on Quote (after update) {
List<QuoteDocument> sr = new List<QuoteDocument>();

    for (Quote newQuote: Trigger.New)
         if (newQuote.Quote_Approval_Status__c == 'Quote on Hold'){
                 sr.add (new QuoteDocument(
                 Template = 'Testing'));  
         }
   insert sr;
 }



Hi Everyone,

I am very new to apex development and I'm hoping one of you can help.   I'm trying to create a controller that is using what I believe (or hope) is a simple query.   I'm attempting to use the case ID to retrieve a list of  related records from a custom object that is related to cases.  However when I execute the code as it appears below, I get zero (0) records. But, if I hard code a 18-digit ID in query statement, the controller works exactly as I want it to.  I suspect the problem has something to do with comparing 18-digit object ID's with 15-digit ID's but I'm not sure how to fix this or this is the actual problem. Can someone tell me what I'm doing wrong?  

My code is below.

 

 

public class mycustomController {
    //capture the case id
    public Id thisCaseId {get;set;}
    //a list to hold the customer objects for this case
    public List<custom_object__c> thesecobjects = new List<custom_object__c>();
    //get the custom objects into the list
    public List<custom_object__c> getthesecobjects() {
        //criteria for the custom objects
        thesecobjects = [Select ID , Name, Case__r.Id, Case__r.CaseNumber FROM custom_object__c WHERE ID =: thisCaseId  
                        ORDER BY Case__c DESC LIMIT 10];
        return thesecobjects;
    }
}

 

Is there any way to find out why the class is failing to load when I go to package an app that needs it?  The class has about 800 lines of code including http callouts and about 80 variables. Could any of this be the reason it is not loading in the package?

 

Thanks!

I'm trying to run a scheduled class and I need help with building the list of records that I need to update.  Below is my class, which will be referenced by a scheduled class: 

 

I'm getting an error : Save error: Initial term of field expression must be a concrete SObject: LIST<Guest_Card__c>

 

global class GuestCardsCheck {


/*
Purpose: - On a nightly basis, any Guest Cards that meet certain conditions will be
automatically changed to "Inactive" status. A scheduled class will call this
class method to perform this check.

*/

public static String checkGCQuery = 'select Id from Guest_Card__c where Inactive_Reason__c = "Independent Lead Source" AND ((Move_In_Date__c != Null AND LastModifiedDate >= Today.addDays(-30)) OR(Move_In_Date__c = Null AND LastModifiedDate >= Today.addDays(-60)))';

public static void checkGuestCards ()
{

//collect a list of records that need to be inactivated

List <Guest_Card__c> InactiveGCs = Database.query(checkGCQuery);

InactiveGCs.Status__c = 'Inactive';

update InactiveGCs;


}

 

 

Is there a way to move trigger logic into an apex class?  I want to add a few lines into a current trigger that references an apex class that does the logic.  I'm running into trouble when trying to replicate the trigger in a class, mainly when I get to the Trigger.new method, can this be called into an apex class, as well as the Trigger.oldmap?

 

Here is the logic in the trigger, which works fine, it creates a record into a related list if a field changes.

 

Any advise?  Will the logic be possible to put into a class and how would I use the trigger.oldmap and Trigger.New methods?

 

Below is the trigger and then below this is the class I am trying to move it too:

 

trigger FieldChangeTrigger on QuoteLineItem (after update) {

 

List <QLI_History_Tracking__c> history = new List <QLI_History_Tracking__c>();

for (QuoteLineItem qli : Trigger.new) {

if(qli.UnitPrice != Null && qli.UnitPrice != trigger.oldMap.get(qli.Id).UnitPrice)
{
history.add(new QLI_History_Tracking__c (
Quote_Line_Item__c = qli.Id,
Sales_Price_From__c = trigger.oldMap.get(qli.Id).UnitPrice,
Sales_Price_To__c = qli.UnitPrice
));
}

if(history.size() >0)
{
insert history;
}

}

 

 

 

Here is what I will be changing the trigger into:

 


trigger FieldChangeTrigger on QuoteLineItem (after update) {

//need to copy all relevant fields so they will always pick up previous values when one is changed
//object wil be called pricing history

if(Trigger.isUpdate && Trigger.isAfter){

managePricingHistory.afterupdate(Trigger.New);

}

 

 

 

An then the above trigger will reference this class

 

public with sharing class managePricingHistory {


public static list<QuoteLineItem> afterUpdate(list<QuoteLineItem> qli) {

List <QLI_History_Tracking__c> history = new List <QLI_History_Tracking__c>();

 

for (QuoteLineItem qlit : Trigger.new) {  

// I'm getting an error message here that says "Loop variable must be of type SObject


}

if(history.size() >0)
{
insert history;
}

return qli;
}

}

 

 

 

 

I'm trying to get 100% coverage on by Apex Batch, so I had to remove this method and put it in it's own class, but I'm struggling as how to cover this method which calls the batch

 

//class to run batch from VS page


public static void runBatchJOB()
{
batchReferrals batchCls = new batchReferrals();
// 2 is size of batch
if (!test.isRunningTest())
database.executebatch(batchCls , 2);
}

 

 

static testmethod void testrunBatchJob()
{

 

//what can i put here to cover the runBatchJob()?

}

How can I call the Contact records I'm creating in my test class?  How can I write a systeAssertEquals on the records that are inserted after the batch is ran?  Below is my test class, but it's throwing an error message that says the variable testcon does not exist when I try to query the contact that it is in the test class:

 

@istest
private class testBatchReferrals {

/*
Purpose: - This is the test method to test the batchReferrals class to ensure it runs properly
- Within this test class
- an account and 2 contacts are created.
- referral entry records are created based off the amount of similar Referral Physicians and MRN's there are in that month
- the batch process takes place
- the result will be 2 new referral entry summary records created that count the similar records for each month.


*/

static testmethod void testBatch(){
Test.startTest();

list<Account> accs = new list<Account>();
Account a1 = new Account(Name = 'test account1');
accs.add(a1);

list<Contact> testcon = new list<Contact>();
Contact c1 = new Contact(FirstName = 'test contact1',  AccountId = a1.Id);
Contact c2 = new Contact(FirstName = 'test contact2', AccountId = a1.Id);
testcon.add(c1);
testcon.add(c2);

list<Referral_Entry__c> testrefent = new list<Referral_Entry__c>();
Referral_Entry__c r1c1 = new Referral_Entry__c (Name = 'test referral 1 con 1', Referring_Physician_del__c = c1.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r2c1 = new Referral_Entry__c (Name = 'test referral 2 con 1', Referring_Physician_del__c = c1.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r1c2 = new Referral_Entry__c (Name = 'test referral 1 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c r2c2 = new Referral_Entry__c (Name = 'test referral 2 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), MRN__c = Decimal.Valueof('1'));
Referral_Entry__c exsum = new Referral_Entry__c (Name = 'test summary referral 1 con 2', Referring_Physician_del__c = c2.Id, Service_Date__c = system.today(), Count_of_MRN__c = Decimal.Valueof('2'));
testrefent.add(r1c1);
testrefent.add(r2c1);
testrefent.add(r1c2);
testrefent.add(r2c2);
testrefent.add(exsum);


batchReferrals batch = new batchReferrals();
batch.contactquery = 'select Id from Contact where Id in :testcon';
ID jobId = Database.executeBatch(batch, 2);
Integer t = [Select count() from Referral_Entry__c where Count_of_MRN__c != Null Id in :testrefent];
system.AssertEquals(0, t);  - The size of this should be 6 (4 of the existing Referr_Entry__c records plus the 2 new summary Referral_Entry__c records.  The existing summary record listed above will be deleted since there is a value in the Count_of_MRN__c field.
Test.stopTest();

 

}

}

 

 

 

I'm getting 75% coverage, but I want to do some system asserts on the Referral Entry object to ensure there are actually 2 records created that have a value in the Count_of_MRN__c field once the batch is complete.

This should be simple, but I can complete this class that inserts records from a Map

 

I've filed up a map that contains Contact ID's, Dates and a Unique Number called MRN__c.  Now I am trying to insert records that are filled with in the map into the Referral_Entry__c object at the end of this class.  

 

Any suggestions? I highlighted where I am having issues below:

 

 

//map to store key month. only including one date for now that corresponds with the one records

//list contact from query above
list<Contact> cons = (list<Contact>)scope;
set<Id> conids = new set<Id>();
for (Contact con : cons) conids.add(con.Id);

list<Contact> fullcontacts = [select Id, LastName,
(select Service_Date__c, MRN__c from Referral_Entries_del__r)
from Contact where Id in :conids];

map<Id, map<Date, set<Decimal>>> conid2datemapmap = new map<Id, map<Date, set<Decimal>>>();
for (Id conid : conids)
{
conid2datemapmap.put(conid, new map<Date, set<Decimal>>());
}

for (Contact con : fullcontacts)
{
//get con map to set of MRNs
//run refe loop

//- set of MRN's for individual Physician for that month
map<Date, set<Decimal>> mrns = conid2datemapmap.get(con.Id);

list<Referral_Entry__c> refs = con.Referral_Entries_del__r;

/*
[Select Id, Service_Date__c, Referring_Physician_del__c, MRN__c
FROM Referral_Entry__c
Where Referring_Physician_del__c = :cons[0].Id])
*/
for (Referral_Entry__c refe : refs)
{

totalprocessed ++;

//Find first of month
Date StartOfMonth = refe.Service_Date__c.toStartOfMonth();

//get MRNs already entered for this month
set<Decimal> theseMRNs = mrns.get(StartOfMonth);

//If there are no MRNs already entered for this month
if (theseMRNs == null)
theseMRNs = new set<Decimal>();

//Add this MRN to set of MRNs for this month
if (refe.MRN__c != null)
theseMRNs.add(refe.MRN__c);

//put set in map
mrns.put(StartOfMonth, theseMRNs);
}

//put map back into con2mrnmap
conid2datemapmap.put(con.Id, mrns);

//set up debug log
debuglog += '<br/>new contact ' + con.Id;
for (Date d : mrns.keyset())
{
debuglog += '<br/>' + d + ' ' + mrns.get(d);
}
} //end for Contact con : fullcontacts


//Delete existing Summary records, which are records without Null values in the Count of MRN field

List<Referral_Entry__c> sumrectodelete = [Select Id, Service_Date__c, Referring_Physician_del__c, MRN__c, Count_of_MRN__c
FROM Referral_Entry__c
Where Count_of_MRN__c != Null];
delete sumrectodelete;

//Insert New Summary records

 

List<Referral_Entry__c> newsumrecords = new List<Referral_Entry__c>();

for (Contact con : fullcontacts)

{

for (Date d : mrns.keyset())  
{
newsumrecords.Referring_Physician_del__c = con.Id;
}

}

 

 

 

This is my first time creating Batch Apex.  I'm looking to count similar records in a custom object and create records within that object based of this count.  I'm looking to see if anyone can point me in the right direction to get started.  I've read a bunch on Batch Apex and seen the example of reassigning Account owners, but my scenario is a little different.

 

Below is my scenario:

 

Custom_Object__c - This is the object where there will be 200,000 records imported each month.

Number_Reference__c - This will be the field in which may have duplicate values

Contact_Reference__c - This will be the name of the Contact

Number_Count__c - This will be a sum field that will populate in a record after the Batch Apex is ran.

 

Month 1, the user imports records.  Let's say that 500 of these records have the same Contact_Reference__c and the same Number_Reference__c.  For example, there are 500 records where John Doe has the number 123 in the Number_Reference__c.  Now, when the user presses a button to run the Batch Apex, it will detect that John Doe has 500 identical records, (meaning records with the same Number_Reference__c and Contact_Reference__c fields), and will then create a record in the same object that equal the following fields:  

Contact_Reference__c = John Doe

Number_Reference__c = 123

Number_Count__c = 50

 

Thanks in advance for any guidance.

 

 

 

 

 

Hello

 

I'm looking for advice on how to approach this case I have:

 

I need to process thousands of objects when a user clicks on a button and for each object I have to do one HTTP callout.

 

I know there is a limit of 10 callouts per request and 1 callout per batch execution.

Also there is a Maximum timeout for all callouts request.

 

I thought of two options:

 

  1. split my objects to groups of 10 using javascript and call my apex class for each group. It this case, in the extreme case there might be hundreds of such groups.
  2. use batch apex (I haven't done it before but I know there such an option) when each batch iteration will process 1 object. In this case thousands of iterations will be needed.

I'm not sure what is the best solution for my case and which will not hit the Limits.

 

Thanks

 

Kruvi

 

  • August 11, 2011
  • Like
  • 0

Hi,

I want to display a list of records processed out of a batch process on a Visuaforce page for user operation.

The Batch process returns a list of records but the list is not passed to the VF controller. The list shows empty when debugged in the Vf controller. I do  realise that the batch process runs asynchronously, but the requirement is really critical.

 

Please reply as soon as possible. Any pointers will be highly appreciated. Thanks in advance.

 

Regards,

Dev1234.

Hello ,

 

I have an approval process on Quote that locks the Quote record. While the record is locked/not approved, we want to restrict user to perform actions on Quote like Create PDF via Create PDF button on quote detail page.

 

On looking at Create PDF page, looks like it is making a function call and the URL of the page is not accessible to us which we could have used in custom vfp page and redirected to standard page reference if the record is approved else

show a popup.

 

Is it possible? I have researched quite a bit but did not find any clue. Its a critical requirement for us hence in case anybody has any idea please let me know

 

Thanks