• k_bentsen
  • NEWBIE
  • 459 Points
  • Member since 2013

  • Chatter
    Feed
  • 16
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 99
    Replies

I have an object MPIAccounts__c. On this object is text a field called Alert__c. The MPIAccounts__c follows a naming convention e.g 91234-0001, 91234-0002,91234-0003,76111-4556,76111-3120,76111-9458


I want to write a trigger such that if the text in Alert__c is changed on a record, I want to find all records in MPIAccounts__c that has the same prefix as this record and updated these with the same alert text.

e.g if the Alert__c on 91234-0001 is changed to 'This is an invoice', 91234-0002, 91234-0003 should also have it's Alert__c updated to 'This is an invoice'

 

similarly if the Alert__c on 76111-9458 is changed to 'This is the balance', 76111-4556,76111-3120 should also have it's Alert__c updated to 'This is the balance'.

 

Note: The MPIAccounts__c are not children of the same parent. So it's not like updating the children of the same same parent.

 

Any suggestions?

 

Thanks heaps!!

 

I need to compare Owner ID and Opportunity Team Member to a User ID in an Apex Class, if the ID's don't match they can't access the VF page. Any idea what this would like. Thanks in advance.

  • October 08, 2013
  • Like
  • 0

This trigger I would think would be really easy, but I'm struggling, and new to triggers. How would I write a trigger to set the standard price book on every opportunity? 

Hi Guys,

 

I have a scenario. Please someone help me ! 

I want a CUSTOM Created Date Time  Field in CASE OBJECT. 

This Field should have values based on Working Hours . 

Monday to Thursday - 8 AM to 4 PM 

Friday - 8 AM to 3 PM 

SATURDAY and SUNDAY - HOLIDAY 


FOR EXAMPLE :Case created by 4:01 PM on Monday, the value of Custom Created date field should be TUESDAY 8 AM .
If a Case is created by 3:01 PM on friDAY, the value of Custom field should be MONDAY 8 AM . 

Please help me with this scenario  !  



i created a picklist in visualforcepage with all the values of a mutilpicklist field from Course__c.

this is my code:

statusOptions = new List<SelectOption>();
        // Use DescribeFieldResult object to retrieve status field.
        Schema.DescribeFieldResult statusFieldDescription = Course__c.Year_Block__c.getDescribe();
        // For each picklist value, create a new select option
        for (Schema.Picklistentry picklistEntry: statusFieldDescription.getPicklistValues()) {
            statusOptions.add(new SelectOption( pickListEntry.getValue(),pickListEntry.getLabel()));
            // obtain and assign default value
            if (picklistEntry.defaultValue){
                course.Year_Block__c = pickListEntry.getValue();
            }  
        }     

 i want to show in the picklist only the multipicklist values of one record.

example:

all multipicklist field values= 1, 2, 3, 4, 5

one record: name=Test ; multipicklist values=1, 3, 5

how can i show only 1,3,5 in the created picklist in vfpage?

 

 

 

  • September 27, 2013
  • Like
  • 0

Hi All,

 

Need help please.  Im not a developer and so struggling with the followng issue: 

 

I have created a custom object which behaves in a similer manner as the "Quote" standard object and so i am able to produce Quotes in PDF by clicking on a custom button called "Create PDF".  However, when I produce the PDF file i would like to incremant the file name by '1' each time.  For example, when the "Create PDF" button is clicked the file name should be Quote_V1.pdf should then become Quote_V2.PDF,  then Quote_V3.PDF etc etc

 

Not sure how to do this.  Please see a part of my apex code below which is where I think i need to make my modification :

     Public PageReference SaveQuote()
    {
        try
        {
            String QId = ApexPages.currentPage().getParameters().get('id');
            dealerQuotation = [SELECT Id,Name FROM Dealer_Quotation__c WHERE Id = :QId]; 
            PageReference pdf = Page.Dealer_Quotation;
            pdf.getParameters().put('id',Qid);
            
            Attachment attach = new Attachment();
            Blob body;
            try
            {
                body = pdf.getContentAsPdf();
            }
            catch(Exception ex)
            {
                body = Blob.ValueOf('Error occured in page');
            }
            string name;
            if(dealerQuotation != null)
            {
                name = dealerQuotation.Name + '.pdf';
            }
            else
            {
                name = 'Quotation.pdf';
            }
            attach.body = body;
            attach.Name = name;
            attach.IsPrivate = false;
            attach.ParentId = QId;
            insert attach; 
            PageReference redirectPage = New PageReference('/' + QId);
            redirectPage.setRedirect(true);
            return redirectPage;    
        }
        catch(Exception ex)
        {
            ApexPages.Message exMsg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
            ApexPages.AddMessage(exMsg);
            return null;
        }    
       
    }

 

