• David "w00t!" Liu
  • NEWBIE
  • 394 Points
  • Member since 2013

  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 110
    Replies
Hello,

I am running into trouble restricting lead conversion based on if certain fields are null.

I have the Industry field and a custom field Revenue Types on the lead object.  Both of these are required fields.  We also have leads coming in from the website, that are allowing leads to bypass this required field on the lead object in Salesforce.com.

Setting custom fields on the lead object that map to custom fields on the Account, Opportunities, and Contact objects, making them required, and mapping them via the User Interface seems like an overly complicated workaround for this.

I am wondering if there is a way via a trigger, or by other means, to make it so if users press "Convert" on the lead conversion process, it will give them an error if Industry and Revenue Types are null.

Setting validation rules on the Opportunity object itself doesn't seem to work for me in this, because this gets in the way of other processes that have previously been programmed.

Hopefully this makes sense.

Thanks for any information!


Controller:
public class TestRerenderController
{
    public List<String> text { get; set; }
    
    public TestRerenderController()
    {
        text = new List<String>();
        text.add('a');
        text.add('b');
        text.add('c');
    }
    
    public void hi()
    {
    }
}

VF page:
<apex:page controller="TestRerenderController" id="p">
    <apex:form >
        <apex:repeat value="{!text}" var="t">
            <apex:inputText value="{!t}"/><br/>
        </apex:repeat>
        <br/>
        <apex:commandLink action="{!hi}" value="Click me" reRender="p"/>
    </apex:form>
</apex:page>

Error when saving the page:
Error: Unknown property 't'


What gives?!
I tried to a load a file with 300 records using data loader in production & I get the following error. I was able load the same with out any error in a sand box. please sos. thank you

50 odd rows of this error followed by the 2nd error with unique record ID's
Error:Too many retries of batch save in the presence of Apex triggers with failures: when triggers are present partial save requires that some subset of rows save without any errors in order to avoid inconsistent side effects from those triggers. Number of retries: 2
2nd Error:duplicate value found: Account_ID__c duplicates value on record with id: 001G000001cEVFL

what could be the issue? thank you kindly

regards

Vishy
Hi,

I have a custom object which contains a field called Country, which is a text area field. If a certain criteria is met, a new Lead will be created using the data from that custom object. However, there is an issue because the Lead's Country field is a pick list and whenever the custom object's Country is not contained in the pick list or is a different variant of that country (i.e. United States vs United States of America). 

Within an apex trigger or class, how can i check if the custom object's country field value is a picklist value of the Lead standard object? If the custom object's country is a value contained in the Lead Country's pick list value then it inserts the Lead, ortherwise I can default the country or value to something else.

Below you will find a sample scenario
CustomObject obj = new CustomObject(FirstName='Test', LastName='Last', Country__c='United States');

//certain criteria is met
Lead newLead = new Lead();
newLead.FirstName = obj.FirstName;
newLead.LastName = obj.LastName;

/*
       * this can cause an error because the Lead object's country picklist value for 'United States' is actually 'United States of America'
       * also, if 'United States' is not in the Lead's object Country Pick list value, then it causes an issue because there is absolutely no correct mapping
*/
newLead.Country = obj.Country__c; 

insert newLead;



  • August 26, 2014
  • Like
  • 0

Hi,

Below is a piece of trigger to prevent the creation of Duplicate on whole org basis,

trigger ContactDuplicatePreventer on Contact(before insert, before update){
   Map<String, Contact> contactMap =new Map<String, Contact>();
    for (Contact contact : System.Trigger.new){
if ((contact.Email !=null) && (System.Trigger.isInsert ||(contact.Email != System.Trigger.oldMap.get(contact.Id).Email))){
  if (contactMap.containsKey(contact.Email)){
contact.Email.addError('Another new contact has the '+'same email address.');
            }else{
                contactMap.put(contact.Email, contact);
     }
       }
    }
    for (Contact contact : [SELECT Email FROM Contact WHERE Email IN :contactMap.KeySet()]){
        Contact newContact = contactMap.get(contact.Email);
        newContact.Email.addError('A Contact with this email '+'address already exists.');
   }
}

