• Jake Gmerek
  • SMARTIE
  • 1475 Points
  • Member since 2011

  • Chatter
    Feed
  • 56
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 423
    Replies

I am troubleshooting System.LimitException: Too many SOQL queries: 101 errors in test classes. Is there a way that I can place i.e. system.debug('<current # on SOQL queries>'); to see where in my code that the SOQL queries jump in debug logs? Is there such a way to reference this global SOQL query count in my apex code?

 

Thank you.

Hi, I'm trying to build a trigger that acts to update a picklist with the value of another picklist (located on the same record).

 

The custom object this trigger is on needs to be restricted but we also need to let all users create and edit records here to a degree, so we have a system where they can "request an update" to the record using identical fields to the actual fields/the fields used in a report. They can fill in one picklist, but the "actual" picklist field should remain as-is until a user with additional permissions changes a checkbox from false to true. I've built everything else we need for this using workflows, but I've learned with picklists you can only go up/down the list or set it to a specific value.

 

I tried changing the picklist to a checkbox as we only have 2 possible values, but ran into the same issue where I can only set it to true or false, not the value of another checkbox. We may also add a third option so I'd like to keep this field as a picklist.

 

I have a trigger and test class written but I get an error when running my test:

System.DmlException: Update failed. First exception on row 0 with id a0DQ0000003vFohMAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CRHUpdateWorkStatus: execution of BeforeUpdate


caused by: System.DmlException: Update failed. First exception on row 0 with id a0DQ0000003vFohMAE; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a0DQ0000003vFoh) is currently in trigger CRHUpdateWorkStatus, therefore it cannot recursively update itself:

 

Here is my trigger:

/* This trigger works based on if the "Request Approved" checkbox is checked.
If it is, it will update "Full-Time or Part-Time?" with the value in
"(Y) Full-Time or Part-Time?", provided that field is also not blank. */

trigger CRHUpdateWorkStatus on Church_Role_History__c (before update) {
     List<Church_Role_History__c> crhNEW = new List<Church_Role_History__c>();
     for(Church_Role_History__c crhOLD: Trigger.New)
     if (crhOLD.Request_Approved__c == True && crhOLD.Y_Full_Time_or_Part_Time__c != '')
     {
          crhNEW.add(new Church_Role_History__c (
          
          // Id
          id = crhOLD.Id,
          
          // Status
          Full_Time_or_Part_Time__c = crhOLD.Y_Full_Time_or_Part_Time__c
          ));
     }
     update crhNEW;
}

 

 

My test class:

@isTest
     private class TESTCRHUpdateWorkStatus {
          public static testmethod void MyTest() {
     
     {
          
          //Create a Contact for this test class.
          Contact c = new Contact();
          c.FirstName = 'Stephanie';
          c.LastName = 'Arce';
          insert c;
          
          //Create an Account for this test class.
          Account a = new Account();
          a.Name = 'Test Church';
          insert a;
     
          //insert a Church Role History record related to the Contact and Account.
          Church_Role_History__c crh = new Church_Role_History__c ();
          crh.Church__c = a.Id;
          crh.Person__c = c.Id;
          crh.Y_Full_Time_or_Part_Time__c = 'Full-Time';
          crh.Church_Position_Title__c = 'Administrative Assistant';
          crh.Request_Approved__c = True;
          insert crh;
          
          //Update the same Church Role History record so Request Approved = True.
          Church_Role_History__c crhu = [select Id from Church_Role_History__c where Id = :crh.Id];
          crhu.Request_Approved__c = True;
          update crhu;
          //See if "(Y) Full-Time or Part-Time?" value was copied to "Full-Time or Part-Time?"
          Church_Role_History__c crhq = [select Id from Church_Role_History__c where Id = :crhu.Id];
          system.assertEquals(crhq.Full_Time_or_Part_Time__c, 'Full-Time');
     }
   }
 }

 

Can someone explain the error message to me and what I have wrong in my trigger? Thank you so much for any help!

Hi There, I created a trigger to execute on a lead when the Lead Status value is changed.  I am able to save the code below, however the task is not being created.  I hardcoded the ownerID for the task for this test.   If anyone knows what I am missing this would be greatly appreciated!

 

trigger createLeadActivity on Lead (after update) { 

    //make a set to hold LeadIds that we need
    Set<Id> leadIds = new Set<Id>();
  
   
    for(Lead l : trigger.new)
        {
        //check to see if our field has been changed
        if(l.status != trigger.oldMap.get(l.Id).Status){
            
            leadIds.add(l.Id);
            
        }

       }
    
    if(!leadIds.isEmpty()){
        
       
        
        List<Lead> leadList = 
            [SELECT Id,Status
            FROM Lead
            WHERE Status = '4 - SAL Engaged' AND Id IN :leadIds ];
            
        
        
        
        
        for(Lead lead: trigger.new){
       
       
        
        
       
        Task newTask = new Task(Subject='LeadPassed',
Status='Not Started',Priority='Normal', OwnerId ='005E0000000QD4F');



        }
       
    }


}

 

Hello all,

 

My first foray into writing a trigger (which I think is what I need to do based on the details below).  I've found a ton of info online which I think has gotten me close, but I'm at a roadblock.


What I'm trying to do is increment a field Number_of_Injuries on a custom object Course by 1 every time a Case is saved where Case.Incident_Type (a custom field on case) is "Injury."

 

The code below returns a result: Error:Apex trigger updateInjuryCount caused an unexpected exception, contact your administrator: updateInjuryCount: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.updateInjuryCount:

 

I would truly appreciate any guidance experts may have on this.

 

