• Rohit Kumar Saini
  • NEWBIE
  • 140 Points
  • Member since 2015


  • Chatter
    Feed
  • 5
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 22
    Replies
HI All,

Here is another script tried to insert 3 related record for opprtunity for 3 month (Jan,feb,March). But not working can anyone help please.
Script
Map <Id, Opportunity> oppItems = new Map <Id, Opportunity>();
       
    list<ARRCalcualateOpportunity__c> Arropplist= new list<ARRCalcualateOpportunity__c>();
        list<Opportunity> opplist= new list<Opportunity>();
    for(opportunity opp:opplist){
       if (opp.StageName == 'Closed Won'&& opp.closeDate.month() >=1 && opp.closeDate.month() <=3 ) 
        {
          oppItems.put(opp.Id, opp);
        }
    }
    
    List<OpportunityLineItem> oliList = [select Id, Name, Product2Id, Product2.Family from 
                                         OpportunityLineItem where OpportunityId IN:oppItems.keyset()];
        
        for(OpportunityLineItem oli :oliList)
        {
             

            if(oli.product2.family == 'software Recurring__c')
                 
                //Date dt = oppobj.closedate;
                    
                     for(Integer i =1;i<=12;i++)
            {
              ARRCalcualateOpportunity__c arrOpp = new ARRCalcualateOpportunity__c();
              arropp.name = oppItems.get(oli.OpportunityId).Name;
              arropp.ownerId = oppItems.get(oli.OpportunityId).OwnerId; 
              arropp.OpportunityArr__c=oppItems.get(oli.OpportunityId).Id;  
                System.debug('arropp list'+arropp);
              Arropplist.add(arropp);
               System.debug('arropp list'+arropplist);
            }
        }
        
        if(Arropplist.size() >0){
          insert Arropplist;
        }
    

 
I created a trigger to update all related Contacts when an Account is updated. It was working perfectly and then I was asked to turn it into a regular class so that it can be called by an existing trigger...now it's not working. It looks like the code is being executed, but I'm not getting an error...Any thoughts?

Trigger that calls my class below (seems to be working fine):
/**
 * Class AccountHandler
 *
 * Trigger Handler for the Account SObject. This class implements the ITrigger
 * interface to help ensure the trigger code is bulkified and all in one place.
 */
public with sharing class CCIAccountHandler implements CCITriggerBase {

    // Constructor
    public CCIAccountHandler() {
    }

    public void bulkGeneral() {}
    /**
     * bulkBefore
     *
     * This method is called prior to execution of a BEFORE trigger. Use this to cache
     * any data required into maps prior execution of the trigger.
     */
    public void bulkBefore() {}

    public void bulkAfter() {}

    public void beforeInsert(SObject so) {}

    public void beforeUpdate(SObject oldSo, SObject so) {
        Account oldAcct = (Account) oldSo;
        Account acct = (Account) so;
        if(acct.V12C__Market__c != null && acct.V12C__Market__c.equals('MHFN')) {
            //SI-2: Send Email to the Account Owner and Quality Specialist
            CCISendEmail.sendDataIntegrationEmail(oldAcct, acct);
        }
        
    }

    /**
     * beforeDelete
     *
     * This method is called iteratively for each record to be deleted during a BEFORE
     * trigger.
     */
    public void beforeDelete(SObject so) {}

    public void afterInsert(SObject so) {
        Account acct = (Account) so;
    }

    public void afterUpdate(SObject oldSo, SObject so) {
    Account oldAcct = (Account) oldSo;
    Account acct = (Account) so;
    CCIProviderChangeAccountTracking.resaveContact(oldAcct,acct);

    }

    public void afterDelete(SObject so) {}

    /**
     * andFinally
     *
     * This method is called once all records have been processed by the trigger. Use this
     * method to accomplish any final operations such as creation or updates of other records.
     */
    public void andFinally() {}

}

My class that will run when certain fields on account is changed and will populate a datetime on contact called last changed:
public with sharing class CCIProviderChangeAccountTracking {

    public static void resaveContact(Account oldAcct, Account newAcct) {
         
        if (oldAcct.Phone != newAcct.Phone ||
                oldAcct.ShippingAddress != newAcct.ShippingAddress ||
                oldAcct.V12C__PR_Practice_Tax_ID_Number__c != newAcct.V12C__PR_Practice_Tax_ID_Number__c ||
                oldAcct.BillingAddress != newAcct.BillingAddress) {
            
            List<Contact> toSave = new List <Contact>();
            for (Contact con : [SELECT Id, Scorecard_Modified_Date__c FROM Contact WHERE Primary_Practicing_Location_Lookup__r.ParentId =:newAcct.Id]) {
                con.Last_Changed_Date__c = Datetime.NOW();
                toSave.add(con);    
            }
            system.debug('-------------' + toSave.size());
            
            try {
            update toSave;}
            catch(exception e){system.debug(e.getMessage());}
        }
    }
}