But i am looking to restrict duplicates only on Account records i.e. it should prevent duplicate contacts in case the the duplicate is on the same Account, if Account is not the same then it should allow duplicates.

Thank You

  • August 26, 2014
  • Like
  • 0
Hi,

Have a requirement where on clicking a button ( custom buttom )  it will take me to the Contact detail page with auto filled Account Name field.
Please help me . I'm confused and any sample code will work best for me . Thanks .Marc

Hello,

I want to write a SOQL to fetch all those account names which have contacts associted with them.

Also to fetch all those account names which have 10 contacts associted with them.


Thanks,
Mayank
I have the below trigger executing beautifully with 100% code coverage. Unfortunately when it creates a new record in the sandbox the Name of the record is the SFDC ID string referenced in the URL of the record. Is there any way to edit the code so readable text populates there instead of the ID string? For example using the name of one of the Parent objects (or combination of both) to easily identify the record

MerchOpps Name
a0aK0000004iSeQ
salesforce.com/a0aK0000004iSeQ

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
trigger MerchOppsRecords on Merchant_Application__c (after update){

    Set<Id> accountIds = new Set<Id>();
    Map<Id,Opportunity> accountOpportunityMap = new Map<Id,Opportunity>();
    for(Merchant_Application__c ma : Trigger.new){
        accountIds.add(ma.Account_Name__c); 
    }
    
  
    for(Opportunity opp : [Select Id, Name, AccountId from Opportunity where AccountId = :accountIds]){
        accountOpportunityMap.put(opp.AccountId,opp);
    }
    
    List<MerchOpps__c> mOps = new List<MerchOpps__c>();
     
    for(Merchant_Application__c ma : Trigger.new){
        
        if(accountOpportunityMap.containsKey(ma.Account_Name__c)){
            MerchOpps__c mo = new MerchOpps__c(ChildofOpp__c = accountOpportunityMap.get(ma.Account_Name__c).Id, ChildofMA__c = ma.ID);
            mOps.add(mo); 
        }
    }
   
    insert mOps;  
    
}
HI,

I have created an in depth flow which is working well, I want to be able to split screen this flow which I can do but I am unsure how to show the flow on oneside and then the created custom object on the otherside?

I think I need to pull a variable out of the flow but I am unsure on this.

Custom Object - Treatment_Plan__c
Variable - VarTreatmentID
Hi,
I have a requirement parsing csv file into salesforce(insert and update.)
I have a date field called in Period Start Date (MM/DD/YYYY.)
But my client is giving me Date Format like this MARCH 2014,
So can anyone please guide me how to convert date filed into This format MARCH 2014,APRIL 2013
a.PeriodStart__c=date.ValueOf(inputvalues[10]);

Thanks for your help and guidance
Regards,
Venkatesh
 Im new in salesforce so pls help me out
Hello,

I am running into trouble restricting lead conversion based on if certain fields are null.

I have the Industry field and a custom field Revenue Types on the lead object.  Both of these are required fields.  We also have leads coming in from the website, that are allowing leads to bypass this required field on the lead object in Salesforce.com.

Setting custom fields on the lead object that map to custom fields on the Account, Opportunities, and Contact objects, making them required, and mapping them via the User Interface seems like an overly complicated workaround for this.

I am wondering if there is a way via a trigger, or by other means, to make it so if users press "Convert" on the lead conversion process, it will give them an error if Industry and Revenue Types are null.

Setting validation rules on the Opportunity object itself doesn't seem to work for me in this, because this gets in the way of other processes that have previously been programmed.

Hopefully this makes sense.

Thanks for any information!



Hi,

What is the significance of-   trigger.newMap.keySet()?