Any help would be greatly appreciated!

 

  • September 24, 2013
  • Like
  • 0

Have a custom "Account Contact Role" (ACR) table here, joiner obj between Accounts and Contacts.  Any time an ACR is added, if the Contact used is missing an Account, I'd like to update that contact record with the Account.

 

I know I'm sufferening from "lazy queryness" here - after 100 different tries and fails, I'm looking for some guidance down the right path - please help !

 

Best way to "bulk friendly" grab the existing Contact Account values?

 

trigger ACR on Account_Contact_Role__c (Before Insert) {

    Map<Account_Contact_Role__c, Contact> ACRtoContactMap = new Map<Account_Contact_Role__c, Contact>();

    for (Account_Contact_Role__c ACR : trigger.new) {
        If (ACR.Contact__r.Account == null) { // <== yes, I know...will always be null 
                                              // (please help me to fix!)
            Contact C = new Contact(Id=ACR.Contact__c);
            C.AccountId=ACR.Account__c;
            ACRtoContactMap.put(ACR, C);
        }
    } 
    if(!ACRtoContactMap.isEmpty()){
        update ACRtoContactMap.values();
    }
}

 

Thanks for any asisstance / guidance !

Hi,

 

I have a requirement that everytime a user changes ownership of a Lead, after 60 days that Lead needs to be re-evaluated. If after 60 days the Lead has not been converted, it needs to automatically be reassigned to the original owner (which there will be a field for).

 

Is the best way to handle this through TBWF or through apex scheduling? Sounds like Time Based Workflow due to the 100 class scheudling limit. Is there a similar limit on workflow?

Any other suggestions?

  • August 19, 2013
  • Like
  • 0

I am trying to use some code from this post. I am trying to write a trigger that allows for bulk processing of counting attachments associated to a record based on the record change(not addition of the attachment). Below is my code that compliles, but I get a runtime error "Apex trigger WasteProfileAttachmentCount caused an unexpected exception, contact your administrator: WasteProfileAttachmentCount: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0fa0000006j8IAAAY; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a0fa0000006j8IA) is currently in trigger WasteProfileAttachmentCount, therefore it cannot recursively update itself: []: Trigger.WasteProfileAttachmentCount: line 30, column 1"

 

I understand that I am not supposed to explicitly call update, on the same record. But how can I update in bulk?....below is the code.

 

trigger WasteProfileAttachmentCount on ProfileDocument__c (before update) {

    Set<Id> ids = new Set<Id>();
    ids.addAll(trigger.newMap.keySet());
    
    AggregateResult[] counts = [SELECT ParentId,count(id)attachments FROM Attachment WHERE ContentType = 'application/pdf' AND ParentId IN :ids GROUP BY ParentId];   
    
    List<ProfileDocument__c> toUpdate = new List<ProfileDocument__c>();
    
    for(AggregateResult ar : counts){
        ProfileDocument__c tempDocs = new ProfileDocument__c(Id=string.valueof(ar.get('ParentId')),Attachments__c=integer.valueof(ar.get('attachments')));
        toUpdate.add(tempDocs);
    }
    
    update toUpdate;

}

  • August 14, 2013
  • Like
  • 0

Hi

 

I have no Apex training but have managed to piece this trigger together with help from these boards! Now i have my trigger in place I need to update all my leads to use it. However I get the  System.LimitException: Too many SOQL queries: 101 error when mass-updating leads.

 

I understand the concept that I'm calling too many SOQL queiers. Anyone willing to help re-code this trigger to bring teh SOQL out of the for loop?

 

trigger updateCCLookupField on Lead (before insert, before update) {

List<Lead> leads = new List<Lead>();

  for (Lead l : Trigger.new)
  { 
  Try
  {
     Campaign_Codes__c AssociatedCC = [SELECT Id FROM Campaign_Codes__c WHERE CodeOnCC__c= :l.Campaign_Code__c];
    l.CC_Lookup__c = AssociatedCC.Id;
  }
  Catch(Exception e)
  {
  l.CC_Lookup__c = null;
  } 
  }
}

Hi,

 