trigger updateInjuryCount on Case (after update, after insert)
{
    
    Integer i = 0;
    
    Set<ID> courseIDs = new Set<ID>(); //variable to store the course id that is used in the case lookup field
    
    Map<ID, integer> id2Injury = new Map<ID, integer>();
    
    for (Case o : Trigger.new) //define case as variable o, when the trigger is first fired
    {
        if ((Trigger.isInsert && o.Incident_Type__c == 'Injury') ||
            Trigger.old[i].Incident_Type__c != o.Incident_Type__c)
        {
            courseIDs.add(o.Course__c); //get the course id from the lookup field on case object
            
            id2Injury.put(o.Course__c, 1); //creates array with course id and integer to increment
        }     
        i++;    
    }
    
    List<Course__c> courses = [select id, Number_of_Injuries__c from Course__c where id in :courseIDs]; //finds the relevant course record
    
    for (Course__c c : courses)
    {
        c.Number_of_Injuries__c++;
    }
    
    update courses;
}

Hi, all,

I'm just starting to tinker around with the development side of SFDC and I've created a trigger that works fine, but I can't seem to ever get my test class to assert true. I've included both below. Any assistance you can provide is greatly appreciated (even in my trigger or best practices). Forgive my stray comments inline.

Trigger:

trigger populateOpptyChildRecords on Opportunity (before update) {
for( Opportunity parent: Trigger.new)
{
 
List<Ad_Campaign__c> children = [ SELECT Id, Opportunity_Id__c, Opportunity_OwnerID__c from 
Ad_Campaign__c where Opportunity__c = :parent.Id];
 
List<Ad_Campaign__c> childrenToUpdate = new List<Ad_Campaign__c>();
 
for(Ad_Campaign__c thischild: children )
{
   if( thischild.Opportunity_OwnerID__c !=  parent.OwnerID)
   {
 //      thischild.Opportunity_OwnerId__c =  parent.OwnerId;
       thischild.Parent_Updated__c = TRUE;
       thischild.Parent_Updated__c = FALSE;
      childrenToUpdate.add(thischild);
   }
}
 
//if( !childrenToUpdate.isEmpty)
//{
   update childrenToUpdate;
//}
 
}
}

 



/=========================================

Test Class:

@isTest
 
private class testPopulateOpptyChildRecords{
static testMethod void runPositiveTestCases(){
        //Set up new account, related oppty, and two users
        
        Account acct = new Account(Name='test account');
            insert acct;
        Account a=[SELECT Id from Account WHERE Name = 'test account' LIMIT 1];
        Opportunity o = new Opportunity(Name='test opportunity', AccountID = acct.Id, StageName='Prospecting', CloseDate=system.Today());
        insert o;
        Ad_Campaign__c ac1 = new Ad_Campaign__c(Opportunity__c=o.Id);
        insert ac1;
        Profile p=[SELECT id FROM Profile p WHERE p.name = 'System Administrator'];
        User u1=new User(
            FirstName='Test', 
            LastName='User', 
            Username='test@test.com.damp', 
            Email='test@test.com', 
            Alias='test1', 
            CommunityNickname='test1', 
            TimeZoneSidKey='America/Los_Angeles', 
            LocaleSidKey='en_US', 
            EmailEncodingKey='ISO-8859-1', 
            ProfileId=p.id, 
                LanguageLocaleKey='en_US');
        insert u1;
    // Get the value for Owner from the Oppty
        Opportunity o1=[SELECT Id, OwnerID from Opportunity WHERE Name = 'test opportunity' LIMIT 1];
        Ad_Campaign__c ac2 =[SELECT Id, Opportunity_OwnerID__c from Ad_Campaign__c WHERE Opportunity__c IN (SELECT Id from Opportunity WHERE Name = 'test opportunity')];
        User u2=[SELECT Id, Name FROM User WHERE Name = 'Test User'];
    //Check to see if the Owner1 field is filled out on the ad campaign
    //System.Assert(ac1.Opportunity_Owner1__c != ''); -- nevermind
    //Update a field on the opportunity to start the trigger
        u2.Id=o1.OwnerId;
        System.Assert(ac1.Opportunity_OwnerID__c==o1.OwnerId);
    }
}

 


//Thanks again

Not an expert with Apex, but I was assuming this should work.

 

My code is creating a record with values received thru a webservice call, I am trying to set the RecordType using one of the values I received. Code for setting recordtype looks something like this:

 

Map<String,RecordType> acctRecordTypes = new Map<String,RecordType>([select NAME from RecordType where SOBJECTTYPE='Account']);

...............................................................

if(nodeName=='AccountType')   acctTypeCode=node.getText();

 .....................................................
RecordTypeId=acctRecordTypes.get(acctTypeCode).ID,

 

 

 

Fails on the last line and gives an error message: "System.NullPointerException: Attempt to de-reference a null object"

 

Was able to isolate the problem to this line using debug as well, hardcoding the RecordTypeID value gives no errors.

 

 

Thanks for taking the time to read and any help you offer.

 


 

I'm trying to find a way to have several fields populate automatically when a new record is entered.  Most of the fields values will come from SOQL Selects.

The trigger should only execute the first time the record is created.  The records will be created from the standard 'New' button, but a custom button can also be used.

 

Thanks for any examples or links

Hi, For efficiency I need to gather all with a single SOQL; however can someone point me how to achive a lookup type scenario with a single SOQL; Some snippet I have:

 