Opportunity i=[select ownerid, id,Owner.manager.email,Owner.manager.name from opportunity where id=:trigger.newMap.keySet()];

Thanks 
Kaity
  • September 01, 2014
  • Like
  • 0
Hi ,

I have written a piece of trigger , trying to prevent duplicate contacts on an Account:

trigger PreventDuplicateContact on Contact (before insert, before update){

Set<id> accid = new Set<id>();
for (Contact c : Trigger.new)
accid.add(c.Accountid);

Map<Id,list<contact>> AccEmails = new Map<Id,list<contact>>();
Map<Id, Contact> cont = new Map<Id, Contact> ([Select Email from Contact where Id in:accid]);

for (Contact c : Trigger.new){
if ((contact.Email !=null) && (System.Trigger.isInsert ||(contact.Email != System.Trigger.oldMap.get(contact.Id).Email))){
if ( cont.containsKey(contact.Email)){
Contact co = cont.get(contact.Email);
if(co.accountid==contact.accountid){
contact.Email.addError('Another new contact has the '+'same email address.');
            }else{
                cont.put(contact.Email,c);
     }}
       }
    }
    for (Contact c : [SELECT Email FROM Contact WHERE Email IN :cont.KeySet()]){
        Contact newContact = cont.get(c.Email);
        newContact.Email.addError('A Contact with this email '+'address already exists.');
   }
}

But this is not working as expected. Please help me get it modified
  • September 01, 2014
  • Like
  • 0
public with sharing class updateAssetController {

    private list<ASSETS__c> asset;
    private list<AUDIT__c> audit;
   private list<AggregateResult> aggResult;
    private Integer Total;
    private String str; 
    private list<answerData> answer;
    private map<String,list<answerData>> ansData ;
    private map<String,Map<String,list<answerData>>> containsAllData ;
    private Integer Totalcount=0;
    private list<answerData>  filAns;
 
   
    public updateAssetController(){
  
       
    }
   
    
    public void allRecord(){
    
       
        asset = [Select id,name from ASSETS__c];
       
        list<String> nameList = new list<String>{'MAKE__c','COUNTRY__c'} ;
           
        ansData = new Map<String,List<answerData>>();
       
        for(String fieldName :nameList){
        
         String query = 'SELECT count(Id) myCount,'+fieldName+',ASSETS__c ';
                query+=  ' FROM AUDIT__c  GROUP BY '+fieldName+',ASSETS__c';
        
         aggResult = Database.query(query);
         
          for(AggregateResult ar:aggResult){
          
             String question;
             Total =  (Integer)ar.get('myCount');
             str = (String)ar.get(fieldName);
           
             question = fieldName.replaceAll('__c','');
            
             if(!ansData.containsKey(question)){
               
                 answer =new List<answerData>();
                 answer.add(new answerData(Total,str,(String)ar.get('ASSETS__c')));
                 ansData.put((question),answer);
             }
             else{
             
                 list<answerData> existingvalue = ansData.get((question));
                 existingvalue.add(new answerData(Total,str,(String)ar.get('ASSETS__c')));
             }
          }
        }
       
        containsAllData = new Map<String,Map<String,List<answerData>>>();
               
        for(ASSETS__c au :asset){
        
         map<String,list<answerData>> filterData = new map<String,list<answerData>>();
        
            for (String s : ansData.keySet()){
            
                list<answerData>  filAns =new list<answerData>();
               
                for(answerData anData : ansData.get(s)){
                
                 if(anData.Auid == au.id){
                 
                  filAns.add(new answerData(anData.a,anData.result,anData.Auid));                        
                        filterData.put(s,filAns);
                 }
                }
            }
            containsAllData.put(au.id,filterData);
        }
       
        Set<ASSETS__c> allAsset =  new Set<ASSETS__c>();
        map<String,List<answerData>> relatedRecord = new map<String,list<answerdata>>();
       
        for (String str : containsAllData.keySet()){
        
            ASSETS__c a = new ASSETS__c(id=str);
            relatedRecord = containsAllData.get(str);
            for(String assign: relatedRecord.keyset()){
            
             if(Assign=='MAKE'){
                 Integer firstInt =0;
                    Integer second =0;
                    String firstValue;
                    String secondValue;
                    Totalcount=0;
                   
                    for(answerData st:relatedRecord.get(assign)){
                    
                     Totalcount +=st.a;
                        if(firstInt == 0|| firstInt<st.a){
                         if(st.result != null && st.a> firstInt){
                                firstInt = st.a;
                                firstValue = st.result;
                            }else if(st.result == null && st.a> firstInt){
                                second =st.a;
                                secondValue =st.result;
                            }
                           
                        }
                    }
                    if(firstInt > 1){
                     a.MAKE__c = firstValue;
                    }
                    else{
                     a.MAKE__c = secondValue;
                    }
             }
               
                else if(Assign=='COUNTRY'){
                 Integer firstInt =0;
                    Integer second =0;
                    String firstValue;
                    String secondValue;
                    Totalcount=0;
                   
                    for(answerData st:relatedRecord.get(assign)){
                    
                        Totalcount +=st.a;
                        if(firstInt == 0|| firstInt<st.a){
                         if(st.result != null && st.a> firstInt){
                                firstInt = st.a;
                                firstValue = st.result;
                            }else if(st.result == null && st.a> firstInt){
                                second =st.a;
                                secondValue =st.result;
                         }
                        }
                    }
                          
                    if(firstInt > 1){
                     a.COUNTRY__c = firstValue;
                    }
                    else{
                     a.COUNTRY__c = secondValue;
                    }
                }
               
            }
            allAsset.add(a);
        }
        list<ASSETS__c> assetRecord =new list<ASSETS__c>();
        assetRecord.addALL(allAsset);
      
       
        update assetRecord;
     
        
    }  
   
    public class answerData {
        
        public Integer a;
        public String Result; 
        private String Auid;    
      
        public answerData(Integer a, String Result,String AssetId) {
            this.a =a;
            this.Result=Result;
            auid = AssetId;
        }
    }
  
}
Hello! I am new to apex development and any help is greatly appreciated. 