I have the following helper class and I am instantiating it as such...  How can I sort on the Account Id?  I need to iterate through the helper clas records in order by account so that I can sum up any related opportunties.  It seems that SF has a limitation on an Aggregate query where I cannot include the account id since it is two paraents up from my Opportunity related object.  I tried all kinds of approaches so I was thinking that this helper class would allow me to iterate through and code for the possibility of multiple opps.

 

...

List<Enrollment_QueryBase.EnrollmentContractSummaryHelperClass> EnrollmentSummary {get; set;}

...

EnrollmentSummary = new List<Enrollment_QueryBase.EnrollmentContractSummaryHelperClass>();

 

for (....

 

    EnrollmentSummary.add(new Enrollment_QueryBase.EnrollmentContractSummaryHelperClass(q, AccountIdMap));

}

 

EnrollmentSummary.sort();  **** this line fails  -- I thought it would sort by the first field in my class!

...

...

 

I appreciate any help you can provide.

 

 

 

     public class EnrollmentContractSummaryHelperClass {
         {
             // Default just to prevent any possible null reference errors
             // really not needed if class is called correctly
             this.RptDt = '190001';            
         }
         public Id AcctId {get; set;}
         public Id OppId {get; set;}         
         public String RptDt {get; set;}
         public Double ContractSum {get; set;}

         public EnrollmentContractSummaryHelperClass ( AggregateResult q, Map<id, Id> AccountIds ) {
             id OppId = (Id)q.get('Opportunity__c');
             this.AcctId = AccountIds.get(OppId);
             this.OppId = OppId; 
             this.RptDt = (String)q.get('Rpt_Dt__c');                           
             this.ContractSum = (Double)q.get('expr0');          
         }        
         
     }      

 

Hi,

 

Actually I already have a trigger that copy some fields from Account to IMP__c. When I deactivate the Account trigger this trigger works fine. But when Account trigger is active it gives me the below error:

 

(This below Trigger is copying status from IMP__C to Account )

 

 

trigger updatefield on imp__c (after update) {
Map<String,imp__c > recordsimp = new Map<String,imp__c >();
List<account> accountToUpdate = new List<account>();

for(imp__c impRecord : trigger.new){
recordsimp.put(impRecord.rec_ID__c,impRecord);
}

accountToUpdate = [select id,Status__c,account_num__c from account where account_num__c IN: recordsimp.keyset()];
for(account accounts: accountToUpdate){
accounts.status__c = recordsimp.get(accounts.account_num__c).Status__c;
}
if(accountToUpdate.size() > 0){
update accountToUpdate;
}
}

 

 

 

 

 

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updatefield caused an unexpected exception, contact your administrator: updatefield: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 087Z00000008cAfIAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, insertfielddat: maximum trigger depth exceeded IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] IAccount trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf] IMP trigger event AfterUpdate for [a0SZ0000001cnpO] Account trigger event AfterUpdate for [087Z00000008cAf]: []: Trigger.updatefield: line 18, column 1

Hello All,

 

I have got a custom Object 'Customer Project' in the related list of an opportunity with the picklist field Status (Active, Inactive). Whenever a record on this object is inserted or updated wit status = Active-->a custom field 'Activate Customer Project' checkbox field on Opportunity must be set to True. 

Moreover, as soon as the Record with status= Active in inserted for custom object ''Customer Project'' , the other records with the Active status must become inactive for the opportunity i.e only one customer project can exist with an Active status for an opportunity.

I have written the following code(bulkified) which is working but any suggestions if there is a better way to do this :

(Note : I have used  If(Trigger.Isupdate && trigger.isAfter)  and used this List insted of string List<Id> setcp = new List<Id>();

for testing only)

Many Thanks!!

 ----------------------------