In the debug log I can see where it calls the class but isn't showing the system.debug
HI,

I have three fields   start__c, end__c and actual_date__c, Iam looking to write validation rule,
1. end date need to be less than start date
2. Start date can't be more than end date.
3. Actual date need to be between start date and end date.
Note: All are date fields and actual date is optional to save record
i have tried it. its not working
IF(
	ISBLANK(actual_date__c),			
			(
				And
				(
					(
					 start__c > actual_date__c
					),   
                    (
					  actual_date__c < End__c
					)
                )			
            )		
			,		
		   (
            And
            (
                (
                    start__c > End__c
                ),   
                (
                End__c < start__c
                )
            )
         )
)


 
User-added image
 I have grouped my account with respective account owner but i have queried in my for loop which is not a a best practice. Can Someone give me optimized version of my code. It will be of great help. Below is my Apex Class.
 
public with sharing class MapofAccountsExt{

 public List<Account> Accountlist{get;set;}
 public Map<String,List<Account>> AccountMap{get;set;}
 public Map<String,List<User>> UserMap{get;set;}
 
 public MapofAccountsExt(ApexPages.StandardController controller) 
    {
        thismethod();
    }

 public PageReference thismethod()
    {
      Accountlist = new List<Account>();
      Accountlist = [select id,AccountNumber,name,owner.name,email__c,Active__c from Account];
        Set<id> setofids = new Set<id>();
        for(Account thisAccount : Accountlist)
        {
            setofids.add(thisAccount.ownerid);
            system.debug('the whole set of id '+setofids);
        }
        list<Account> newAccountList = new List<Account>();
        
        newAccountList= [Select id,AccountNumber,name,ownerid,owner.name,email__c,Active__c from Account where ownerid in:setofids];
        system.debug('this expense id for the list '+newAccountList);
        
        
        AccountMap= new Map<String,List<Account>>();
        List<Account> accList = new List<Account>();
        for(Account thisAccountid: newAccountList)
        {
                accList = [select id,AccountNumber,name,ownerid,owner.name,email__c,Active__c from Account where ownerid=:thisAccountid.ownerid and (id = '0016F00002PEDkg' or id ='0016F00002PEECU' or id='0016F00002PF4Bt' or id = '0016F00002PF5UK')];
                AccountMap.put(thisAccountid.owner.name,accList);
                system.debug('this Account id '+AccountMap);

        }
        List<User> Userlist = new List<User>();
        Userlist = [select id,name,email from User];
        UserMap = new Map<String,List<User>>();
        List<User> Userlist1 = new List<User>();
        for(User thisUser1 : Userlist)
        {
            Userlist1 = [select id,name,email from User where email=:thisuser1.email limit 1];
            UserMap.put(thisuser1.name,Userlist1);
        }
        
        
        return null;       
    }
}

 
can anyone please modify my code . 

Under an account , there should be only one contact with name phone . if i create one more contact with same name then the error shoulp appear . my code :
trigger PreventDuplicateContactMap on Contact (before insert,before update) {
    
    if(trigger.isInsert || trigger.isUpdate)
    {
        Map<Id,List<Contact>> accMap = new Map<Id,List<Contact>>();
        List<Contact> contactList;
        
        for(Contact c: [Select Id,LastName,phone,Email,accountId from Contact where AccountId !=Null ]){
            if(accMap.containsKey(c.accountId)){   
                accMap.get(c.accountId).add(c);
                  system.debug('If loop ===');
            }
            else{
            system.debug('else loop ===');
                contactList = new List<Contact>();
                contactList.add(c);
                accMap.put(c.accountId,contactList);
            }       
        }
        
        for (Contact c : Trigger.new) 
        {
        if(accMap.containsKey(c.accountId))
            {
                for(Contact con : accMap.get(c.accountId))
                {
                if( (c.Phone== con.Phone) || ( c.LastName == con.LastName ) )
                    {
                        c.addError('Duplicate Contact.......... ');
                    }
                }
            }
        }
    }
}
User-added image


