• UC Innovation
  • PRO
  • 3885 Points
  • Member since 2016
  • UC Innovation, Inc.

  • Chatter
    Feed
  • 100
    Best Answers
  • 0
    Likes Received
  • 4
    Likes Given
  • 0
    Questions
  • 601
    Replies
Having a coding issue that I can't figure out.... New to this and feel like I am missing something.

Creating a trigger on a joiner object (Horizon_Account_Cases__c) between cases and a custom object (Horizon_Account__c) which has only two fields (Horizon_Acct__c and Case__c) which are unique keys for the ID's on the two related object cases.  Upon triggering on Horizon_Account_Cases__c, the related case (eg Case__C) should have its field Related_Horizon_Account__c updated with the value in the joiner object that triggered (Horizon_Acct__c).  Can't get it to compile and need help!  I am sure I am missing something very obvious...

public class horizonCaseLinkUtil {
    
    public static void addHorizonToCase (List<sObject> linkIds) {
        try {
        
        List<Case> casesToUpdate = [select Id 
                                            from Case caseUsed
                                            where Id in :linkIds.Case__c 
                                                         limit 1];                                                         

        List<Horizon_Account__c> horizonAccounts = [select     Id
                                            from Horizon_Account__c hzActCase
                                            where Id in :linkIds.Horizon_Acct__c
                                                         limit 1];                                                         
                                                         
        for (Case cases : casesToUpdate) 
        {
            for (Horizon_Account__c horizon : horizonAccounts)
            {
                cases.Related_Horizon_Account__c = horizon.Id;
            }
            
        }
        update casesToUpdate;
        }
        catch (Exception e) {
            System.debut('Issue with the Horizon Case Update: ' +e.getMessage() );
        }
    }
    
}


trigger HorizonAcctCaseLinked on Horizon_Account_Cases__c (after insert, after update) {
            List<sObject> linkedHorizonCase = new List<sObject>();
            for (Horizon_Account_Cases__c hzActCase : Trigger.new)
                linkedHorizonCase.add(hzActCase);
            if (linkedHorizonCase.isEmpty() == false)
            {
                horizonCaseLinkUtil.addHorizonToCase(linkedHorizonCase);
            }   
}


@isTest(SeeAllData=true)
public class HorizonCaseLinkTest {
        static testMethod void caseLinkTestMethod() {
        List<sObject> sourceList = [SELECT Id 
        FROM Horizon_Account_Cases__c LIMIT 1];
        Case c = new Case(Subject = 'Test Case');
        Horizon_Account__c horizonAcct = new Horizon_Account__c (Name='Test Horizon Acct');
        if(sourceList.size() == 0) {
            sourceList.add(
                    new Horizon_Account_Cases__c(Case__c =c.Id, Horizon_Acct__c=horizonAcct.Name)
            );
        }
        horizonCaseLinkUtil.addHorizonToCase( sourceList );
        }
}

 
Why would my email signature not be attaching to email Alerts?User-added image
I have my email setting set up
User-added image

Any Ideas?

Adeline
New to Salesforce.

I'm creating a fairly complex process in Process Builder on the Opportunity object.  When the record is saved I want to trigger and calculated some dates and do a few other checks to make sure only valid option types are entered.  Therefore, I want Process Builder to run after I do the Save trigger.  I couldn't find any documentation on this.
Hi,
I had tried to add the report tab, but I couldn't find this step"Click Edit next to the Recruiting app." how I can find it?
Hello,

I have an users who have profile "partner community", I want this profile to access only "cases" which are accociated to only 2 accounts.

How can i achieve this funcntionality ?
  • January 30, 2017
  • Like
  • 0
Hi I have written batch class to update stage field of opportunity as per close date but when I run my batch class it will be updating close date also.
How to prevent that can you guide where I did mistake in my code :

global class batchOpportunityUpdate implements Database.Batchable <sObject>{
    
    date dt1 = system.today().addDays(+30);
    date dt2 = system.today().addDays(+120);
    date dt3 = system.today().addDays(+182);
    Id oppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('New Rec3 Type').getRecordTypeId(); 
    
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        
        string query = 'SELECT Id,CloseDate,StageName,RecordTypeId FROM Opportunity Where RecordTypeId =:oppRecordTypeId ';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope){
            for(Opportunity opp : scope){
                if(opp.CloseDate <= dt1 && oppRecordTypeId == opp.RecordTypeId){
                System.debug('Record'+oppRecordTypeId +'dt1'+dt1);
                opp.StageName ='Qualification';
                }else if(opp.CloseDate <= dt2 && oppRecordTypeId == opp.RecordTypeId){
                    opp.StageName ='Needs Analysis';
                }else if(opp.CloseDate <= dt3 && oppRecordTypeId == opp.RecordTypeId){
                opp.StageName ='Closed Won';
                }
            }
            update scope;
            
    }
    global void finish(Database.BatchableContext BC){
            
    }
}