trigger updateOpportunityStatus on Customer_Project__c (after insert, after update) {
                List<opportunity> opps = new List<opportunity>();
                List<Id> setcp = new List<Id>();
                List<Customer_Project__c> cps = new List<Customer_Project__c>();
                List<Customer_Project__c> cpps = new List<Customer_Project__c>();              
                opportunity opp;  
    
    If(Trigger.Isinsert && trigger.isAfter){
     for(Customer_Project__c cp : trigger.new){
        If(cp.status__c=='Active' && setcp.size()==0 ){
            setcp.add(cp.Id);        
             opp = [Select Id, name,Active_Cust_Project__c from Opportunity where Id= :cp.Opportunity__c];
            
            If(opp != null){
               opp.Active_Cust_Project__c = True;
               opps.add(opp); }
               
            }
           cps = [select Id,status__c from Customer_Project__c where Opportunity__c=:opp.id];
           for(Customer_Project__c c:cps){
             //Using the List because there is no get or a similar method for set
             If(c.Id != setcp.get(0)){
             c.status__c = 'Inactive';
             cpps.add(c);}           
           }
       }
       
     update cpps;     
    }
    
    If(Trigger.Isupdate && trigger.isAfter){
     for(Customer_Project__c cp : trigger.new){
        If(cp.status__c=='Active' ){
            opp = [Select Id, name,Active_Cust_Project__c from Opportunity where Id= :cp.Opportunity__c];
            If(opp != null && opp.Active_Cust_Project__c != True){
               opp.Active_Cust_Project__c = True;
               opps.add(opp);             }
          }
         cps = [select Id,status__c from Customer_Project__c where Opportunity__c=:opp.id];
           for(Customer_Project__c c:cps){
             //Using the List because there is no get or a similar method for set
             If(c.Id != setcp.get(0)){
             c.status__c = 'Inactive';
             cpps.add(c);}           
           }

      }
    }
        

update opps;
        
        

     }

------------------------------------------------------------------------------------------------------------------------------------------

Hello all.

 

I'm working since a few time on apex and I develloped a trigger witch works well but My test class is a problem.

 

This is the error message :

 

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TR04Objectifcompte: execution of BeforeInsert
caused by: System.NullPointerException: Attempt to de-reference a null object
Trigger.TR04Objectifcompte: line 6, column 1: []

 

This is my trigger :

 

 

trigger TR04Objectifcompte on Account (before update, before insert) 
{

    for (Account a : trigger.new)
    {
    List<Objectifs_commerciaux_annuels__c> listobj = new List<Objectifs_commerciaux_annuels__c> ([select Id from Objectifs_commerciaux_annuels__c where Nom_du_VRP__r.Id =: a.OwnerId and recordtype.name = 'Objectifs liés au compte' and debut_periode__c <=: a.createddate.date() and fin_periode__c >=: a.createddate.date()]);
   
        if ( listobj.isEmpty() == false && (a.Nouveau_client__c == true || a.Commercialement_inactif__c == false) )
        {
            Objectifs_commerciaux_annuels__c obj = [select Id from Objectifs_commerciaux_annuels__c where Nom_du_VRP__r.Id =: a.OwnerId and recordtype.name = 'Objectifs liés au compte' and debut_periode__c <=: a.createddate.date() and fin_periode__c >=: a.createddate.date()]; 
            a.Objectifs_commerciaux_annuels__c = obj.id;
        }    
    
    }

}

 

This is my test class :

 

@isTest
public class ObjectifcompteTestClass{
  
  
    static testMethod void validateObjectifcompte() 
    {
    
// Creation of the user
Profile p = [select id from profile where name='Administrateur système'];
User u1 = new User(alias = 'standt2', email='standarduser@test12.com',
emailencodingkey='UTF-8', lastname='Testing1', languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id,firstname='Heather',
timezonesidkey='America/Los_Angeles', username='standarduser@test12.com');
insert u1;  

date mydate = date.today();

 

// Creation of the custom object "Objectifs_commerciaux_annuels__c"
String objRecordTypeId = [Select Id From RecordType Where SobjectType = 'Objectifs_commerciaux_annuels__c' and Name = 'Objectifs liés au compte'].Id;
Objectifs_commerciaux_annuels__c obj = new Objectifs_commerciaux_annuels__c(); 
obj.debut_periode__c = mydate.addDays(-15) ; 
obj.fin_periode__c = mydate.addDays(15);
obj.Nom_du_VRP__c = u1.Id;

obj.RecordTypeId = objRecordTypeId;
insert obj;

 

//Creation of the account witch respects conditions trigger
String strRecordTypeId1 = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'Client'].Id;
Account accnt = new Account();
accnt.Name = 'test account';
accnt.RecordTypeId  = strRecordTypeId1;
accnt.OwnerId = u1.Id;
accnt.Nouveau_client__c = true;
accnt.Commercialement_inactif__c = false;
insert accnt ;

 

// Test       

System.assertEquals(obj.Id, accnt.Objectifs_commerciaux_annuels__c );

}
    
}

 

Defintly I know I didn't follow Apex bestpratcices because I have a Soql in a loop in my Trigger.

However, I spend a long time to try to stay in bestpratices and work my test class but I did not succes, so it would be wonderfull if somebody could help me to finish my development.

 