Object.coerceIntoArray()@https://callpass.lightning.force.com/auraCmpDef?aura.app=markup://one:one&aura.mode=PROD&_au=qFI9rOLlNPR9yNNEp1-iig&_ff=DESKTOP&_l=true&_lrmc=1730203071&_l10n=en_US&_c=false&_style=-1720540562&_density=VIEW_ONE&Dashboard_Pal=DashboardPal&analyticsHome=analyticsDataProvider,createNewFolderEvent,sharedServices&calendar=refresh&dashboards=linkCard&desktopDashboards=dashboard,embeddedDashboard,feedPanel,focusFeedButtonEvent,metricServiceEvent&folder=baseIntegration,breadcrumb,breadcrumbItem,configRetriever,forceActionProxy,listView,listViewDataLoadingComplete,pickerAction,pickerActionComplete,pickerDialog,pickerDialogPanel,pickerNavigate,pickerSelection,searchResult,utils&force=actionRow,calendarDateLibrary,calendarLibrary,calendarStoreCreate,calendarStoreUpdate,changeCalendarType,emptyState,eventEndDateTimeUpdate,eventStartDateTimeUpdate,menuTriggerIcon,recordLayoutList&home=eventCardDataChanged,eventCardDataManager,eventCardStencil,eventContainer,homeCard,notifyLastAllDayItemOnEventCard,outputLookupWithPreviewWithoutProfilePic,recentRecordContainer,recentsItemStencil&ltng=afterScriptsLoaded,beforeLoadingResources,require&offline=draftChange,sash&reports=sharedServices&runtime_sales_activities=activityRecurrenceLibrary,activityRelatedListRow,activitySubject,lastOpenedStatusForTask,taskCardEmpty,taskChangeStatusFailure,taskCommon,taskContent,taskContentFields,taskContentInner,taskContentRefresh,taskHighlights,taskInlineEditRecordDataChanged,taskRecordUpdated,taskRow,taskStatus,taskUpdateLastOpenStatus,tasksReturned,todayTaskContainer,todayTasksCardDataChanged,todayTasksCardDataProvider,todayTasksFilter,todayTasksFilterTypeChangedEvent,todayTasksLibrary,todayTasksList&sfa=checkboxButton,ping&ui=infiniteListRow&_uid=-1394731863:357:438
init()@https://callpass.lightning.force.com/auraCmpDef?aura.app=markup://one:one&aura.mode=PROD&_au=qFI9rOLlNPR9yNNEp1-iig&_ff=DESKTOP&_l=true&_lrmc=1730203071&_l10n=en_US&_c=false&_style=-1720540562&_density=VIEW_ONE&Dashboard_Pal=DashboardPal&analyticsHome=analyticsDataProvider,createNewFolderEvent,sharedServices&calendar=refresh&dashboards=linkCard&desktopDashboards=dashboard,embeddedDashboard,feedPanel,focusFeedButtonEvent,metricServiceEvent&folder=baseIntegration,breadcrumb,breadcrumbItem,configRetriever,forceActionProxy,listView,listViewDataLoadingComplete,pickerAction,pickerActionComplete,pickerDialog,pickerDialogPanel,pickerNavigate,pickerSelection,searchResult,utils&force=actionRow,calendarDateLibrary,calendarLibrary,calendarStoreCreate,calendarStoreUpdate,changeCalendarType,emptyState,eventEndDateTimeUpdate,eventStartDateTimeUpdate,menuTriggerIcon,recordLayoutList&home=eventCardDataChanged,eventCardDataManager,eventCardStencil,eventContainer,homeCard,notifyLastAllDayItemOnEventCard,outputLookupWithPreviewWithoutProfilePic,recentRecordContainer,recentsItemStencil&ltng=afterScriptsLoaded,beforeLoadingResources,require&offline=draftChange,sash&reports=sharedServices&runtime_sales_activities=activityRecurrenceLibrary,activityRelatedListRow,activitySubject,lastOpenedStatusForTask,taskCardEmpty,taskChangeStatusFailure,taskCommon,taskContent,taskContentFields,taskContentInner,taskContentRefresh,taskHighlights,taskInlineEditRecordDataChanged,taskRecordUpdated,taskRow,taskStatus,taskUpdateLastOpenStatus,tasksReturned,todayTaskContainer,todayTasksCardDataChanged,todayTasksCardDataProvider,todayTasksFilter,todayTasksFilterTypeChangedEvent,todayTasksLibrary,todayTasksList&sfa=checkboxButton,ping&ui=infiniteListRow&_uid=-1394731863:351:211