for(Contact cnt_old:oldContacts) { List cnt = [select email from Contact where id =: cnt_old.masterrecordid];

 

I need to use masterrecordid due to delete happens from a merge action and get other cols of the winning records.

 

After getting winning records/cols I then need to relate to oldContacts....both queries are on same contact obj

So, now I have select within For loop, which I need to avoid, thanks!

Hello,

 

I have the next error in VF

 

Attempt to de-reference a null object

Error is in expression '{!iniQuestionsResponsesLB}' in component <apex:page> in page deal_questions_and_responses_lb

An unexpected error has occurred. Your development organization has been notified.     

 

My class is:

 

/**
* Victor
 */
@isTest
public without sharing class QuestionsResponsesLB {
    
    List<Deal_Screening_Question_Response__c> questions;
    List<Deal_Screening_Questions__c> origiQuestions;
    List<Deal_Screening_Question_Response__c> conRespuestas;
    public String sId {get; set;}
    public Boolean inEdit {get; set;}
    
    /*
    *
    */
    public List<Deal_Screening_Question_Response__c> getQuestions(){
        PageReference p = ApexPages.currentPage();
        sId = p.getParameters().get('id');
        
        Opportunity myOppo = [SELECT Deal_Category__c FROM Opportunity WHERE Id = :sId];
        
        questions = [SELECT Category__c,Concept__c,Country__c,language__c,Name,Publish__c,Question_Number__c,Question__c,Sub_Category_2__c,Sub_Category__c FROM Deal_Screening_Question_Response__c WHERE Category__c = :myOppo.Deal_Category__c ORDER BY Question_Number__c];
        return questions;
    }
    
    /*
    *
    */
    public void iniQuestionsResponsesLB(){
        PageReference p = ApexPages.currentPage();
        sId = p.getParameters().get('id');
        
        conRespuestas = [SELECT Category__c,Concept__c,Country__c,language__c,Name,Publish__c,Question_Number__c,Question__c,Sub_Category_2__c,Sub_Category__c FROM Deal_Screening_Question_Response__c WHERE Opportunity__c = :sId];
        if(questions.size() > 0){ //Tenemos respuestas por lo que las mostramos
        	inEdit = true;
        }
        else{//Caso en el que no tenemos respuestas
        	String cat;
        	String idioma;
        	
        	Opportunity myOppo = [SELECT Deal_Category__c FROM Opportunity WHERE Id = :sId];
        	origiQuestions = [SELECT Category__c,Concept__c,Country__c,language__c,LB__c,Name,Publish__c,Question_Number__c,Question_Type__c,Question__c,Sub_Category_2__c,Sub_Category__c FROM Deal_Screening_Questions__c WHERE Category__c = :myOppo.Deal_Category__c ORDER BY Question_Number__c];
        	
        	if(origiQuestions.size() > 0){//Si para esta categoria tenemos preguntas entonces las gruardamos en la tabla preguntas/respuestas
        		//Creamos una lista de preguntas/respuestas
        		List<Deal_Screening_Question_Response__c> forInsert = new List<Deal_Screening_Question_Response__c>();
        		//Por cada una de las preguntas crearemos su pregunta respuesta
        		for(Deal_Screening_Questions__c q : origiQuestions){
        			forInsert.add(new Deal_Screening_Question_Response__c(Question_Number__c = q.Question_Number__c,Category__c = q.Category__c,Sub_Category__c = q.Sub_Category__c,Question__c = q.Question__c,Opportunity__c = sId,language__c = q.language__c,Publish__c = q.Publish__c));
        			if(forInsert.size() > 0){
        				insert forInsert;
        			}
        		}
        	}
        	else{
        		inEdit = false;
        	}
        }
    }
    
    
    /*
    *
    */
    public PageReference CloseUp(){
        PageReference pr = New PageReference('/'+ sId);
        pr.setRedirect(true);
        return pr;
    }
}

 My page is

 

<apex:page controller="QuestionsResponsesLB" tabstyle="Opportunity" action="{!iniQuestionsResponsesLB}" showHeader="true" sidebar="true">
    <apex:pageBlock title="Questions">
    <apex:form >
        <apex:pageBlockSection columns="1" rendered="true">
            <apex:pageblocktable value="{!Questions}" var="question" id="list">
                <apex:column headerValue="Preguntillas">
                    <apex:outputText value="{!question.Question__c}"/>
                </apex:column>
                <apex:column headerValue="Respuestas">
                    <apex:inputText size="100"/>
                </apex:column>
            </apex:pageblocktable>
        </apex:pageBlockSection>
        <apex:pageBlockSection >
            <apex:commandButton value="Cancel" action="{!closeUp}"/>
        </apex:pageBlockSection>
    </apex:form>
    </apex:pageBlock>
</apex:page>

  When I remove action={!iniQuestionsResponsesLB} the page work well

 

Whats is happening ? Any idea of the error ?

 

Thanks for all

 

In an Apex batch process, I am s creating record of a new RecordType that is a consolidation of 2 existing RecordTypes of  each Account record.

 

It is functioning properly EXCEPT it's not getting the Related Lists.  I presume that it would require specific code to address it but,  for instance,  to populate the Related Contacts, I used:

 

Note - The item.Accounts is the source record List which includes Account.Contacts in the query,  myAccount is the new record being created.

 

myAccount.Contacts = item.Account.Contacts;     I got the error  -  field is not writable.

 

I tried     myAccount.Contacts.Id = 'xx';   -  ( xx is just to test the reference) which resulted in  the error  -   Invalid foreign key relationship.

 

Any ideas on how this would be populated?

 

 

Here is the code I have in the custom button in our QA Sandbox; the button on the case object is called “New CSC Case”.

 

/500/e?retURL=%2F{!Case.ParentId}&def_parent_id={!Case.Id}&{!Case.Parent_Case_Account_ID__c}&def_account_id={!Account.Id}&{!Case.Device__c}&def_device_id={!ISPICKVAL(Case.Device__c,'')}&RecordType=012A0000000teDM&ent=Case

 

The button is on the page layout for a case and when clicked most of the functionality works correctly: a new child case is created of a different record type, the parent case number is filled in and the correct account value is filled in on the child case based on the value from the parent case.  The section o fthe button formula which isn't working is the part about &{!Case.Device__c}&def_device_id={!ISPICKVAL(Case.Device__c,'')}

 

I'm trying to take the single picklist value for "device" from the parent case and pass it to the new child case in the button.  In the URL for the new child case, I see that the picklist value was copied from the parent case, but it doesn't pass it to the child.  The URL produced when the button is clicked is below.

 

https://cs11.salesforce.com/500/e?retURL=%2F&def_parent_id=500Z0000002PoFe&def_account_id=001A0000002dpzb&2.5&def_device_id=false&RecordType=012A0000000teDM&ent=Case

 

You can see that the value of "2.5" is in the URL which is correct, but that value doesn't pass to the picklist for the new child case.

 

Can anyone please suggest what's wrong with the part of the button formula &{!Case.Device__c}&def_device_id={!ISPICKVAL(Case.Device__c,'')} ?

 

Thanks to all for any ideas!  Happy New Year!

 

Hi All,

 

I am adding a custom picklist field in case object, which has the values "YES" and "NO". My requirement is when ever the field is changed to "YES" then the change date should be displayed to next to that..... Do I have to write the trigger for this?

Hi Team,

 

I have a filed called price in three objectsa,b and c.

 

My requirement is can we create formula filed in c object by getting the values of price values from a and b.

 

If yes please tell me the syntax..

 

 

 

I have  done the same requirement from workflow but getting few defects with that.

  • November 26, 2012
  • Like
  • 0

I've just created my first trigger which fires on opportunities and checks to see if an opportunity was paid for using a gift certificate custom object that we created and if so then goes and debits the apporpriate amount from that gift certificate. Part of this involves a SOQL to create a list of all the gift certificates that currently have a balance greater than 0. As their is a governor limit on the amount of SOQL queries you can do, and as there is such an emphasis on "bulkification" of your code, I initally placed this SOQL query at the beginning of the trigger, outside the for loop that acts on every record so as not to fire mulitple times when bulk uploading opportunities. That being said, I don't plan on ever bulk uploading opportunities. 


Here's the question. Given that most opportunities won't be paid for with a gift certificate and the fact that I have no intention of ever bulk uploading opportunities, would it make more sense to forego the bulkification best practice and only perform the SOQL query after determining whether or not the query needed to be made? 

When I try to insert/update a new Client_CC__c record, I get a really strange error. The parent Client_Form__c record that is trying to be updated has no null value in either field, and the Sent_Date__c field for the child Client_CC__c record is also not null. Any ideas on how to resolve this?

 

I'm getting the following error:

 

System.NullPointerException: Attempt to de-reference a null object: Trigger.ClientFormUpdate12: line 20, column 1

 

Line 20 begins the following if statement

if(updateform.Most_Recent_Email__c <= ccs.Sent_Date__c){
					updateform.Most_Recent_Email__c = ccs.Sent_Date__c;
					update updateForms;				
				}

 

Here's the entire trigger

trigger ClientFormUpdate12 on Client_CC__c (before insert, before update) {
		
	List<ID> FormIDs = new List<ID>();
	List<Client_Form__c> updateForms = new List<Client_Form__c>();
		For( Client_CC__c ccs : Trigger.New){
 		FormIDs.add(ccs.Id);
			}
			
	Map<ID, Client_Form__c> FormUpdateMap = new Map<ID, Client_Form__c>();
		for(Client_Form__c cfc : [Select ID , Most_Recent_Email__c, Most_Recent_Good_Lead__c 
							FROM Client_Form__c WHERE ID in:FormIDs])
		{
 			FormUpdateMap.put(cfc.ID, cfc);
		}
	
		for (Client_CC__c ccs : trigger.new){
		
			Client_Form__c updateform = FormUpdateMap.get(ccs.Id);
			if (ccs.Form__c != null){
				if(updateform.Most_Recent_Email__c <= ccs.Sent_Date__c){
					updateform.Most_Recent_Email__c = ccs.Sent_Date__c;
					update updateForms;				
				}
			}			
			
			if (ccs.Good_Lead__c = true){
				if(updateform.Most_Recent_Good_Lead__c <= ccs.Sent_Date__c){
					updateform.Most_Recent_Good_Lead__c = ccs.Sent_Date__c;
					update updateForms;					 
			}
		}
	}
}

 

  • May 24, 2012
  • Like
  • 0

Heres the scoop....  I need to have a field autopopulate with data that will be coming from two different objects, either one or the other based on record type.

 

Here is what I have, but the '||', or "OR" is not working as I had hoped.  Any suggestions??

 

IF( RecordTypeId ='012M00000008bcI', Chaney_Account__r.Customer_Number__c,"") ||
IF(RecordTypeId ='012M00000008bcD',PW_Account__r.BPCS_Customer_Number__c,"")

I need some help taking this SOQL outside of the for loop - but i'm having trouble constructing a query (I usually use __r notation within the SOQL) to traverse to related objects - I'm nto sure how to do this for Users since it's not really a related object - not unless they've been enabled on the contact.

 

Requestor__c is a lookup to a contact, which may or may not be an active customer portal user. This is an old piece of code I'm trying to update and make more efficient.

 

trigger changeOrderOwner on Order__c (before insert, before update) {

	try {
		for(Order__c o : Trigger.new) {
			o.OwnerId = [SELECT u.Id FROM User u WHERE u.ContactId = :o.Requester__c].Id;
		}
	}
	catch(Exception e) {
		
	}	

}

 

  • February 22, 2012
  • Like
  • 0

Greetings All!!

 

I have been working on a Google Visualization and am working on creating a graph with several plot points. The error I am getting is: Content cannot be displayed: Too many script statements: 200001

 

I am working with plotting out 2305 records into a line graph.

 

1) Is this possible?

 