We have a custom field on accounts called "Account Manager" ( Account_Manager__r.Id ).  This is the Client Services Account Manager who handles an account in addition to the Account Owner (account owner is usually the Sales Rep).

The custom fields called "Account Manager" is a Lookup to User object field and could be EITHER a USER, a QUEUE or it could also be BLANK.

 

I am creating a client services cases model (which is the record type '012R00000004tyC' you see below). 

 

I need to create a trigger that does the following:

IF THE ACCOUNT MANAGER CUSTOM FIELD ON ACCOUNT OBJECT IS NOT NULL > THEN ASSIGN CASE TO ACCOUNT MANAGER

IF THE ACCOUNT MANAGER CUSTOM FIELD ON ACCOUNT OBJECT IS NULL > THEN ASSIGN CASE TO THE CASE CREATOR

 

The trigger I have created below works ONLY if the Account Manager custom field IS NOT NULL.

It does NOT assign it to case creator if Account Manager custom field is blank... and it does not know what to do if Account Manager custom field field is blank.

(It throws the following error message if the Account Manager custom field is blank)

 

"Error: Invalid Data.

Review all error messages below to correct your data.

Apex trigger caseToAM caused an unexpected exception, contact your administrator: caseToAM: data changed by trigger for field Owner ID: owner cannot be blank"

 

Can anyone help me revamp this trigger?  Thank you!!

 

 

trigger caseToAM on Case (before insert) {

   Set<ID> accountIDs = new Set<ID>();

  

   for (Case c : trigger.new) {

      //build a set of unique account ids associated to the case(s) being created

      if (c.AccountId != null && c.RecordTypeId == '012R00000004tyC') {

         accountIDs.add(c.AccountId);

      }

     

   }

   //get the account manager id for all accounts affected

   List<Account> lAccounts = [SELECT Id, Name, Account_Manager__r.Id FROM Account WHERE Id in :accountIDs];

  

   //loop through the cases again and assign the account manager to the case

   for (Case c : trigger.new) {

      //change the owner to the account manager

          for (Account a : lAccounts) {

            if (c.AccountId == a.Id) {

               c.OwnerId = a.Account_Manager__r.Id;

               break;

          }

      }

     

   }  

  

}

trigger CalculateWaitTimeInHours on Case (before insert, before update) {
    if (Trigger.isInsert) {
        for (Case updatedCase:System.Trigger.new) {
            updatedCase.Last_Status_Change__c = System.now();
            updatedCase.Hours_In_Wait_Status__c = 0;
            updatedCase.Hours_Not_In_Wait_Status__c = 0;
        }
    } else {

        // get the wait statuses configured on system
        Set<String> waitStatusSet = new Set<String>();
        for (Wait_Status__c waitStatus:[Select Name From Wait_Status__c]) {
            waitStatusSet.add(waitStatus.Name);
        }

        // get the default business hours
        BusinessHours defaultHours = [select Id from BusinessHours where IsDefault=true];

        // get the closed statuses (because at the point of this trigger Case.IsClosed won't be set yet)
        Set<String> closedStatusSet = new Set<String>();
        for (CaseStatus status:[Select MasterLabel From CaseStatus where IsClosed=true]) {
            closedStatusSet.add(status.MasterLabel);
        }

        // for any case where the status is changed, recalc the business hours in the buckets
        for (Case updatedCase:System.Trigger.new) {
            Case oldCase = System.Trigger.oldMap.get(updatedCase.Id);

            if (oldCase.Status!=updatedCase.Status && updatedCase.Last_Status_Change__c!=null) {
                //OK, the status has changed
                if (!oldCase.IsClosed) {
                    //We only update the buckets for open cases

                    //On the off-chance that the business hours on the case are null, use the default ones instead
                    Id hoursToUse = updatedCase.BusinessHoursId!=null?updatedCase.BusinessHoursId:defaultHours.Id;

                    //The diff method comes back in milliseconds, so we divide by 3600000 to get hours.
                    Double timeSinceLastStatus = BusinessHours.diff(hoursToUse, updatedCase.Last_Status_Change__c, System.now())/3600000.0;
                    System.debug(timeSinceLastStatus);

                    //We decide which bucket to add it to based on whether it was in a stop status before
                    if (waitStatusSet.contains(oldCase.Status)) {
                        updatedCase.Hours_In_Wait_Status__c += timeSinceLastStatus;
                    } else {
                        updatedCase.Hours_Not_In_Wait_Status__c += timeSinceLastStatus;
                    }

                    System.debug(updatedCase.Status);
                    if (closedStatusSet.contains(updatedCase.Status)) {
                        System.debug(updatedCase.Hours_In_Wait_Status__c);
                        System.debug(updatedCase.Hours_Not_In_Wait_Status__c);
                        updatedCase.Case_Age_In_Business_Hours__c = updatedCase.Hours_In_Wait_Status__c + updatedCase.Hours_Not_In_Wait_Status__c;
                    }
                }

                updatedCase.Last_Status_Change__c = System.now();
            }
        }
    }
}