Here is the issue i am having. 

We are a real estate developer, and we use the case objects to log defiencies in condos (missing a door, scratches in the paint, cracks in a counter, etc)

our assets are in the following format : (project name) - (condo number)

instead of using the standard lookup field functionality (the looking glass, then search for keywords), i'd love to have 2 dropdown custom fields on the case object, one for the project, and one for the unit number, and when we save the new case, an apex trigger would run and concatenate the values of those fields into the (project name) - (condo number) format, and update the asset lookup field. 

I tried with a workflow rule + field update, but it won't let me update lookup fields. 

how would i go into doing that?

thank you very much!








I'm new to apex and am having difficulty with a test class for a working trigger and class in my sandbox.
The trigger and class I have work after insert and after update on a field value ('Stage') on a parent object. 
If the parent is new, then a new child object is created with a Stage__c field that mirrors the parent object 'Stage' field

I started writing a bulk test class, but as I couldn't get it to properly create new records, I started again from scratch with a single test record.
I insert the test record and a child record is created exactly as it should be. (System.debug, assert etc. confirm).

Then I take that same test parent record and update the 'Stage' field to a new value. The after update trigger should create another new child record with the new 'Stage__c' value and also find the old child record and update a field there. 

Even though System.debug says I've successfully updated the field 'Stage' on the parent object, the trigger is clearly not being called as it doesn't created a second child object.

I'm using oldStage.Stage = 'new value';  update oldStage;  

Guessing the Test environment never really 'saved' my initial record so it doesn't recognize this is a legit update. 

Can you help me understand best practice and solution(s)?