File name is Object.coerceIntoArray()@https://callpass.lightning.force.com/auraCmpDef?aura.app=markup://one:one&aura.mode=PROD&_au=qFI9rOLlNPR9yNNEp1-iig&_ff=DESKTOP&_l=true&_lrmc=1730203071&_l10n=en_US&_c=false&_style=-1720540562&_density=VIEW_ONE&Dashboard_Pal=DashboardPal&analyticsHome=analyticsDataProvider,createNewFolderEvent,sharedServices&calendar=refresh&dashboards=linkCard&desktopDashboards=dashboard,embeddedDashboard,feedPanel,focusFeedButtonEvent,metricServiceEvent&folder=baseIntegration,breadcrumb,breadcrumbItem,configRetriever,forceActionProxy,listView,listViewDataLoadingComplete,pickerAction,pickerActionComplete,pickerDialog,pickerDialogPanel,pickerNavigate,pickerSelection,searchResult,utils&force=actionRow,calendarDateLibrary,calendarLibrary,calendarStoreCreate,calendarStoreUpdate,changeCalendarType,emptyState,eventEndDateTimeUpdate,eventStartDateTimeUpdate,menuTriggerIcon,recordLayoutList&home=eventCardDataChanged,eventCardDataManager,eventCardStencil,eventContainer,homeCard,notifyLastAllDayItemOnEventCard,outputLookupWithPreviewWithoutProfilePic,recentRecordContainer,recentsItemStencil&ltng=afterScriptsLoaded,beforeLoadingResources,require&offline=draftChange,sash&reports=sharedServices&runtime_sales_activities=activityRecurrenceLibrary,activityRelatedListRow,activitySubject,lastOpenedStatusForTask,taskCardEmpty,taskChangeStatusFailure,taskCommon,taskContent,taskContentFields,taskContentInner,taskContentRefresh,taskHighlights,taskInlineEditRecordDataChanged,taskRecordUpdated,taskRow,taskStatus,taskUpdateLastOpenStatus,tasksReturned,todayTaskContainer,todayTasksCardDataChanged,todayTasksCardDataProvider,todayTasksFilter,todayTasksFilterTypeChangedEvent,todayTasksLibrary,todayTasksList&sfa=checkboxButton,ping&ui=infiniteListRow&_uid=-1394731863:357:438
init()@https://callpass.lightning.force.com/auraCmpDef?aura.app=markup://one:one&aura.mode=PROD&_au=qFI9rOLlNPR9yNNEp1-iig&_ff=DESKTOP&_l=true&_lrmc=1730203071&_l10n=en_US&_c=false&_style=-1720540562&_density=VIEW_ONE&Dashboard_Pal=DashboardPal&analyticsHome=analyticsDataProvider,createNewFolderEvent,sharedServices&calendar=refresh&dashboards=linkCard&desktopDashboards=dashboard,embeddedDashboard,feedPanel,focusFeedButtonEvent,metricServiceEvent&folder=baseIntegration,breadcrumb,breadcrumbItem,configRetriever,forceActionProxy,listView,listViewDataLoadingComplete,pickerAction,pickerActionComplete,pickerDialog,pickerDialogPanel,pickerNavigate,pickerSelection,searchResult,utils&force=actionRow,calendarDateLibrary,calendarLibrary,calendarStoreCreate,calendarStoreUpdate,changeCalendarType,emptyState,eventEndDateTimeUpdate,eventStartDateTimeUpdate,menuTriggerIcon,recordLayoutList&home=eventCardDataChanged,eventCardDataManager,eventCardStencil,eventContainer,homeCard,notifyLastAllDayItemOnEventCard,outputLookupWithPreviewWithoutProfilePic,recentRecordContainer,recentsItemStencil&ltng=afterScriptsLoaded,beforeLoadingResources,require&offline=draftChange,sash&reports=sharedServices&runtime_sales_activities=activityRecurrenceLibrary,activityRelatedListRow,activitySubject,lastOpenedStatusForTask,taskCardEmpty,taskChangeStatusFailure,taskCommon,taskContent,taskContentFields,taskContentInner,taskContentRefresh,taskHighlights,taskInlineEditRecordDataChanged,taskRecordUpdated,taskRow,taskStatus,taskUpdateLastOpenStatus,tasksReturned,todayTaskContainer,todayTasksCardDataChanged,todayTasksCardDataProvider,todayTasksFilter,todayTasksFilterTypeChangedEvent,todayTasksLibrary,todayTasksList&sfa=checkboxButton,ping&ui=infiniteListRow&_uid=-1394731863:351:211
HI All,

Here is another script tried to insert 3 related record for opprtunity for 3 month (Jan,feb,March). But not working can anyone help please.
Script
Map <Id, Opportunity> oppItems = new Map <Id, Opportunity>();
       
    list<ARRCalcualateOpportunity__c> Arropplist= new list<ARRCalcualateOpportunity__c>();
        list<Opportunity> opplist= new list<Opportunity>();
    for(opportunity opp:opplist){
       if (opp.StageName == 'Closed Won'&& opp.closeDate.month() >=1 && opp.closeDate.month() <=3 ) 
        {
          oppItems.put(opp.Id, opp);
        }
    }
    
    List<OpportunityLineItem> oliList = [select Id, Name, Product2Id, Product2.Family from 
                                         OpportunityLineItem where OpportunityId IN:oppItems.keyset()];
        
        for(OpportunityLineItem oli :oliList)
        {
             

            if(oli.product2.family == 'software Recurring__c')
                 
                //Date dt = oppobj.closedate;
                    
                     for(Integer i =1;i<=12;i++)
            {
              ARRCalcualateOpportunity__c arrOpp = new ARRCalcualateOpportunity__c();
              arropp.name = oppItems.get(oli.OpportunityId).Name;
              arropp.ownerId = oppItems.get(oli.OpportunityId).OwnerId; 
              arropp.OpportunityArr__c=oppItems.get(oli.OpportunityId).Id;  
                System.debug('arropp list'+arropp);
              Arropplist.add(arropp);
               System.debug('arropp list'+arropplist);
            }
        }
        
        if(Arropplist.size() >0){
          insert Arropplist;
        }
    

 