Is it possible to access data that has been loaded into an instance of a class once it has been instatiated, from outside the class? I have a class that pulls some data from the database, puts it into a wrapper class, sorts it, and stores into a map. From a separate class, I want to be able to access the data from the map using a key value that is an instance variable in said class. I imagine this is a programming methodology that isn't exclusive to Apex, but is something like this possible?

 

A static method won't work because obviously I can't access instance data, and so I would have to replicate the data polling, wrapping, sorting and storing behavior within it, which I want to avoid. I also tried extending the class that wants to access the data from the initial class, but that doesn't work because when an instance of the second class is created, the first class is also instantiated again, which would be redudant. 

 

Definitely would appreciate some insight into this. Let me know if this doesn't make sense and/or want to know the use case behind this.

 

Thanks

Is it possible to check global organization settings via API? More specifically, can we check if the "Disallow HTML documents and attachments" is enabled or not? If so, how do we retrieve it?

Hello,

Given an object ID is there a way to get its fields info without using SOQL? See example below:

 

I have an aid = accountID given below

 

instead of writing

select id, parentId, name, Type from Account where Id =: aid

 

can I write something like below

 

string sname;

string stype;

 

sname = aid.name;

stype = aid.type;

 

basically it is similar to below statements and it works when I write a trigger like this one below.

Case CaseUpdated:trigger.new

GroupNo = CaseUpdated.Group__c;

 

Please advise

Paul

 

  • October 17, 2013
  • Like
  • 0

 

Does anyone know a good way to prevent users from taking ownership of records from a queue when they reach a certain record count?

 

For example, a user is allowed to pull leads from the queue, but once they own 2,500 leads, they should be unable to take more.

 

I'm thinking I could create two fields on the user object:

  • User.Max_Lead_Count (Number)
  • User.Current_Lead_Count (Number)

And then create a validation rule preventing ownership when the current lead count is equal to the max lead count.

 

My question is what kind of apex should I write to populate a lead count field on the user object?

  • October 15, 2013
  • Like
  • 0

I have an object MPIAccounts__c. On this object is text a field called Alert__c. The MPIAccounts__c follows a naming convention e.g 91234-0001, 91234-0002,91234-0003,76111-4556,76111-3120,76111-9458


I want to write a trigger such that if the text in Alert__c is changed on a record, I want to find all records in MPIAccounts__c that has the same prefix as this record and updated these with the same alert text.

e.g if the Alert__c on 91234-0001 is changed to 'This is an invoice', 91234-0002, 91234-0003 should also have it's Alert__c updated to 'This is an invoice'

 

similarly if the Alert__c on 76111-9458 is changed to 'This is the balance', 76111-4556,76111-3120 should also have it's Alert__c updated to 'This is the balance'.

 

Note: The MPIAccounts__c are not children of the same parent. So it's not like updating the children of the same same parent.

 

Any suggestions?

 

Thanks heaps!!

 

I need to compare Owner ID and Opportunity Team Member to a User ID in an Apex Class, if the ID's don't match they can't access the VF page. Any idea what this would like. Thanks in advance.

  • October 08, 2013
  • Like
  • 0

This has been working in production for around a year and suddenly it stopped working over the weekend. 

 

below is the initialization section of the OpportunityControllerExtension

followed by the debugging log showing the error.

I've highlighted the offending line of code in RED.

 

This same code worked in Prod up until this weekend, and the same code also works perfectly in Sandbox. 

 

I have users who are up in arms, so any help would be appreciated.

Thanks,

Mike

 

 