Thanks
HOW to get this equation result using APEX program and writing its class.

Example:  INPUT  a=1,b=2


out put should be= 9
  • August 29, 2014
  • Like
  • 0
When executing the following query on an object with many rows the system appears to hang. No results are returned, nor is any error triggered. Developer console returns "Communication Failure - no response from server", Workbench just keeps adding dots "." to "loading" message, nothing actually loads and eventually returns "Service was temporarily interupted or is unavailable. Please try again in a moment". The apex application just appears to hang.

SELECT Id,LastModifiedDate FROM AccountShare ORDER BY LastModifiedDate DESC LIMIT 2000

If we then execute the same query approx. 1 to 2 hours later we instantly get a result. I suspect this is because the query has been cached.

This type of query is being used by a Backup application that we are currently reviewing.

This also occurs on other objects: OpportunityShare, CaseComment and a few others.
  • August 29, 2014
  • Like
  • 0
Why not element lookup field can be added to the custom settings.
Hi,

We have 2 scheduled jobs which are executing hourly basis in our app. In few of our client's org, they stopped executing unexpectedly.

They are shown in Setup->Monitoring->Scheduled Jobs

But, the next scheduled run of both the jobs is null.

What can be the reason of this kind of behavior?

Thanks,
Rupali
I have a trigger on the Opportunity that creates a new Case when a custom opportunity field is marked True. At the bottom, I grab associated custom objects (Software_Key__c) from the opportunity and relate them to the new case.

When I test the trigger, line 59 is returning too many SOQL queries. No idea why because it isn't in a for loop. Anyone see what I'm missing?


Trigger: 
trigger CreateCase on Opportunity (after update) {

    List<Opportunity> newOpps = Trigger.new;
    Map<Id, Opportunity> oldOpps = Trigger.oldMap;
    
    List<Case> caseList = new List<Case>();
   
    Map<Id, Id> ocrMap = new Map<Id, Id>();
    List<OpportunityContactRole> ocrList = [SELECT Id, ContactId, OpportunityId
                                            FROM OpportunityContactRole
                                            WHERE OpportunityId IN :newOpps AND IsPrimary = true];
    for (OpportunityContactRole ocr : ocrList)
    {
    	ocrMap.put((Id) ocr.OpportunityId, (Id) ocr.ContactId);    
    }
    
	for (Opportunity opp : newOpps)
	{
		Opportunity beforeUpdate = oldOpps.get(opp.Id);

	   if (!beforeUpdate.Health_Check_Trigger__c && opp.Health_Check_Trigger__c && opp.New_Renew__c == 'New')
           {
		Case thisCase = new Case();
		thisCase.AccountId = opp.AccountId;
		thisCase.Subject = '14-Day Health Check';
            	thisCase.Health_Check__c = true;
            	thisCase.OpportunityId__c = opp.Id;
            	thisCase.OwnerId = '00Ga00000045f3pEAA';
            	thisCase.RecordTypeId = '012a0000001NcLLAA0';
            
		try
	        {
	            thisCase.ContactId = ocrMap.get(opp.Id);
	        }
	        catch(Exception e){}
            
	        caseList.add(thisCase);
             }
    }

    if (!caseList.isEmpty())
    {
     	try
        {
        	insert caseList;
        }
        catch (Exception e){}   
    }

    Map<Id, Id> caseMap = new Map<Id, Id>();
    for (Case c : caseList)
    {
        caseMap.put((Id) c.OpportunityId__c, (Id) c.Id);
    }
 
    List<Software_Key__c> skList = [SELECT Id, CaseId__c, Opportunity__c 
                                    FROM Software_Key__c 
                                    WHERE Opportunity__c IN :caseMap.keySet()];

    List<Software_Key__c> skToUpdate = new List<Software_Key__c>();
    for (Software_Key__c sk : skList)
    {
        sk.caseId__c = caseMap.get(sk.Opportunity__c);
        skToUpdate.add(sk);
    }
    try
    {
        update skToUpdate;
    }
    catch (Exception e){}


}