2) If so how can I avoid the limitation?

 

Here is the Code:

public with sharing class TestResultGraphConroller {

	
	public TestResultGraphConroller(ApexPages.StandardController stdController){
	}
	
	public String getTestResult(){
        return getTestResult(null);
    }
    
    public String getTestResult(List<Id> ids){
        
        GoogleViz gv = new GoogleViz();
                
        gv.cols = new list<GoogleViz.col> { 
            new GoogleViz.Col('col1','Channel Flow','number'),
            new GoogleViz.Col('col2','Channel Volume','number'),
            new GoogleViz.Col('col3','Test','string')
        };
                
        Decimal numTestResult = 0.01;
        string query = 'SELECT Id, Channel_Flow__c, Channel_Volume__c, Test__c FROM Trial_Data__c WHERE Channel_Volume__c > 0' ;
                         
        // The unit testing path.
        if(ids != null && ids.size() > 0){
            query += ' AND Id IN :ids';
        }
        
        query += ' ORDER BY Name ASC'; 
                       
        for(Trial_Data__c td : Database.query(query)){  
            GoogleViz.row r = new GoogleViz.row();
            r.cells.add ( new GoogleViz.cell( numTestResult ) );
            r.cells.add ( new GoogleViz.cell( td.Channel_Volume__c ) );
            r.cells.add ( new GoogleViz.cell( td.Channel_Flow__c ) );
            r.cells.add ( new GoogleViz.cell( td.Test__c ) );
                
            gv.addRow( r );
            numTestResult ++;
        }

        return gv.toJsonString();
    } 

 Thank you for any help you can provide!!

 

JP

I am trying to figure out a formula that will let me do an average revenue per user (ARPU) on a per quarter basis.

What I am currently doing is (January revenue + February revenue + March revenue)/3

however, this is not accurate because if February or March numbers are not in yet, the divider causes the the ARPU to be lower than it actually is.

Can you help me with a formula for this?

  • February 07, 2012
  • Like
  • 0

The code below is setup to automatically create projects for all opportunities that reach a probability of >=90%. I am new to APEX coding and would like to add additional statements that would only allow 1 project for each opportunity. Right now, if an opportunity is updated from 90% to 100% an additional project would be created. What is the best way to limit the code so that only 1 project is created for each opportunity regardless of how many times the probability is updated?

 

Any help is greatly appreciated.

 

This is the code:

 

trigger Locate_Prob90_Opportunities on Opportunity (after update,after insert) {
	
	list<Opportunity> p90opps =
	[select probability
	from opportunity
	where probability >=90
	for update];
	
	for (opportunity oppz: p90opps){
		if(oppz.probability>=90){
			SFDC_project__c prject = new SFDC_Project__c(name='Acme test',opportunity__c=oppz.id);
	
			insert prject;
		
		}
	}
	
	
}

 

 

  • December 20, 2011
  • Like
  • 0

I have a fairly complicated VF page that is doing alot of things.  Everything is working except for line item editing.  Essentially I have a pageblock table that displays outputfields.  When a commandlink is pressed the output field for that row is not rendered and an input text field is rendered instead in its place. This is all working as desired.

 

However, when I hit the save command button, the value from the inputText field is not saved as part of the update statement.  It seems like I can not get the value to bind to the conroller.  I have tried using an input field, both with an separate object and as a way to update an entry in the mlines list  and neither work.  I have also tried various ideas using the <apex:param/> tag.

 

Any other ideas on why this will not work?

 

Here is the relevant code, there is much more but this should be the major sections involved.  Thanks in advance.

 

 

VF Page:

<apex:pageBlockTable value="{!mLines}" var="sl" title="Mechanical Lines">
        <apex:column styleClass="PN" headerValue="Part Number">
          <apex:outputfield value="{!sl.Part_Number__c}" rendered="{!removeId!=sl.id}" /> 
          <apex:inputText value="{!updatedPN}" rendered="{!removeId==sl.id}"/>
        </apex:column>
       
        
        <apex:column styleClass="action">
        <apex:commandLink value="Edit" action="{!EditLineStatus}" reRender="lineItems" immediate="true" rendered="{!removeId!=sl.id}">
            <apex:param value="{!sl.id}" assignTo="{!removeId}" name="removeId"/>
          </apex:commandLink>
          <apex:commandLink value="Save" action="{!EditLine}" reRender="lineItems" immediate="true" rendered="{!removeId==sl.id}">
            <apex:param value="{!sl.id}" assignTo="{!removeId}" name="removeId"/>
          </apex:commandLink>
</apex:pageblockTable          

 Controller:

public updatedPN {get; set;}

public pageReference editLine(){
        
        specifying_Lines__c updatedSl = new specifying_Lines__c(id = removeId, part_number__c = updatedPN);
        update updatedSl;
        requery();
        removeId = '';
        return Null;
      }

 

We have an interesting scenario that is keeping us from having good test coverage in our Org and I am looking for ideas on how to fix it:

 

Essentially the pseudocode goes like this:

 

listofLeads = Select stuff from lead where conditions are met and order by some criteria;

 

for (lead l: listofLeads){

   

   leadtoGet = select stuff from lead where id = l.id limit one for update

   if(leadtoGet is not NULL){

        update lead owner to current user

         break

   }

}

 

So the issue is obvious we have a SOQL query in the for loop.  In production we have no problems because there is a small enough number of users that there are few leads locked at any given time and once an unlocked lead is found the break gets us out of the loop and avoids governor limits.  However in testing this on 200 hundred records it loops more than enough times to hit the SOQL query limit.  As a work around a custom setting has been implemented that disables this entire block of code.  This allows the test to pass.

 

Unfortunately, this is actually replicated for 4 separate criteria and results in a large block of code that does not get tested and brings down our overall test coverage.  Also we are considering merging another org into this one that would increase the number of users by an order of magnitude and that could pose a problem as well, so we would like to refactor this code, but we are stuck.

 

Any ideas would be appreciated.

Recently I posted a question about the apex:relatedList tag.  Since that tag would not do what I needed it to do, I thought about making a custom component that worked like i need it to.  Here is what it should look like in practice:

 

<c:CustomRelatedList objectType="opportunity" fields="ID,Name"  relatedField="Account"></c:CustomRelatedList>

 

The assumption in this case is that this would be on a VF page that was displaying an account record, it would display a related list of opportunities using the fields in the fields attribute and where the relatedField = theCurrentAccountID.

 

I started implementing this using a controller and dynamic VF in Apex, and I can even create the query and display the results to an extent.  But what I am running into is that the attributes are not set in the controller until after the custom component is rendered.  What that means is that I have no way of dynamically determining the number of colums or even of setting the column headings because there does not seem to be a way to access the data from the custom component attributes when I need to.

 

I am looking for ideas on how to get the appropriate data into the controller earlier.  My only thought on this right now is to change the attributes of the custom controller to URL parameters and access them that way, but I feel that that set up is less ideal and could limit the usability of the component in the future.  Any other ideas?

 

Thanks 

Hello,

 

I have a case where I want my VF page to display a related list.  However, I can not find a way to define which fields show up on the resulting list.  My understanding, and what I have seen, is that the field list is pulled from the related list on the default page layout for that record type on the given object.  The problem that I run into is that we are using the default page layout still and I do not want the related list in question to show up on it, but whenever I remove the related list from the default page layout the related list on the VF page just defaults to showing the ID field.

 

My question is then, does anyone know of a different way to set the fields that are displayed by the relatedList tag?

 

Thanks.

Can you Dynamically create a field in a Trigger?

 

something like mySobject.addField(name = 'myName', etc);

 

I don't think that you can do that, but I thought I would ask before I gave up.

 

Thanks

I have a custom object with a "Set Default" Checkbox to indicate that that record is the default record for another process.  Obviously I only want one default record at a time.  I am writing a trigger to set all the other records checkbox to false when a new or updated records checkbox is set to true.  Here is my Code:

 

 

trigger SetDefault on Workflow_Types__c (before insert, before update) {
    
    List<Workflow_Types__c> wt = new List<Workflow_Types__c>([Select id, default__c from Workflow_Types__c]);
    Integer size = wt.size();
    for (Workflow_Types__c w: Trigger.new){
        if (w.Default__c == True){
            for (Integer i = 0; i < wt.size(); i++){
                if (wt[i].id != w.id){
                    wt[i].Default__c = False;
                    //update wt[i];
                }else{
                    Workflow_Types__c temp = wt.remove(i);
                    system.assertEquals(w.id, temp.id);
                    system.assertEquals(wt.size(), size-1);
                }
            }
        }
    }
    update wt;
    
}

 The problem is that even though I am trying to remove the record that calls the trigger and the assertions are passed for some reason it is still trying to recursively update the calling record when I call update wt, and gives me an error.  If I uncomment the line //update wt[i]; and comment the other update it does work, but I am afraid of possibly hitting governor limits by putting the DML statement in the for loops.  Any ideas would be appreciated.

 

Thanks

 

Edit: I have determined that the behaviour I described only happens when there are only two records in the object.  If I add more objects I have no problems

 

Hello I have three objects Order__c, Serial_number__c and path__c

 

Serial Number has a look up on order and is the master of path.  Path has a lookup on order.

 

Before inserting a path record I am trying to automatically get the order field filled in by using the serial number.  Here is my trigger:

 

 

trigger addOrder on Path__c (before insert) {
     
     for (integer i = 0; i < trigger.new.size(); i++){
    
        trigger.new[i].order__c = trigger.new[i].serial_number__r.Order__r.id;
         
    }
}
It does not return an error, but just leaves the Lookup field on Path blank.  Any Ideas on why this is not working?
Thanks

 

Hello,

 

I have three custom objects object1, object2, and object3.

 

Object2 is looks up a field in object1 and is the master of object3

 

In an apex class I have a query like List<object1> testList = new List<object1>( [select name, Object2_relationship_to_Object1__r.id from object 1])

 

What I need to do is take the id that is returned from object2 and get all the members of object3 that are related to it (select name from object 3 where id =: testList.Object2_relationship_to_Object1.id), but the only way that I can think to do it is interate through testList and call another query, which I know is bad because of governor limits.  Is there a better way to do this?

 

Thanks

I have an object that I would like to have security on based on two conditions the users profile and the value of a picklist field.  There are two diffferent tasks that I am trying to accomplish.  First it to hide a button and second is to make the picklist in question read-only.  So logically it would look like this:

 

if (user_profile == correct_user AND picklist1 == correct_data)

display button or allow edit on field

else hide button or make field read only

 

Is there any way to do this?

 

Thanks

How to call Two methods in  One Button click???????????thx in advance

  • December 03, 2013
  • Like
  • 0

I am troubleshooting System.LimitException: Too many SOQL queries: 101 errors in test classes. Is there a way that I can place i.e. system.debug('<current # on SOQL queries>'); to see where in my code that the SOQL queries jump in debug logs? Is there such a way to reference this global SOQL query count in my apex code?

 

Thank you.

Ours is Non profit organization where we use bucket model to handle individuals . For those who are not aware of it , under this model salesforce create one dummy account (individual) and if no org is provided it puts that contact under individual  . As a best practice no master should have more than 10k child records . It causes data skewing problem . 

I know one solution to it is create some more such dummy buckets and assign records to different  buckets . But how do I do that ? I have around million records . 

Any suggestions...

Thanks

I've got a beforeUpdate trigger on user that is supposed to do some work when the user is deactivated.  However the code seemed to not pass the below condition:

 

if (i.isactive == false)
{
   //do some work here
}

 

Shouldn't I be detecting for the Isactive field for this?  

 

TIA!

  • November 05, 2013
  • Like
  • 0

 

 

Is There a better Solution ? .

 

Custom Object : Math

    Custom  Field : N1

    Custom  Field : N2

 

Calculated fields/Formula fields : ((n3*n2__c)+n1__c) Where n3 is a range of value 10 to 500 in multiples of 10.

 

Sol 1 :

====

Each record having 50 ff fields with n1 and n2


 
 Click to View sample structure

==== 

 Problems :

1. Increases the count of fields 50 // downside is if we forsee range in multiples of one. we would have 500 fields.

2. n3 is a range entered by the "end user"  So system should be able to query shown below

 

Scenario 1 :

End user  searches for n3 = 30 

Search_Value < 3800  // This could be any value

 

 [Select n1__c, n2__c WHERE FF30 =:Search_Value] ; // Note FF30 is Dynamically Placed as n3 = 30

 

 

Scenario 2 : 

End user  searches for n3 = 40 

Search_Value < 5000 // This could be any value

 [Select n1__c, n2__c WHERE FF40 =:Search_Value] ; // Note FF30 is Dynamically Placed as n3 = 40

 

Search field should be dynamically changed based on the users input which is not a good practice too.

 

 

Sol 2 :

Create a child object for Math Say Math_subset__c

====

 

  Click to View sample structure
=====
 

Problems :

1. This will increase 50 Child records for each Math Record. if we foresee  this n3 in multiples of 1 then 500 records.

Imagine we have 2000 Math records this will increase the record count of subset 2000*500 ie. 2,500,000 records which is not a feasible solution seen.

 

2. Will reduce the performance of search.

 

 

Sol 3 : Hackers Solution

create a string field which holds those precalculated values as shown below.

=====

 

Click to View sample structure
====  

Search as :

[Select n1__c, n2__c WHERE String_Field__C LIKE '%Search_Value%'] ;

 

It has its own code complexity.

 

You may wonder why we need to store n3 as precalculated value. to get an answer please check More Info

 

 

 

 

 

 

 

 

 

 

Hey all,

 

I'm hoping to learn a great deal by posting here to find some expert feedback, and ideas. 

 

It's always been in the back of my mind that the more complex an application gets: the more "setup" based data is required to be populated during test classes. It seems to me that no matter how efficiently I code, follow best practices, and come up with interesting solutions: that I will eventually hit a wall  when it comes to getting (what salesforce deems) the necessary code coverage.

 

My team and I have been building an application for Supply Chain Management. It's a complex beast with many objects, and a great deal of automation and apex driven business logic. The two main application flows facilitate: Purchasing and Selling of Items.

 

This means we have complex systems surrounding pricebooks for Vendors, and Customers, warehouse/location validation, Item Databases, Bill of Materials Management, SalesOrder/Purchase Order management, Inventory Ins/Outs. There are a great deal of things that have to happen for a user to get to the final stage of one of the two main application flows. None of this is meant to happen all at once. It happens over time through a number of different user interfaces - this is basic application design for complex systems 101.

 

My issue comes when covering my code. In order to cover classes that take place at the end of one of the two previously mentioned flows: I have to essentially set up the entire organization. This includes huge numbers of DML statements/queries that have to occur in a single transaction because tests require this!

 

My question to you all is this: What secrets/tips do you have for developing complex applications and avoiding governor limits inside test classes? How do you avoid or mitigate the unnecessary overhead of re-factoring your architecture just for the needs of silly test classes that are ignored by clients during installation anyways?

 

Before you consider referring me to articles about "how to make your triggers batchable" and so on - know that I already do. There is not a single method or function in my entire application (that uses DML/Queries) that is not batchable. I use maps/sets everywhere to a point of obsession.

 

I look forward to what you all have to offer

  • October 25, 2013
  • Like
  • 0

I have objects A, B, and C. Object B is an association object for A and C, so it has a master-detail with both of them. Object B also has a formula field which takes values from C. I want to roll up that formula field to A. I know I need to use Apex and Triggers to do this, but I'm just learning and need some help with how to set up the triggers and classes. Thanks to all who respond

Hi,

 

I have created a very basic custom object called "News".  It uses a standard controller.  I have a page that displays a headline, the owner and the created date.  My visualforce code is:

 

<apex:pageBlockTable value="{!News}" var="n">
    <apex:column headerValue="Recent Posts"><br/><font size="5"><apex:outputLink value="/apex/NewsItem?id={!n.id}">{!n.Name}</apex:outputLink></font><br/><font size="1"><i>Posted by {!n.Owner.Name on {!n.CreatedDate}.</i></font><br/><br/>{!n.Preview_Text__c}<br/><br/><apex:outputLink value="/apex/NewsItem?id={!n.id}">Read More >> </apex:outputLink><br/><br/></apex:column>
    </apex:pageBlockTable>

 

How would I change this to sort by the created date by default?  I don't want the users to be able to change the order, I just want to code it to sort so that the newest records appear first.

We want to automatically add Maintenance Products to our Opportunity Products when a License is chosen.  We dont want sales to have to click on both products, but always have the maintenance product get inherited from the license product.  I am told that apex trigger ios only way for this to happen.

I have a conundrum. I want to run a query using the Like Comparison on multiple elements, but not having much luck.  When I attempt to us "Or" logic within a "Like" comparison no records are returned.  Can someone assist?

 

SELECT Academic_Plan_Returned__c, Campus_Name__c, CreatedById, CreatedDate, Quarter__c, Student__r.Name,  Student__r.Student_Id__c FROM At_Risk__c  where Student__r.Student_Id__c != '9999' and Academic_Plan_Returned__c = true and CreatedDate > 2013-04-05T00:00:00Z and CreatedDate < 2013-05-19T00:00:00Z and Campus_Name__c like '%new port,tampa%'

  • August 16, 2013
  • Like
  • 0

 Hi all,

  plz clear my doubt

 

 

I have trigger of 36% coverage and class of 69% will it be movable into production?

I have a custom object called "Contract_Line_Item__c" when someone enters in a product id I need to look it up and pull the UnitPrice from pricebookentry with

pricebook2id that is a constant and the product2id entered into the object by the user before save.  My code is just choking on my...  Having a hell of a day with brain overload...  Anyway I will give kudos to anyone who can probably solve this easily...  Here is the code.....

 

public with sharing class MaintContractLineItemCreation 
{
   public static void CreateContractLine(Map<Id,Contract_Line_Item__c> oldMap, Map<Id,Contract_Line_Item__c> newMap)
   {
    List<Contract_Line_Item__c> ContractLineItemsToUpdate = new List<Contract_Line_Item__c>();
    List<Id> CLIIds = new List<Id>();

    For(Contract_Line_Item__c cli : newMap.Values())
    {
        CLIIds.add(cli.id);
    }
        
    
    List<Contract_Line_Item__c> LineItemsToUpdate = new List<Contract_Line_Item__c>();

    
    for(Contract_Line_Item__c li :[SELECT ID, (SELECT UnitPrice FROM PricebookEntries where pricebook2id = '01s3000000001JS'), 
                (SELECT Product_LU__c, List_Price__c FROM Contract_Line_Items__r where id in :CLIIds) FROM Product2])

    {
        
            LineItemsToUpdate.List_Price__c =  li.UnitPrice;

            LineItemsToUpdate.add(li);
                
    }
    Update(LineItemsToUpdate);
   }
}

 Thanks again,

Steve

5 of our 30 companies were sold to another firm.  From a shared instance, we need to spin a new SFDC instance/licenses and move the companies out of our instance.  The data portion makes sense but we used tons of custom objects, triggers, apex class, workflows etc.

 

Is there a clone button for this development work and layout stuff? 

Hi, I'm trying to build a trigger that acts to update a picklist with the value of another picklist (located on the same record).

 

The custom object this trigger is on needs to be restricted but we also need to let all users create and edit records here to a degree, so we have a system where they can "request an update" to the record using identical fields to the actual fields/the fields used in a report. They can fill in one picklist, but the "actual" picklist field should remain as-is until a user with additional permissions changes a checkbox from false to true. I've built everything else we need for this using workflows, but I've learned with picklists you can only go up/down the list or set it to a specific value.

 

I tried changing the picklist to a checkbox as we only have 2 possible values, but ran into the same issue where I can only set it to true or false, not the value of another checkbox. We may also add a third option so I'd like to keep this field as a picklist.

 

I have a trigger and test class written but I get an error when running my test:

System.DmlException: Update failed. First exception on row 0 with id a0DQ0000003vFohMAE; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CRHUpdateWorkStatus: execution of BeforeUpdate


caused by: System.DmlException: Update failed. First exception on row 0 with id a0DQ0000003vFohMAE; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a0DQ0000003vFoh) is currently in trigger CRHUpdateWorkStatus, therefore it cannot recursively update itself:

 

Here is my trigger:

/* This trigger works based on if the "Request Approved" checkbox is checked.
If it is, it will update "Full-Time or Part-Time?" with the value in
"(Y) Full-Time or Part-Time?", provided that field is also not blank. */

trigger CRHUpdateWorkStatus on Church_Role_History__c (before update) {
     List<Church_Role_History__c> crhNEW = new List<Church_Role_History__c>();
     for(Church_Role_History__c crhOLD: Trigger.New)
     if (crhOLD.Request_Approved__c == True && crhOLD.Y_Full_Time_or_Part_Time__c != '')
     {
          crhNEW.add(new Church_Role_History__c (
          
          // Id
          id = crhOLD.Id,
          
          // Status
          Full_Time_or_Part_Time__c = crhOLD.Y_Full_Time_or_Part_Time__c
          ));
     }
     update crhNEW;
}

 

 

My test class:

@isTest
     private class TESTCRHUpdateWorkStatus {
          public static testmethod void MyTest() {
     
     {
          
          //Create a Contact for this test class.
          Contact c = new Contact();
          c.FirstName = 'Stephanie';
          c.LastName = 'Arce';
          insert c;
          
          //Create an Account for this test class.
          Account a = new Account();
          a.Name = 'Test Church';
          insert a;
     
          //insert a Church Role History record related to the Contact and Account.
          Church_Role_History__c crh = new Church_Role_History__c ();
          crh.Church__c = a.Id;
          crh.Person__c = c.Id;
          crh.Y_Full_Time_or_Part_Time__c = 'Full-Time';
          crh.Church_Position_Title__c = 'Administrative Assistant';
          crh.Request_Approved__c = True;
          insert crh;
          
          //Update the same Church Role History record so Request Approved = True.
          Church_Role_History__c crhu = [select Id from Church_Role_History__c where Id = :crh.Id];
          crhu.Request_Approved__c = True;
          update crhu;
          //See if "(Y) Full-Time or Part-Time?" value was copied to "Full-Time or Part-Time?"
          Church_Role_History__c crhq = [select Id from Church_Role_History__c where Id = :crhu.Id];
          system.assertEquals(crhq.Full_Time_or_Part_Time__c, 'Full-Time');
     }
   }
 }

 

Can someone explain the error message to me and what I have wrong in my trigger? Thank you so much for any help!

Hi. I have a trigger that triggers for more records than I hope for

 

trigger createOrderforABFSCB on Stem_Cell_Bank__c (after update) {

    List<ChargentOrders__ChargentOrder__c> co = new List<ChargentOrders__ChargentOrder__c>();  
   
  for (Stem_Cell_Bank__c scb : Trigger.new) {

    if (scb.Stage__c == 'Stem Cells Banked') { /*scb to oscb*/
      
      //initiate the object to put values for furture record
      ChargentOrders__ChargentOrder__c c = new ChargentOrders__ChargentOrder__c();

      //map Order fields to SCB that is being created for this Order
      c.Stem_Cell_Bank__c = scb.Id; /*scb to oscb*/

          c.ChargentOrders__Date__c = date.today();
          c.Order_Item__c = 'Yearly Stem Cell Banking Fee';
      
      if(scb.Stem_Cells_Banked_Date__c!=null)
        c.ChargentOrders__Payment_Start_Date__c = scb.Stem_Cells_Banked_Date__c.addYears(1);
      else
        scb.addError('Cannot have empty stem cell bank date before stage is set to stem cell banked');
          
      //add this new object to the list that would be inserted later
      co.add(c);
    } //end if
  } //end for scb
  
  //once the loop is done, insert the new record to Order
  try{
    insert co;
  } catch (system.Dmlexception e) {
    system.debug(e);
  }

}

This seems to add a new record for all records with stage__c = 'Stem Cells Banked'

 

I need to add a new ChargentOrder record for existing Stem_Cell_Bank__c record only to the respective ID when Stage__c is updated to 'Stem Cells Banked'

 

I tried researching more about using oldMap and played around with the logic:

 

Stem_Cell_Bank__c oscb = Trigger.oldMap.get(scb.ID);

 

But having a hard time getting it work. Plus if I could add a checksum logic to only allow 2 ChargentOrder records to 1 Stem_Cell_Bank record it will help even more to not encounter these type of errors in the future

 

Any suggestions would be greatly appreciated

 

Thank you in advance

 

Daniel

Hi

 

    Can SSRS be integrated with Salesforce . Do Salesforce allow to develop reports in SSRS.

 

Thanks

 

Hello I am new to Apex / Trigger and would like to use it to update one field from another on a custom object. I know this can be done via workflow but would like to try this with  a trigger so I can start to understand more about Apex. I am in the mids of reading about apex etc but would be grateful if someone could give me a few examples.

 

What I am trying to achieve:

 

Object name = Test object

 

Field 1 = A

 

Field 2 = B

 

All I want to do is make "field A" update with "field B" value after update.

 

Thank you