public with sharing class OpportunityControllerExtension {

   private final Opportunity opp;
   private final Opportunity currentOpportunity;
   private final Account billingAccount;
   private final Account agency;
   
   private aaWSDLBeans.CampaignInfo[] campaignInfo;
   private List<OpportunitySplit> splitList;
   private List<OpportunityPartner> agencyList;
   private List<Revenue_Forecast__c> newRevenueForecasts;
   public  boolean debug;
   
   public OpportunityControllerExtension(ApexPages.StandardController stdController) {
      currentOpportunity = (Opportunity)stdController.getRecord();
      debug = false;
      this.opp = [
         SELECT
              o.StageName
            , o.Name
            , o.Estimated_Revenue_Start_Date__c
            , o.Estimated_Revenue_End_Date__c
            , o.campaign_total__c
            , o.OwnerId
            , o.AccountId
            , o.AutoIO__c
            , o.I_O__c
            , o.PO__c
            , o.account.type
            , o.account.Category__c
            , o.account.sub_category__c
            , o.billing_io_key__c
            , o.account.platform_id__c
            , o.account.agency_name__r.id
            , o.account.agency_name__r.name
            , o.account.parent.name
            , o.account.name 
            , o.account.owner.name 
            , o.account.Primary_Campaign_Manager__c 
            , o.account.owner.email 
            , o.account.BillingStreet 
            , o.account.CS_Login_First_Name__c 
            , o.account.BillingCity 
            , o.account.CS_Login_Last_Name__c  
            , o.account.BillingState 
            , o.account.Website 
            , o.account.BillingPostalCode 
            , o.account.Account_Email__c 
            , o.account.BillingCountry       
            , o.account.Phone       
             ,   (SELECT Month__c, Split_Owner__r.Name, Revenue__c, Split__c, Split_Revenue__c 
                    FROM Revenue_Forecasts__r order by Month__c, Split_Owner__r.Name)
         FROM Opportunity o
         WHERE o.id = :currentOpportunity.id];

      /*this.billingAccount = currentOpportunity.account;*/
      this.billingAccount = opp.account;
      this.agency = opp.account.agency_name__r;           
  
      this.splitList = [
         Select o.SplitPercentage, o.SplitOwnerId, o.SplitAmount
         From OpportunitySplit o
         Where o.OpportunityId = :currentOpportunity.id];
         
      if (splitList.isEmpty()) {
         splitList = new List<OpportunitySplit>();
         splitList.add(new OpportunitySplit(OpportunityId = opp.id, 
                           SplitOwnerId = opp.OwnerId, SplitPercentage = 100));
      }
      calcNewRevenueForecasts();
   }

12:01:11.275 (275088000)|SOQL_EXECUTE_BEGIN|[17]|Aggregations:1|select o.StageName, o.Name, o.Estimated_Revenue_Start_Date__c, o.Estimated_Revenue_End_Date__c, o.campaign_total__c, o.OwnerId, o.AccountId, o.AutoIO__c, o.I_O__c, o.PO__c, o.account.type, o.account.Category__c, o.account.sub_category__c, o.account.platform_id__c, o.account.agency_name__r.id, o.account.agency_name__r.name, o.account.parent.name, o.account.name, o.account.owner.name, o.account.owner.email, o.account.Primary_Campaign_Manager__c, o.account.BillingStreet, o.account.CS_Login_First_Name__c, o.account.BillingCity, o.account.CS_Login_Last_Name__c, o.account.BillingState, o.account.Website, o.account.BillingPostalCode, o.account.Account_Email__c, o.account.BillingCountry, o.account.Phone, o.billing_io_key__c, (select Month__c, Split_Owner__r.Name, Revenue__c, Split__c, Split_Revenue__c from Revenue_Forecasts__r order by Month__c, Split_Owner__r.Name) from Opportunity o where o.id = :tmpVar1
12:01:11.330 (330646000)|SOQL_EXECUTE_END|[17]|Rows:1
12:01:11.331 (331377000)|SOQL_EXECUTE_BEGIN|[60]|Aggregations:0|select o.SplitPercentage, o.SplitOwnerId, o.SplitAmount from OpportunitySplit o where o.OpportunityId = :tmpVar1
12:01:11.384 (384942000)|EXCEPTION_THROWN|[60]|System.QueryException: null
12:01:11.385 (385075000)|SYSTEM_MODE_EXIT|false
12:01:11.385 (385245000)|CODE_UNIT_FINISHED|OpportunityControllerExtension <init>

I am attempting to test this code. I need to set up the controller and set the parameters.
CONTROLLER.

The visualForce page has a standard controller of contact

Public Class myClass{
 public ApexPages.standardController controller {get; set;}
 public string pid {get; set;}

//CONSTRUCTOR
public myClass(ApexPages.StandardController controller){
 this.controller = controller;
 pId = ApexPages.CurrentPage().getparameters().get('id');
}

 

TEST CLASS

@isTest
public class testMyClass{

static testMethod void myTest(){
 PageReference pageRef = Page.myPage;
 Test.setCurrentPageReference(pageRef);

//create contact
 Contact cont = new Contact(name ='bob');
 insert cont;

 ApexPages.CurrentPage().getparameters().put('pid', cont[0].id);
 ApexPages.StandardController sc = new     ApexPages.standardController(cont[0]);
ApexPages.currentPage().getParameters().put(?); myClass sic = new myClass(sc);
system.assertQuals('something', here); } }

 

  • October 04, 2013
  • Like
  • 0

This trigger I would think would be really easy, but I'm struggling, and new to triggers. How would I write a trigger to set the standard price book on every opportunity? 

I have a problem with my trigger which concerns resolution time ( it includes time from open case = initial response time to when a case is closed = resolution time), but it won't  re-calculate the resolution minutes if the response time has been set before and I'll try to change the date/time again. How should I change my code?


Here's my trigger:

´trigger CaseResolutionMinutesTrigger on Case (before update) {
    
    if (Trigger.isUpdate) {
        
        for (Case updatedCase:System.Trigger.new) {
            System.Debug('CaseResolutionMinutesTrigger: CASE ID: ' + updatedCase.Id);           
                        
            RecordType recordType = [select Id, Name from RecordType where SObjectType = 'Case' and Name = 'Support' LIMIT 1];
            
            System.Debug('CaseResolutionMinutesTrigger: FETCHED RECORD TYPE: ' + recordType.Id );
            System.Debug('CaseResolutionMinutesTrigger: RECORD TYPE IN CASE: ' + updatedCase.RecordType.Id );
            
            // Get old Case data. We are also only interested in Support Cases.
            if (System.Trigger.oldMap.get(updatedCase.Id) != null /*&& updatedCase.RecordType == recordType*/ ) {
            
                Case oldCase = System.Trigger.oldMap.get(updatedCase.Id);            
                System.Debug('CaseResolutionMinutesTrigger: OLD STATUS: ' + oldCase.Status);
                System.Debug('CaseResolutionMinutesTrigger: NEW STATUS: ' + updatedCase.Status);
                  if (updatedCase.Resolution_time__c != null && updatedCase.Resolution_minutes__c == null && updatedCase.Related_Setup__c != null ) {
                    
                    // Related Setup
                    Setup__c relatedSetup = [select Id, Contract__c, Cost_Center__c, Name, Service_Availability__c from Setup__c where Id =: updatedCase.Related_Setup__c];
                    System.Debug('CaseResolutionMinutesTrigger: Related Setup: ' + relatedSetup.Name);
                    
                    // Get BusinessHours from Setup -> Contract-> Contract(Agreement) -> Business Hours
                    ServiceAvailability saHelper = new ServiceAvailability();
                    Id hoursToUse = saHelper.GetHoursToUse(updatedCase, relatedSetup);
                    if(hoursToUse != null ) {                                       
                        System.debug('CaseResolutionMinutesTrigger: HOURS TO USE: ' + hoursToUse);
                                        
                     //Double resolutionMinutes = Initial_Response__c.GetTime() - Resolution_time__c.GetTime();
                     Double resolutionMinutes = BusinessHours.diff(hoursToUse, updatedCase.Initial_Response__c, System.now());
                     Double rmMins = resolutionMinutes / 60000.0;
                     Double rmHrs = resolutionMinutes / 60000.0 / 60;
                     Double rmDays = resolutionMinutes / 60000.0 / 60 / 24;
                        
                     System.Debug('CaseResolutionMinutesTrigger: RESOLUTION MINUTES (ms): ' + resolutionMinutes);
                     System.Debug('CaseResolutionMinutesTrigger: RESOLUTION MINUTES (mins): ' + rmMins);
                     System.Debug('CaseResolutionMinutesTrigger: RESOLUTION MINUTES (hrs): ' + rmHrs);
                     System.Debug('CaseResolutionMinutesTrigger: RESOLUTION MINUTES (days): ' + rmDays);                     
                        
                     updatedCase.Resolution_minutes__c = rmMins;
                   
                     // update updatedCase;
                   } else { 
                        System.Debug('SETUP NOT FOUND: ' + updatedCase.Related_Setup__c);
                   }
                }
            }
        }
    }
}

  • September 30, 2013
  • Like
  • 0