my requirement is when i will add comment in case feed comment then in case field which i created (latestComment) show latest comment.

here is my code: for Trigger

trigger latestCommentTrigger on Case (before insert, after update) {
    for(Case c : trigger.new) {
        if(c.Comments == Null){
            c.Comments.adderror('enter comment');
        }
        c.Comments = c.Latest_Comment__c;
        
            }
}


i didnot getting output of this code can any one help me out of this question.
This is my query.
SOBject acc = [Select Id, Name, (Select Id, Account.Parent.Parent.Name, Name from Contacts__r) from Sales_Location__c where Id ='a005j000009xxxBAxU']; 
Contact abc =(Contact)(acc.getSobjects('Contacts__r')).get(0); System.debug(abc.get('Account.Parent.Parent.Name'));

But instead of using get() if I  directly use abc.Account.Parent.Parent.Name , I am getting result. But I don't know why  my code fails in case of get().  In Actual scenario abc is of SObject type that's why I need to use get() here.

 
I have 2 methods When i click on button  first method creating contact and second one creating site.externaluser and then login site.
how can i handle this in lightning component.
How can i change the excuting transaction?
Please let me know the solution

 
Hello, 

I need set a mask on my lightning input text, to get de Data Format. (YYYY-MM-DD)
Can anyone could help me?

 
Hy Folks,

I need pass text of  picklist to insert a record of case by component lightning .

I need the text instead of the value, by the way, how can I pass on the text and the value?


Code


Component.cmp

 <aura:attribute name="caseObj" type="case" default="{'sobjectType': 'Case',
                         'AccountId': '',
                         'MSISDN__c': '',
                         'Status': '',
                         'Origin': '' ,
                          'Motivo1__c': '' 
                                                 
                       }"/>




     
<label>Montadora</label>
       <force:inputField aura:id="AccountId"  value="{!v.caseObj.AccountId}"/>
       
</div>

    

<div class="form-group">
            <label>MSISDN</label>
            <ui:inputText class="form-control" value="{!v.caseObj.MSISDN__c}"/>
</div>  
    
    
    
<div class="form-group">
            <label>Status</label>
            <force:inputField aura:id="Status"  value="{!v.caseObj.Status}"/>
</div>   
       

<div class="form-group">
            <label>Origem</label>
            <force:inputField aura:id="Origin"  value="{!v.caseObj.Origin}"/>
    
</div> 


<!--   PICKLIST  I NEED GET TEXT OF SELECTION  -->
<!--   ---------------------------------------------------------------  -->

<lightning:layoutItem size="12" padding="around-small">    
        <lightning:select aura:id="Motivo1__c"
                          value="{!v.caseObj.Motivo1__c}"
                          name="motivo1"
                          label="Motivo 1"
                          onchange="{!c.onControllerFieldChange}">
            <aura:iteration items="{!v.listMotivos1}" var="val">
                <option value="{!val.MasterLabel}">{!val.DependentFieldTextPtBR__c}</option>
            </aura:iteration>
        </lightning:select>
    </lightning:layoutItem>


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