Hello,

I have defined apex trigger code which is working fine but the issue is with code coverage, its showing only 73% while deploying it into the production. Please help

Code snippet: 

trigger sendEmail on Case (after insert,after update) {
   Public static Boolean InitialEmail =false;
   Public static Boolean FinalEmail =false;
 
    //adding for check of trigger behaviour
     if(checkRecursive.runOnce())
    {
     for(Case c:trigger.new) {
      
        system.debug('outside'+c.Send_Email_to_Contact__c);
      
        if ((trigger.isInsert || (trigger.oldMap.get(c.Id).Send_Email_to_Contact__c != c.Send_Email_to_Contact__c)) && (c.Send_Email_to_Contact__c && !c.Do_not_Send_Email__c  && c.Email_of_Complainant__c!=null && c.Status!='Completed')) {
              
              system.debug('??????'+c.Send_Email_to_Contact__c);
             
              sendEmailMessage(c.id,c.ownerId,c.Internal_Comments__c,c.Email_of_Complainant__c,c.Site_Details__c,c.CaseNumber,c.Case_Customer_Reference__c );
        }
       
        if ((trigger.isInsert || (trigger.oldMap.get(c.Id).Status != c.Status)) && (c.Final_email_to_contact__c && !c.Do_not_Send_Email__c  && c.Email_of_Complainant__c!=null && c.Status=='Completed')) {
               
                system.debug('****************'+c.Send_Email_to_Contact__c);
               
                sendFinalEmailMessage(c.id,c.ownerId,c.Internal_Comments__c,c.Email_of_Complainant__c,c.Site_Details__c,c.CaseNumber,c.Case_Customer_Reference__c);
        }
    }
}
Controller:
public class TestRerenderController
{
    public List<String> text { get; set; }
    
    public TestRerenderController()
    {
        text = new List<String>();
        text.add('a');
        text.add('b');
        text.add('c');
    }
    
    public void hi()
    {
    }
}

VF page:
<apex:page controller="TestRerenderController" id="p">
    <apex:form >
        <apex:repeat value="{!text}" var="t">
            <apex:inputText value="{!t}"/><br/>
        </apex:repeat>
        <br/>
        <apex:commandLink action="{!hi}" value="Click me" reRender="p"/>
    </apex:form>
</apex:page>

Error when saving the page:
Error: Unknown property 't'


What gives?!
Hello,

We currently have created a custom object (Account Enrollment Data Sheet) within Salesforce that upon creation of the EDS record  pulls data from the Account and Opportunity objects primarily to populate the same fields represented within the custom object  - aka Account Enrollment Data Sheet .  The EDS is accessed via the Mini-Page layout off the Opportunity which is associated to the Account.  

Within the Account we have contacts that are associated to the acount.  One of our challenges has been to populate the Benefit Contact and Billing Contact fields contained within the custom EDS object with the contacts associated to the Account in which we are working.  We are working with a contracted concern to assist us with this delivery and so far this particular issue has stumped them.  They have tried a filtered lookup field but that doesnt work as its only showing the most recent contacts that have been "touched" buy that user.  Ideally, when the EDS record is created, we wanted to automatically populate the Benefit and Billing Contact fields on the custom EDS object.  The contacted concern could not delvier this requirement.
 
They have used formula's, filters, etc. to attempt to deliver this requriement.  At this point we are at a loss to understand why if I am already on the Account/Opportunity, I cannot either -automatically populate these two fileds or use the lookup to list just those contacts associated to the account in question.

Any feedback or recommendations would be greatly appreciated.

Thanks.

Getting this error (Error: Compile Error: unexpected token: JSONGenerator at line 11 column 11) when saving a new class, any thoughts? 
i have a images of size 5 GB and static resources limit is 250MB only. how to store these images in static resources?