Thanks,
sumit
Hi, this code is functional but I think that it needs to be bulkified and improved. Can anyone provide a rewrite using best practices please? Thanks in advance!
 
trigger Results on Results__c (before insert, before update) {
    
    for (Results__c res : Trigger.new) {
        if (res.Name == '4'){
            
            List<Game__c> game = [SELECT Fourth_Place_Award__c
                                 FROM Game__c WHERE Id = :res.Game__c];
            	
            for(Game__c g : game){
                            If (g.Fourth_Place_Award__c == 0)
                            			{
                						res.Bubble__c = TRUE;
            							}
            						}

            				}
            
        }
        
    }

 
  • January 18, 2017
  • Like
  • 0
Hello Developers!
I have a rollup summary sum trigger on child object and it works fine accept it doesn't allow me to delete the child record once created.
I appreciate your help!
Trigger DirectCareAmount on Direct_Care_Assistance__c( after insert, after update,after delete,after undelete) {
     Set<Id> DispoIdSet= new Set<Id>();
     List<Cat_Disposition__C > DispoListToUpdate = new List<Cat_Disposition__C>();
     Map<Id,Cat_Disposition__c>  MapDispoToReset  = new Map<Id,Cat_Disposition__c>();
     
    if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete)
    {
        for(Direct_Care_Assistance__c DC: Trigger.new)
        {
            if(DC.Cat_Disposition__C != null)
                {
                    DispoIdSet.add(DC.Cat_Disposition__C );
                }     
        }
    }
   If(Trigger.isDelete) 
      { 
       for(Direct_Care_Assistance__c DC: Trigger.old) 
           { 
               if(DC.Cat_Disposition__C != null) 
                   {     
                           DispoIdSet.add(DC.Cat_Disposition__C );
                           MapDispoToReset.put( DC.Cat_Disposition__C, new Cat_Disposition__C ( Id= DC.Cat_Disposition__C,
                                                                                           Money_Spent_on_Direct_Care_Assistance__c = 0 ) );
                   } 
           } 
       }
    
   for(AggregateResult res : [SELECT Count(id)Quantity, Cat_Disposition__C ,sum(Dollar_Amount__c)addition FROM Direct_Care_Assistance__c WHERE                                                                     
                                                                                   Cat_Disposition__C IN :DispoIdSet group by Cat_Disposition__C ]) 
        {
                DispoListToUpdate.add(new Cat_Disposition__C         (     Id=(Id)res.get('Cat_Disposition__C'), 
                                                                           Money_Spent_on_Direct_Care_Assistance__c =  (Double)res.get('addition')
                                                                     )     
                                     );
                                                        
               if(Trigger.IsDelete && MapDispoToReset.containsKey(  (Id)res.get('Cat_Disposition__C ') )  )
                    {
                            MapDispoToReset.remove(  (Id)res.get('Cat_Disposition__C')  );                  
                    }
            }
        for ( ID cid : MapDispoToReset.keySet() )
        {
          DispoListToUpdate.add((Cat_Disposition__C)MapDispoToReset.get(cid));
        }
        
    try
    {
      update DispoListToUpdate;
    }
    catch(DmlException de)
    {
      System.debug(de);
    }
}
Error:  when delete the child record:

Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger DirectCareAmount caused an unexpected exception, contact your administrator: DirectCareAmount: execution of AfterDelete caused by: System.SObjectException: Invalid field Cat_Disposition__C for AggregateResult: Trigger.DirectCareAmount: line 37, column 1". 


 
Hello All,

Which Data type is better to use for Formula field which returns Phone Number? 

Text or Number? Is there any way that we can display formula field phone number in salesforce phone number format? ex:(123)-456-7890
 
Hi ... As a part of create a Schedule Batch Apex a query will return list of deals...... But I could not able to handle the list of records in Execute method.

End up with " Argument must be an Inline query"
I have written the following code for this:

global class PaymentAmountDueUpdt implements Database.Batchable<sObject>{
    global string [] email = new string[] {'xxxxxxxx.com'};
    List<Deal__c> deals;
    
    //Start method
    global Database.QueryLocator start (Database.BatchableContext BC) {
        //List<Deal__c> deals = [select id, Payment_Amount_Due__c,(select id, Payment_Date__c, Purchase_Amount__c from cash_flows__r where Payment_Satisfied__c = false order by Payment_Date__c limit 1) from deal__c ];
        Deals = new List<Deal__c>([select id, Payment_Amount_Due__c,(select id, Payment_Date__c, Purchase_Amount__c from cash_flows__r where Payment_Satisfied__c = false order by Payment_Date__c limit 1) from deal__c]);
        return Database.getQueryLocator(Deals);
    }
    
    //Execute Method
    global void execute (Database.BatchableContext BC, List<Deal__c> deals) {
          for(Deal__c d : deals){    
            if(!d.cash_flows__r.isEmpty()){
                d.Payment_Amount_Due__c = d.cash_flows__r.get(0).Purchase_Amount__c;
            }
        }
        update deals;
    }

Please suggest me where it went wrong.

Thanks !
I do not want to show a column in a data table if the respective field for all records returned in a query are empty . 
For example, if the field PAID_LOSS__c in the result set is empty how can I render that column false ? 

I render the page block if the entire result set is empty but need to also test each discrete field in order to not render a particular column within the data table. 
<apex:pageBlockSection columns="1" id="section2c" title="* Expiring Contract Experience" showHeader="true" rendered="{!NOT(!PriorYRcontractSectionList.empty)}" >
 
 
             <apex:outputPanel id="out2c">
                <apex:actionstatus startText="loading...">
                    <apex:facet name="stop" >
                        <apex:outputPanel >
                                                                                
                             <apex:dataTable style="text-align:right;" value="{!PriorYRcontractSectionList}" var="pyr" rules="all" cellpadding="5"  >
                                <apex:column value="{!pyr.Name}" headerValue="Contracts"/>
                                <apex:column value="{!pyr.ULTIMATE_PREMIUM__c}" headerValue="Ult Prem"/>                       
                                <apex:column value="{!pyr.PAID_LOSS__c}" headerValue="Ttl Rprd Loss" />  
                                 <apex:column value="{!pyr.ACR__c}" headerValue="Ttl ACR"/>  
                                <apex:column value="{!pyr.ULTIMATE_LOSS__c}" headerValue="Ttl Ult Loss Incl ACR"/>                               
                                <apex:column value="{!pyr.Ultimate_Loss_Ratio__c}" headerValue="Ult LR%"/>  
                                <apex:column value="{!pyr.F_DETAIL_COMMISSION__c}" headerValue="Ult Comm%"/>  
                                <apex:column value="{!pyr.F_DETAIL_BROKERAGE__c}" headerValue="Ult Brok%"/>     
                                <apex:column value="{!pyr.ULT_OVERHEAD_EXCL_CATS__c}" headerValue="Ult OH%"/>
                                <apex:column value="{!pyr.ULT_CR_ACCT_OH__c}" headerValue="Ult CR%"/> 
                                <apex:column value="{!pyr.ULT_CR_ACCT_EXCL_OH__c}" headerValue="Ult CR x OH%"/>                               
                                <apex:column value="{!pyr.ITD_CR_EXCL_ACCT_OH__c}" headerValue="ITD CR x OH%"/>                                                              
                            </apex:dataTable>
                            
                       </apex:outputPanel>
                    </apex:facet>
                </apex:actionstatus>
            </apex:outputPanel>
 
 
 </apex:pageBlockSection>
 
 
 public List<MR_Contracts__c> BoundcontractQSSummaryList {get;set;}
 this.BoundcontractQSSummaryList = queryBoundQScontractsummaryById(contractNumbers, this.ContractYear);   
  
	   
  private List<MR_Contracts__c> queryBoundQScontractsummaryById(List<String> contractIds, string ContractYear) {
      return [
      SELECT
        Id
        ,Name
        ,Renewal_Date__c
        ,Effective_Date__c
        ,SPD_RTC_CODE__c 
        ,SUBJECT_PREMIUM_PS__c
        ,QUOTA_SHARE_PART_OF__c
        ,Limit__c
        ,Event_Limit__c
        ,Participation__c
        ,Estimated_Premium_PS__c
        ,Maiden_Re_Limit__c
        ,Attachment_Type__c
        ,RSO_LAE_TYPE__c
        ,RSO_ECO_PCNT__c
        ,RSO_XPL_PCNT__c
        ,F_DETAIL_COMMISSION__c
        ,PROFIT_COMM_RATE__c
        ,PROFIT_COMM_PNCT__c
        ,Ceding_Comm_Min__c
        ,Ceding_Comm_Prov__c
        ,Ceding_Comm_Max__c    
        ,CEDING_COMM_INT__c
        ,CEDING_COMM_MIN_LR__c
        ,CEDING_COMM_PROV_LR__c
        ,CEDING_COMM_MAX_LR__c
        ,CEDING_COMM_INT_LR__c
        ,BROKERAGE__c
        ,CAT_LOAD_PCT__c
        ,PRICED_ULT_OVERHEAD_EXCL_CATS__c
        ,ROE_COMBINED_TARGET__c
        ,COMBINED_RATIO__c
        ,Priced_C_R_Excl_OH__c
        ,TARGET_ROE__c
        ,ROE__c
  
       FROM
        MR_Contracts__c
      WHERE
        ContractSubmissionRef__c IN :contractIds
      AND
        SPD_RTC_CODE__c LIKE '%QS%'   
      ORDER BY Name DESC
    ];
  }

 
Hello, 
I'm new to Salesforce. In our assest records we have part numbers that range from 15-25 digits. These numbers are entered into fields in SF for documentation. The last 6 digits of the 15-25 number is the actual serial number of the part, the rest is manufacturing codes. I would like the field to display the last 6 digital, but if a user click (or double clicks) the field it shows the full lenght number. 

If you have a solution that would be great and how to create it. I inherited the Saleforce and trying to figure it all out. 

Thanks for any help! 
Brian
 
Hi SF Jodhas,

I would like to understand the likely result of the following scenario please:

I have an Email Template 'A' with a certain template id, we have a corresponding email template 'B' in sandbox that has been built with the same API name but different template id (this was no data refresh between prod and sandbox). Now when I push 'B' to production will it overwrite the existing 'A' in production since the Unique Emaiol Template API name is the same between A & B? or is there a risk of creating a new Email template as the template ids are different between the systems? Thanks in advance.

Regards,

Vijay
I'm curious to know, if I import records to our Sandbox will those records create duplication in our Production org? I have some data that resides in our Production org that I want to import to our Sandbox to work on. Will that then create a duplicate in the Production org?

Thanks in advance for any help with this one.

Glenn
The triggers below count the number of contacts and active contacts on an account. I am not getting any errors with the below triggers however, after doing some testing I found that recalculation is not taking place when a contact is deleted and field "Number of Contacts" is not updating properly. How can I correct this problem? 
 
trigger NumberOfContacts on Account (before insert, before update) {
if(trigger.isinsert)
    for(account a:trigger.new)
        a.Number_of_contacts__c = 0;
else {
    List<AggregateResult> agResult = [SELECT Count(ID) conCount, AccountId accId FROM Contact WHERE AccountId IN :trigger.new Group By AccountId];
    for(AggregateResult result : agResult){
        trigger.newmap.get((Id) result.get('accId')).Number_of_contacts__c = (Integer)result.get('conCount');
    }

    for(Account act : Trigger.new){
        act.Number_of_active_contacts__c = 0;
    }
    agResult = [SELECT Count(ID) conCount, AccountId accId FROM Contact WHERE AccountId IN :trigger.new AND Inactive__c = false Group By AccountId];
    for(AggregateResult result : agResult){
        trigger.newmap.get((Id) result.get('accId')).Number_of_active_contacts__c = (Integer)result.get('conCount');
    }
}
 
trigger NumberOfContactsOnAccount on Contact (after insert, after update, after delete, after undelete) {
List<Contact> contacts = new list<contact>();
Map<Id,account> accounts = new map<id,account>();
if(trigger.new!=null)
    contacts.addAll(trigger.new);
if(trigger.old!=null)
    contacts.addAll(trigger.old);
for(contact c:contacts)
    accounts.put(c.accountid,new account(id=c.accountid));
accounts.remove(null);
update accounts.values();
}

User-added image


Thanks in advance!
I am trying to use Data Loader to insert several Contact records for existing Accounts.  I have the Salesforce ID of the existing account but the error I get back is:  Organization Name: id value of incorrect type:001A000000yL5CnlAK/d.  That is the correct SF ID for the account (I have verified this)  Help!
I have a lookup field that looks for contacts of a certain record type.  That part works fine. The problem is I want the filter to only apply to our sales reps. If an admin enters a value, I don't want that filter to apply. 

I see that I can make the field optional or required, but this is an all or nothing approach. I would be fine to make it optional for admins and required for sales reps but this is not possible.

So I tried to add in another filter critera for current user profile to only include admins, however this doesn't seem to work.  

Does anyone have recommendations for me to get around this?
Thanks!
I am having trouble with the syntax on line 28 (bolded below) – the error I receive says: ‘expecting a right parentheses, found ‘and’’
How can I correct that part? I want it to check to be sure the expiration date is less than today and that the status is not currently in manually expired or expired. If it passes, execute the batch expiration.

global class Batch_ExpDate_NoPricIn
{
global Database.QueryLocator start(Database.BatchableContext BC)
{
string manualExpStr = 'Manually Expired';
string expiredStr = 'Expired';

string query= 'select Id,RecordTypeId,RecordType.Name,Par_Status__c,Effective_date__c,Expiration_Date__c from Price_Authorization_Request__c where Par_Status__c !=:manualExpStr and Par_Status__c !=:expiredStr';

return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List Parlist)
{

if(Parlist != null && !Parlist.isEmpty())
{
for(Price_Authorization_Request__c parObj : Parlist)
{

List NprList = [select Id,Expiration_Date__c, PAR_Status__c from Price_Authorization_Request__c Where Price_Authorization_Request__c =: parObj.Id];

if(NprList != null && NprList.size() > 0)
{
Integer count = 0;
for(Price_Authorization_Request__c PARObjNpr : NprList)
{

if(PARObjNpr.Expiration_Date__c != null && PARObjNpr.Expiration_Date__c < system.today() && PARObjNpr.PAR_status__c !='Manually Expired' and PARObjNpr.PAR_Status__c != 'Expired')
{
count = count + 1;
}
}
}
}
}
}
global void finish(Database.BatchableContext BC)
{}
}

 
I have two objects linked with a lookup field. 
On each object is a field called "reciept number" (that is unique).
On one object the information comes in through an automated process. My hope is to build something that compares the two "reciept number" fields and if it finds a match, it populates the look upfield with the Salesforce Unique ID number for that record (to link the two records).
Try as I might, I haven't been able to find anything that discusses how this can be done.
Any help in pointing me in the right direction would be greatly appreciated. 
How can I get this to work, trying to create a URL within records to bring employees to a tracking page for shipments:

https://www.fedex.com/apps/fedextrack/?tracknumbers=LEFT(Auto_TrackingNum_Step1__c,find(' ',Auto_TrackingNum_Step1__c))

This doesnt seem to be working as I get a syntax error
Having a coding issue that I can't figure out.... New to this and feel like I am missing something.

Creating a trigger on a joiner object (Horizon_Account_Cases__c) between cases and a custom object (Horizon_Account__c) which has only two fields (Horizon_Acct__c and Case__c) which are unique keys for the ID's on the two related object cases.  Upon triggering on Horizon_Account_Cases__c, the related case (eg Case__C) should have its field Related_Horizon_Account__c updated with the value in the joiner object that triggered (Horizon_Acct__c).  Can't get it to compile and need help!  I am sure I am missing something very obvious...

public class horizonCaseLinkUtil {
    
    public static void addHorizonToCase (List<sObject> linkIds) {
        try {
        
        List<Case> casesToUpdate = [select Id 
                                            from Case caseUsed
                                            where Id in :linkIds.Case__c 
                                                         limit 1];                                                         

        List<Horizon_Account__c> horizonAccounts = [select     Id
                                            from Horizon_Account__c hzActCase
                                            where Id in :linkIds.Horizon_Acct__c
                                                         limit 1];                                                         
                                                         
        for (Case cases : casesToUpdate) 
        {
            for (Horizon_Account__c horizon : horizonAccounts)
            {
                cases.Related_Horizon_Account__c = horizon.Id;
            }
            
        }
        update casesToUpdate;
        }
        catch (Exception e) {
            System.debut('Issue with the Horizon Case Update: ' +e.getMessage() );
        }
    }
    
}


trigger HorizonAcctCaseLinked on Horizon_Account_Cases__c (after insert, after update) {
            List<sObject> linkedHorizonCase = new List<sObject>();
            for (Horizon_Account_Cases__c hzActCase : Trigger.new)
                linkedHorizonCase.add(hzActCase);
            if (linkedHorizonCase.isEmpty() == false)
            {
                horizonCaseLinkUtil.addHorizonToCase(linkedHorizonCase);
            }   
}


@isTest(SeeAllData=true)
public class HorizonCaseLinkTest {
        static testMethod void caseLinkTestMethod() {
        List<sObject> sourceList = [SELECT Id 
        FROM Horizon_Account_Cases__c LIMIT 1];
        Case c = new Case(Subject = 'Test Case');
        Horizon_Account__c horizonAcct = new Horizon_Account__c (Name='Test Horizon Acct');
        if(sourceList.size() == 0) {
            sourceList.add(
                    new Horizon_Account_Cases__c(Case__c =c.Id, Horizon_Acct__c=horizonAcct.Name)
            );
        }
        horizonCaseLinkUtil.addHorizonToCase( sourceList );
        }
}

 
I am trying to use Eclipse IDE and we keep receiving the invalid username, password, security token error.  We have everything, made sure credentials are correct, we put token after password.  Nothing seems to work.  I know the password is fine and token, it downloads objects we created in SF, but we badly need to execute soql against the schema.  Please Help!!!
I'm hoping you can help please.

We are executing a Batch class from Scheduler Class - it is not executing. We tried to run Batch class from Execute anonymous, still not working and throws an error "Internal Salesforce Error" (attached error below)

Very much appreciate any ideas.

Thanks
Jim
jim.fisher@spandex.com.au

Batch Class fatal error
Hello everyone,

I am having issues getting value of the date field from the Opportunity object. I need to get Start date and End date, store them in a variable to send them as a part of an XMLH request. I have tried few things:
var startDate  = [SELECT Start_Date__c FROM Opportunity where Id = 'XYZ']; 
var startDate = {!Opportunity.Start_Date__c}; - this is a weird one I get a long number, but it's not the milliseconds, and it starts with 0.00049578....

var c = new sforce.SObject("Opportunity");
var startDate = c.Start_Date__c;

nothing works. I have a feeling I am very close, but can't quite get there. Any help apprechiated. 
 
I am doing thhe Trailhead excerize of process automation annd I get the 
System.ListException: List index out of bounds: 0
It does not say how annd where.

I redid the the one picklist - Type. and the Field update functions and all the places where the pcklist values are referenced.
But I am still getting the error.

I have not learned the debug mode and not in the visual force language yet.

Could someone please direct me to solve the issue.

Thanks in advance.
Pevaz 
Why would my email signature not be attaching to email Alerts?User-added image
I have my email setting set up
User-added image

Any Ideas?

Adeline
Hi all!

I am trying to create a field on cutom object that will display Account Primary Contact (First Name Last name) on it. On contact page I have dropdown where I select Role for the contact.

I was thinking if that is possible to do with the formula. But not sure how to implement it right.

Here is suggested solution I found http://salesforce.stackexchange.com/questions/97479/formula-field-to-show-primary-contact-name-on-account-object

But the case is that, I want use field values now and not to wait intil they created/edited.

Thank you for helping me out!
if a user enters a date value into a date field, can a validation field require a specific picklist value?

AND( 
ISBLANK(Ending_Date__c), 
OR( 
ISPICKVAL( Status__c, 'Pink'), 
ISPICKVAL( Status__c, 'Red')))
Good morning,

I have an apex trigger on opportunities that creates a new opportunity for the next year when a specific "sales stage" is selected. I recently updated the trigger to fire when the Closed/Won sales stage is selected OR Membership Started is selected. The problem is that the Membership Started stage is changed at a later date to Closed/Won, which will create a duplicate new opportunity (we only want 1 new opp). Does anyone have any advice? I have been stuck for a few days. My code is shown below:

 public static void createNextYearOpp(List<Opportunity> newlist, Map<Id, Opportunity> oldMap){
        Map<String, Schema.RecordTypeInfo> recordTypeInfo = Schema.SObjectType.Opportunity.getRecordTypeInfosByName();      
        list<Opportunity> newYearOppList = new list<Opportunity>();
        map<Id,Opportunity> originalOppIdToCloneOpp = new map<Id,Opportunity>();
        
        for(Opportunity opp : newList){
            if(oldMap != null && oldMap.get(opp.id).StageName != opp.StageName && opp.StageName == 'Closed/Won'|| opp.StageName =='Membership Started PIP'
                    && opp.Buy_Type__c == 'Security Benchmarks' && opp.Prospect_Type__c == 'SB New Business'
                    && opp.Membership_Start_Date__c != null) {
                Opportunity newOpp = new Opportunity();
                Id recordId = recordTypeInfo.get(opp.Prospect_Type__c).getRecordTypeId();
                newOpp.RecordTypeId = recordId;
                newOpp.name = opp.CloseDate.addYears(1).year() + ' ' + opp.name.subString(4);
                newOpp.Prospect_Type__c = 'SB Renewal';
                newOpp.CloseDate = opp.Membership_Start_Date__c.addYears(1);
                newopp.Membership_Start_Date__c = opp.Membership_Start_Date__c.addYears(1);
                newopp.Buy_Type__c = opp.Buy_Type__c;
                newOpp.AccountId = opp.AccountId;
                newOpp.NextStep = opp.NextStep;
                newOpp.Follow_up_Date__c = opp.Follow_up_Date__c;
                newOpp.CIS_CAT_Trial__c = opp.CIS_CAT_Trial__c;
                newOpp.Billing_Cycle__c = opp.Billing_Cycle__c;
                newOpp.Priority__c = opp.Priority__c;
                newOpp.Membership_Category__c = opp.Membership_Category__c;
                newOpp.OwnerId = opp.OwnerId;
                newOpp.Legacy_Membership_Fee__c = opp.Legacy_Membership_Fee__c;
                newOpp.TotalOpportunityQuantity = opp.TotalOpportunityQuantity;
                newOpp.Probability = opp.Probability;
                newOpp.Reason_Lost__c = opp.Reason_Lost__c;
                newOpp.Forecast__c = opp.Forecast__c;
                newOpp.LeadSource = opp.LeadSource;
                newOpp.Description = opp.Description;
                newOpp.Legacy_Created_By__c = opp.Legacy_Created_By__c;
                newOpp.Legacy_Created_Date__c = opp.Legacy_Created_Date__c;
                newOpp.Campaign = opp.Campaign;
                newOpp.Amount = opp.Amount;
                newOpp.StageName = 'To Be Invoiced';
                system.debug('@@ '+newOpp.name);
                //newYearOppList.add(newOpp);
                originalOppIdToCloneOpp.put(opp.Id,newOpp);
            }            
        }
Hello Team,

I am running into governor limits despite using database.batchable .
I am not being able to identify where the issue is.... Can some one just check my code and identify if possible ..
Any help is appreciated...
 
global class BatchToUpdatePageViews implements Database.Batchable<sObject>, Database.Stateful, Schedulable, Database.AllowsCallouts{

    private List<String> EMAIL_BATCH_RESULTS = new List<String>{System.Label.Email_List};  
    global  UrlIndividualMonthlyActivityServices.PageviewBatchResponse runningBatchResponse;
    private String query;
    private Integer queryYear;
    private Integer queryMonth;

    global BatchToUpdatePageViews(Integer year, Integer month){
        runningBatchResponse = new UrlIndividualMonthlyActivityServices.PageviewBatchResponse();

        // Validate user input, if request to run batch is not for todays date
        if(month != null && year != null && month >= 0 && month <= 12 && year > 1950){
            this.queryYear  = year;
            this.queryMonth = month;
        }
        else{
            Date yesterdaysDate = Date.today().addDays(-1);

            this.queryYear  = yesterdaysDate.year();
            this.queryMonth = yesterdaysDate.month();
        }

        this.query  = 'SELECT Id, GID__c ';
        this.query += 'FROM Monthly_Activity__c ';
        this.query += 'WHERE Year__c = ' + queryYear + ' ';
        this.query += 'AND Month__c = ' + queryMonth + ' ';
        this.query += 'AND GID__c <> null ';
        this.query += 'AND GID__c > 0 ';
    }

    global BatchToUpdatePageViews(){
        this(null, null);
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monthly_Activity__c> currentBatchRecords){
        List<URL_Individual_Monthly_Activity__c> urlIndividualMonthlyActivities = [
            SELECT Id, GID__c, URL__c, Month__c, Year__c
            FROM URL_Individual_Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        

        if(urlIndividualMonthlyActivities.isEmpty()){
            return;
        }

        UrlIndividualMonthlyActivityServices.batchHandlerToUpdatePageviewCredits(
            runningBatchResponse,
            urlIndividualMonthlyActivities,
            queryYear,
            queryMonth
        );

        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecords().isEmpty()){
            List<Database.SaveResult> updateResults =
                Database.update(runningBatchResponse.getSuccessRecords(), false);

            for(Database.SaveResult updateResult : updateResults){
              if(!updateResult.isSuccess()){
                for(Database.Error err : updateResult.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
    }

    global void execute(SchedulableContext SC){
        Database.executeBatch(new BatchToUpdatePageViews(), 2);
    }
    
    global void finish(Database.BatchableContext BC){
        AsyncApexJob apexBatchResult = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id =: BC.getJobId()
        ];
    
        // Generate email body
        String emailBody = 'Apex Batch to Update Pageview Credits processed '
            + apexBatchResult.TotalJobItems + ' batches with '+ apexBatchResult.NumberOfErrors + ' failures.\n\n'
            + 'Database errors (if any): ' + JSON.serialize(runningBatchResponse.getDatabaseErrors()) + '\n';
        
        // Extract error string from batch response
        //emailBody += runningBatchResponse.generateErrorString();

        // Send email
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(EMAIL_BATCH_RESULTS);
        mail.setSenderDisplayName('About.com Experts - Batch Results');
        mail.setSubject('About.com - Batch to Update Page Views - status: ' + apexBatchResult.Status);
        mail.setPlainTextBody('Batch Process has completed\n\n' + emailBody);

        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
    }
}

 
New to Salesforce.

I'm creating a fairly complex process in Process Builder on the Opportunity object.  When the record is saved I want to trigger and calculated some dates and do a few other checks to make sure only valid option types are entered.  Therefore, I want Process Builder to run after I do the Save trigger.  I couldn't find any documentation on this.
Hi,
I had tried to add the report tab, but I couldn't find this step"Click Edit next to the Recruiting app." how I can find it?
Hello,

I have an users who have profile "partner community", I want this profile to access only "cases" which are accociated to only 2 accounts.

How can i achieve this funcntionality ?
  • January 30, 2017
  • Like
  • 0
I have several Related Lists which are on the Page Layout for Account.  I would like to programatically add an additional Related List to the Page Layout for Account through Apex alone.  Is that possible?
 

What is the way to upload an object RECORD with all its lookup data from Sandbox to Production?

 

 

Thanks in advance .Please help if there is any way to do that.

Hi,

We're currently have a Salesforce Enterprise license and I'm wondering as if is there a way we can bring all of our existing data from our Production environment to our Sandbox environment so that we can do some performance tests.  Any idea is welcome.

 

Thanks,

bear_2001

HI Experts,

I have a requirment where i have to find useless columns on all tables in my org,and wants to remove it,actually am working on some JUNK org they created huge columns on each and every table so now i just wanted to find out which are not using by any one in my org and remove them permenantly,can anyone adivise me is there any tools we can use to do it?Or any other way?

Thanks In Advance!
We are trying to create a field formula to calculate commissions based on down payment percentage. The IF formula is slightly too big. Any suggestions to make this formula fit?

IF(Down_Payment_Percent__c >= 0.1 && Down_Payment_Percent__c <= 0.2499, Amount *0.08,

IF(Down_Payment_Percent__c >= 0.25 && Down_Payment_Percent__c <= 0.4999, Amount *0.09,

IF(Down_Payment_Percent__c >= 0.5 && Down_Payment_Percent__c <= 0.7499, Amount *0.10,

IF(Down_Payment_Percent__c >= 0.75 && Down_Payment_Percent__c <= 0.9999, Amount *0.11,

IF(Down_Payment_Percent__c >= 1 , Amount *0.12,0)))))

Thanks
Hi All,

We use the case assignment rules within our business and they work well

I currently have these marked as default on the page layout so it automates this.

However users want the ability to save and check a case before pushing it through the rules. Is it possible to attach some code to a custom button that will push the case through the assignment rules if they want to?

Thanks Matt
In my application, I create a form for public to fill in thier information. There questions of all require public to insert attachment. The default name of the attachment are the name decidie by public, but it is hard for administraion. Thus, I want to rename it in a meaningful way:

(RecordID)_(UserName)_(DateOfCreate)_(Q).(Format)
RecordID is the name of the record of custom object.
UserName is the data insert by users in the field "Artist_English_Name__c"
DateOfCreate is the date of creating the record of custom object.
Q is the question that the attachment belongs to.
Format is the type of attachment indicated, as I need them for the name conversion in data export.
Because I want to trace back the attachment ie owned by who and which question. 

At this stage, I only achieve this ("a002800000i5q8UAAQ_Alex_2016-08-03_Technical_field2.png") by this code:
objAttachmentt.Name = artist.Id+'_'+artist.Artist_Group_Name_English__c+'_'+String.valueOf(system.today())+'_Technical'+'_'+objAttachmentt.Name;

But I want to achieve this ("a002800000i5q8UAAQ_Alex_2016-08-03_Technical.png"). 

The whole code for reference:
public class extattachfile {
    Public attachment objAttachment{get;set;}
    Public attachment objAttachment2{get; set;}
    Public attachment objAttachment3{get; set;}
    Public attachment objAttachmentt{get; set;}
    Public attachment objAttachments{get; set;}
    Public Artist__c artist{get; set;}
    Public extattachfile(apexpages.standardcontroller stdCon) {
        objAttachment = new Attachment();
        objAttachment2 = new Attachment();
        objAttachment3 = new Attachment();
        objAttachmentt = new Attachment();
        objAttachments = new Attachment();
        artist= new Artist__c ();
    }
    public PageReference save() {
        Boolean checkAttachment = false;
        Boolean isValidUrl = true;
        if(artist.Id == null){
            if(artist.Website__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.Website__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Website URL.'));
                    isValidUrl = false;
                }
            }
            if(artist.Facebook__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.Facebook__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Facebook URL.'));
                    isValidUrl = false;
                }
            }
            if(artist.SoundCloud__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.SoundCloud__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Soundcloud URL.'));
                    isValidUrl = false;
                }
            }
            if(artist.YouTube__c != null){
                Pattern emailPattern = Pattern.compile('^((http|https)://)??(www[.])??([a-zA-Z0-9]|-)+?([.][a-zA-Z0-9(-|/|=|?)??]+?)+?$');
                Boolean isMatch = emailPattern.matcher(artist.YouTube__c).matches();
                if(!isMatch){
                    objAttachment.Body = null;
objAttachment2.Body = null;
objAttachment3.Body = null;
objAttachmentt.Body = null;
objAttachments.Body = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please provide a valid Youtube URL.'));
                    isValidUrl = false;
                }
            }
            if(isValidUrl){
                insert artist;
            }else{
                return null;
            }
        }
        List<Attachment> attachmentList = new List<Attachment>();
        if(objAttachment.Body != null){
            objAttachment.ParentId = artist.id;
            objAttachment.Name = artist.Id+'_'+artist.Artist_Group_Name_English__c+'_'+String.valueOf(system.today())+'_Photo1'+'_'+objAttachment.Name;
            attachmentList.add(objAttachment);
            checkAttachment = true;
        }
        if(objAttachment2.Body != null){
            objAttachment2.ParentId = artist.id;
            objAttachment2.Name = artist.Id+'_'+artist.Artist_Group_Name_English__c+'_'+String.valueOf(system.today())+'_Photo2'+'_'+objAttachment2.Name;
            attachmentList.add(objAttachment2);
            checkAttachment = true;
        }
        if(objAttachment3.Body != null){
            objAttachment3.ParentId = artist.id;
            objAttachment3.Name = artist.Id+'_'+artist.Artist_Group_Name_English__c+'_'+String.valueOf(system.today())+'_Photo3'+'_'+objAttachment3.Name;
            attachmentList.add(objAttachment3);
            checkAttachment = true;
        }          
        List<Attachment> attachmentListother = new List<Attachment>();
        if(objAttachmentt.Body != null){
            objAttachmentt.ParentId = artist.id;
            objAttachmentt.Name = artist.Id+'_'+artist.Artist_Group_Name_English__c+'_'+String.valueOf(system.today())+'_Technical'+'_'+objAttachmentt.Name;
            attachmentList.add(objAttachmentt);
        }
        if(objAttachments.Body != null){
            objAttachments.ParentId = artist.id;
            objAttachments.Name = artist.Id+'_'+artist.Artist_Group_Name_English__c+'_'+String.valueOf(system.today())+'_Stage'+'_'+objAttachments.Name;
            attachmentList.add(objAttachments);
        }
        Insert attachmentListother;
        if(attachmentList.size() > 0 && checkAttachment){
            insert attachmentList;
            attachmentList = null;
            // if successfully inserted new contact, then displays the thank you page.
            return Page.ack;
        }else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Please attach at least one photo attachment.'));
            return null;
        }             
    }
}

Thank you.