Controller.js

    create: function(component, event, helper)    {
        
        console.log('Create record');
    
       
        
        
        
        var caseObj = component.get("v.caseObj");
        
        
        var action = component.get("c.createRecord");
      
        
        action.setParams({
            caseObj : caseObj
        });


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

ClassController.apxc

 @AuraEnabled
    public static void createRecord (Case caseObj){
        
        
        
        
        try{
            System.debug('NovoCasoComponentController::createRecord::caseObj'+ caseObj);
            
            if(caseObj != null){
                
            
                caseObj.Account = null;
                insert caseObj;
            }
            
        } catch (Exception ex){
            
        }



Thanks!
 
Hi I have added lightning quick actions on page layout but not visible in lightning. I have added actions post, log a call, email, new task, new event.
Any sugessions ?
User-added image
Hello, 

I have a simple apex class that looks up unassigned leads (the # currently in the default queue) and posts the current count to Slack via webhook. The class works fine, however, I scheduled it to run twice per day and it keeps posting the same number each time -- what I believe is the number of leads that were in the queue at the time of scheduling... not at the time it runs.

I'm not sure if I'm completely missing something here or what, but I don't see how/why that would be the case. Also... how do I get around this? Create a class to schedule which simply calls the other class? Code below...

Thank you! 
 
public class PostLeadCounttoSlack implements schedulable { 

    private static final String slackURL = 'https://hooks.slack.com/services/T0xxxxxxxxxxxxxxxxxxxxxxx';
    AggregateResult res = [SELECT count(id) From Lead where OwnerId in (SELECT Id from Group where type='Queue' and Name='Default Lead Queue')];
    Integer lc = integer.valueof(res.get('expr0'));

    public void execute(SchedulableContext sc){

    Map<String,Object> msg = new Map<String,Object>();
        msg.put('text', 'There are ' + lc + ' leads in the queue.');
        msg.put('mrkdwn', true);
        msg.put('link_names', '1');
        String body = JSON.serialize(msg);    
        System.enqueueJob(new QueueableSlackCall(slackURL, 'POST', body));
    }

    public class QueueableSlackCall implements System.Queueable, Database.AllowsCallouts {
         
        private final String url;
        private final String method;
        private final String body;
         
        public QueueableSlackCall(String url, String method, String body) {
            this.url = url;
            this.method = method;
            this.body = body;
        }
         
        public void execute(System.QueueableContext ctx) {
            HttpRequest req = new HttpRequest();
            req.setEndpoint(url);
            req.setMethod(method);
            req.setBody(body);
            Http http = new Http();
            HttpResponse res = http.send(req);
        }
 
    }    
}
Hi all.
I have jquery-html code that work well out of SFDC.
Now I'm trying to move it to SFDC VF.

Currently, without action, jquery works well. However, when I add Actionfunction, it stoped.
I will show you code.

Jquery
<script> 
// Slide Up
$(document).ready(function(){
    $("#btn2").click(function(){
        $("#last").slideUp("slow");
      $("#end").show();
       });
  });
</script>

VF
<apex:form>
	<apex:actionFunction name="runSave" action="{!saveResponse}"/>
  </apex:form>
  	<button class="btn	btn-primary	btn-block" id="btn2" onclick="runSave()"> Submit </button>

I cannot use Command Button because, Command Button does not accept jquery using id("btn2").
When I use commandbutton instead of button, it doesn't work.

But I need to run method in Controller, so I tried to use actionfunction.
However, when I run above code, slide up work at the first time and during sliding, page reloaded and slidnig cannot be completed.
I need to complete sliding and stop at div section sliding up completed.

Anybody help me approach?

Thanks in advance.
 
I have a lookup relationship between Accounts and Leads (account__c) and I would like to create a before insert, before update (I think) trigger to transfer the Account Name to the Company name field. I just don't even know where to begin.  

Is this how you would do it? If so, could someone point me in the right direction or help me? 
I created a trigger to update all related Contacts when an Account is updated. It was working perfectly and then I was asked to turn it into a regular class so that it can be called by an existing trigger...now it's not working. It looks like the code is being executed, but I'm not getting an error...Any thoughts?

Trigger that calls my class below (seems to be working fine):
/**
 * Class AccountHandler
 *
 * Trigger Handler for the Account SObject. This class implements the ITrigger
 * interface to help ensure the trigger code is bulkified and all in one place.
 */
public with sharing class CCIAccountHandler implements CCITriggerBase {

    // Constructor
    public CCIAccountHandler() {
    }

    public void bulkGeneral() {}
    /**
     * bulkBefore
     *
     * This method is called prior to execution of a BEFORE trigger. Use this to cache
     * any data required into maps prior execution of the trigger.
     */
    public void bulkBefore() {}

    public void bulkAfter() {}

    public void beforeInsert(SObject so) {}

    public void beforeUpdate(SObject oldSo, SObject so) {
        Account oldAcct = (Account) oldSo;
        Account acct = (Account) so;
        if(acct.V12C__Market__c != null && acct.V12C__Market__c.equals('MHFN')) {
            //SI-2: Send Email to the Account Owner and Quality Specialist
            CCISendEmail.sendDataIntegrationEmail(oldAcct, acct);
        }
        
    }

    /**
     * beforeDelete
     *
     * This method is called iteratively for each record to be deleted during a BEFORE
     * trigger.
     */
    public void beforeDelete(SObject so) {}

    public void afterInsert(SObject so) {
        Account acct = (Account) so;
    }

    public void afterUpdate(SObject oldSo, SObject so) {
    Account oldAcct = (Account) oldSo;
    Account acct = (Account) so;
    CCIProviderChangeAccountTracking.resaveContact(oldAcct,acct);

    }

    public void afterDelete(SObject so) {}

    /**
     * andFinally
     *
     * This method is called once all records have been processed by the trigger. Use this
     * method to accomplish any final operations such as creation or updates of other records.
     */
    public void andFinally() {}

}

My class that will run when certain fields on account is changed and will populate a datetime on contact called last changed:
public with sharing class CCIProviderChangeAccountTracking {

    public static void resaveContact(Account oldAcct, Account newAcct) {
         
        if (oldAcct.Phone != newAcct.Phone ||
                oldAcct.ShippingAddress != newAcct.ShippingAddress ||
                oldAcct.V12C__PR_Practice_Tax_ID_Number__c != newAcct.V12C__PR_Practice_Tax_ID_Number__c ||
                oldAcct.BillingAddress != newAcct.BillingAddress) {
            
            List<Contact> toSave = new List <Contact>();
            for (Contact con : [SELECT Id, Scorecard_Modified_Date__c FROM Contact WHERE Primary_Practicing_Location_Lookup__r.ParentId =:newAcct.Id]) {
                con.Last_Changed_Date__c = Datetime.NOW();
                toSave.add(con);    
            }
            system.debug('-------------' + toSave.size());
            
            try {
            update toSave;}
            catch(exception e){system.debug(e.getMessage());}
        }
    }
}

In the debug log I can see where it calls the class but isn't showing the system.debug
HI,

I have three fields   start__c, end__c and actual_date__c, Iam looking to write validation rule,
1. end date need to be less than start date
2. Start date can't be more than end date.
3. Actual date need to be between start date and end date.
Note: All are date fields and actual date is optional to save record
i have tried it. its not working
IF(
	ISBLANK(actual_date__c),			
			(
				And
				(
					(
					 start__c > actual_date__c
					),   
                    (
					  actual_date__c < End__c
					)
                )			
            )		
			,		
		   (
            And
            (
                (
                    start__c > End__c
                ),   
                (
                End__c < start__c
                )
            )
         )
)


 
User-added image
 I have grouped my account with respective account owner but i have queried in my for loop which is not a a best practice. Can Someone give me optimized version of my code. It will be of great help. Below is my Apex Class.
 
public with sharing class MapofAccountsExt{

 public List<Account> Accountlist{get;set;}
 public Map<String,List<Account>> AccountMap{get;set;}
 public Map<String,List<User>> UserMap{get;set;}
 
 public MapofAccountsExt(ApexPages.StandardController controller) 
    {
        thismethod();
    }

 public PageReference thismethod()
    {
      Accountlist = new List<Account>();
      Accountlist = [select id,AccountNumber,name,owner.name,email__c,Active__c from Account];
        Set<id> setofids = new Set<id>();
        for(Account thisAccount : Accountlist)
        {
            setofids.add(thisAccount.ownerid);
            system.debug('the whole set of id '+setofids);
        }
        list<Account> newAccountList = new List<Account>();
        
        newAccountList= [Select id,AccountNumber,name,ownerid,owner.name,email__c,Active__c from Account where ownerid in:setofids];
        system.debug('this expense id for the list '+newAccountList);
        
        
        AccountMap= new Map<String,List<Account>>();
        List<Account> accList = new List<Account>();
        for(Account thisAccountid: newAccountList)
        {
                accList = [select id,AccountNumber,name,ownerid,owner.name,email__c,Active__c from Account where ownerid=:thisAccountid.ownerid and (id = '0016F00002PEDkg' or id ='0016F00002PEECU' or id='0016F00002PF4Bt' or id = '0016F00002PF5UK')];
                AccountMap.put(thisAccountid.owner.name,accList);
                system.debug('this Account id '+AccountMap);

        }
        List<User> Userlist = new List<User>();
        Userlist = [select id,name,email from User];
        UserMap = new Map<String,List<User>>();
        List<User> Userlist1 = new List<User>();
        for(User thisUser1 : Userlist)
        {
            Userlist1 = [select id,name,email from User where email=:thisuser1.email limit 1];
            UserMap.put(thisuser1.name,Userlist1);
        }
        
        
        return null;       
    }
}

 
BREAKDOWN 
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value. 

Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP ! 
trigger Updatecampaign on pse__Expense_Report__c (before insert,before Update) {

// Local catches for bulkified data
    private map<Id, pse__Proj__c> projMap = new map<Id, pse__Proj__c>();      

   for (pse__Expense_Report__c er: Trigger.new) (

   		projectIds.add(er.Campaign_Expense__c);
   		}

   		for{pse__Proj__c pro: [select id, Campaign__c from pse__Proj__c where Campaign__c in :projectIds]}
   		{
   		projMap.put(pro.Campaign__c, projMap)
   		}

   			for (pse__Expense_Report__c er : Trigger.new)
   			{
   			er.Campaign_Expense__c=projMap.get(er.Campaign_Expense__c).Id;
   			
   			}
   		}

 
Hi,
I'm new to development and need to create a trigger which will call an API to GET information from a third party app, then use the data retrieved to update a couple of picklist values in salesforce on the corresponding record. The record's unique identifier is the email address, which it will use to identify which record in the third party app to retrieve the data from.  How would I write the class to call the API and where would I begin with creating the API? I've exhausted the resources and I'm still a little lost. 
The trigger would be on the account object and would run when a picklist value changes (so a record is updated), and I need it to also update 2 picklist values on the record with the values retrieved from the callout. 

Any help is much appreciated,
Many Thanks :)
Natasha 
can anyone please modify my code . 

Under an account , there should be only one contact with name phone . if i create one more contact with same name then the error shoulp appear . my code :
trigger PreventDuplicateContactMap on Contact (before insert,before update) {
    
    if(trigger.isInsert || trigger.isUpdate)
    {
        Map<Id,List<Contact>> accMap = new Map<Id,List<Contact>>();
        List<Contact> contactList;
        
        for(Contact c: [Select Id,LastName,phone,Email,accountId from Contact where AccountId !=Null ]){
            if(accMap.containsKey(c.accountId)){   
                accMap.get(c.accountId).add(c);
                  system.debug('If loop ===');
            }
            else{
            system.debug('else loop ===');
                contactList = new List<Contact>();
                contactList.add(c);
                accMap.put(c.accountId,contactList);
            }       
        }
        
        for (Contact c : Trigger.new) 
        {
        if(accMap.containsKey(c.accountId))
            {
                for(Contact con : accMap.get(c.accountId))
                {
                if( (c.Phone== con.Phone) || ( c.LastName == con.LastName ) )
                    {
                        c.addError('Duplicate Contact.......... ');
                    }
                }
            }
        }
    }
}
I am getting the  error at following line
 User-added image
component.set("v.items",items);

Controller code: 
({
    doInit : function(component, event, helper){
        var getItemsAction = component.get("c.getItems");
        getItemsAction.setCallback(scope, function(response){
            var state = response.getState();
            if(state=="SUCCESS"){
                var items = response.getReturnValue();
                component.set("v.items",items);
            }
            
        });
        $A.enqueueAction(getItemsAction);
        
    },
    clickCreateItem : function(component, event, helper) {
           helper.createItem(component);
    }
})

and Helper
({
    createItem : function(component) {
        var newItem = component.get("v.newItem");
        var newItem1 = JSON.parse(JSON.stringify(newItem));
        var items = component.get("v.items");
        items.push(newItem1);
        component.set("v.items",items);
        component.set("v.newItem", {'sobjectType':'Camping_Item__c','Name':'','Quantity__c':0,'Price__c':0,'Packed__c':false});
        /*var saveItemAction = component.get("c.saveItem");
        saveItemAction.setParams({campingItem:newItem1});
        saveItemAction.setCallback(scope, function(response){
            var state = response.getState(); alert(state);
            if(state=="SUCCESS"){
            }
        });
        $A.enqueueAction(saveItemAction); */
    }
})

coponent code
<aura:component controller="CampingListController">
    <aura:attribute name="newItem" Type="Camping_Item__c" default="{'sObjectType':'Camping_Item__c','Quantity__c':0,'Price__c':0,'Name':'test'}"/>
    <aura:attribute name="items" Type="Camping_Item__c[]" />
    <aura:handler name="init" action="{!c.doInit}" value="{!this}" />
    
    <ol>
        <li>Bug Spray</li>
        <li>Bear Repellant</li>
        <li>Goat Food</li>
    </ol>
    
    <form class="slds-form--stacked" aura:id="campingform">
        <lightning:input  aura:id="newItemName" label="Camping Item Name" value="{!v.newItem.Name}" />
        <lightning:input aura:id="newItemPrice" label="Price" value="{!v.newItem.Price__c}" Type="number"
                         namename="campingPrice"
                         min="0.1"
                         formatter="currency"
                         step="0.1"
                         messageWhenRangeUnderflow="Enter an Price that's at least 0.1."/>
        <lightning:input aura:id="newItemQuantity" label="Quantity" type="Integer" value="{!v.newItem.Quantity__c}" min="1"/>
        <lightning:input aura:id="newItemPacked" label ="Packed" checked="{!v.newItem.Packed__c}" type="checkbox"/>
        <lightning:button label="Submit" onclick="{! c.clickCreateItem}" />
    </form>
    
    <div class ="slds-card slds-p-top--meduim">
        <header class ="slds-card__header">
            <h3 class = "slds-text-heading--small">Items</h3>
        </header>
        <section class ="slds-card__body">
            <div id="list" class = "row">
                <aura:iteration items="{!v.items}" var="itemVar">
                    <c:campingListItem item="{!itemVar}"/>
                </aura:iteration>
            </div>
        </section>
    </div>
</aura:component>



Please help me on the issue.