• Abhishek Bansal
  • ALL STAR
  • 8537 Points
  • Member since 2015
  • Software Developer
  • Metacube Softwares Pvt Ltd


  • Chatter
    Feed
  • 281
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 1
    Questions
  • 1416
    Replies
Hi,
I have a Lightning component form which consists of many fields and parts. What I need is to refresh a particular part of the Lightning component without refreshing the whole component.
User-added image
In the above image I have the Fetch Contact Info in one whole div so when I click the refresh icon it should empty all the fields if the values are present. Is there any possibility to do that, any information will be helpful.

Thanks,
Bharath Kumar Thota
Hi,
I am trying to create an alert on a specific date field on an object that is time-based related. 

The issue is that both Process Builder and WorkFlow only fire when an object is updated or created, but not when a date becomes Today (naturally, without editing or creating the object's fields).

Here are my 3 separate use cases (each needs its own solution, but has the same problem):
1. On a custom object called "Project" we have a date-field called KICKOFF DATE.  When the date becomes today, we want an email alert to send out a reminder that today is kickoff date for this project.
2. When an Opp is in Stage 1 and it's Age = 60 days, we want to send an email alert that the Opportunity is 60 days old (from created date) and is in stage 1.
3. When an Opportunity is approaching the Close Date and is in a lower Stage, we want an alert to fire that says warns it is approaching.
So now I think I need a trigger to help fire this in Process Builder. 

Anybody ever had this need before or accomplished this?
Hello,

I have a custom object called Account_Addresses__c that has a master-detail relationship to the Account object. That object houses address information as each account may have multiple addresses, however, only one of those addresses can be marked "current". I have a field on the custom object called Current__c to capture which address is current.

I created a trigger (below) to mark and unmark the addresses whena user changes the Current__c field and I am trying (in the same trigger) to then update a checkbox field on the Account record (Left_CA__c) if the newly selected current address is not in California and the Left_CA__c field on the Account was not already checked off.  However, this part of my trigger does not seem to be firing properly. From the logs, it looks like my Account map is initially null but then somehow gets populated. What am I doing wrong?

DEBUG|@@@### - parentAcct Map: {}
AcctAddrPrimCurr on Account_Addresses trigger event AfterUpdate|__sfdc_trigger/AcctAddrPrimCurr 0
DEBUG|@@@### - parentAcct Map: {0011h00000lC9vvAAC=Account:{Id=0011h00000lC9vvAAC, Left_NY__c=false}}
 
trigger AcctCurr on Account_Addresses__c(after update,after insert) {


//Update Account Address for Current
    List<Account_Addresses__c> acctAddr2 = new List<Account_Addresses__c>();

// Sets holding Account IDs (unique) and Addresses IDs (unique)
	Set<Id> CurrAcctIds = new Set<Id>();
	Set<Id> acctAddrIds2 = new Set<Id>();

    for(Account_Addresses__c aa2 : trigger.new){
       if(aa2.Current__c == TRUE){
            CurrAcctIds.add(aa2.Account__c);
			acctAddrIds2.add(aa2.id);
        }
    }

// get the records from Account Addresses that are under the Account but not meant to be Current

    acctAddr2 = [SELECT Id,Current__c
                FROM Account_Addresses__c
                WHERE Current__c = TRUE AND Account__c IN:CurrAcctIds AND Id NOT IN:acctAddrIds2];
	for(Account_Addresses__c aa2:acctAddr2)
		aa2.Current__c = FALSE;
    update acctAddr2;

//update related Account to check if new current address is not CA
	Map<ID, Account> parentAcct = new Map<ID, Account>();

    parentAcct = new Map<Id, Account>([SELECT Id, Left_CA__c, Date_Left_CA__c 
                                       FROM Account 
                                       WHERE Id IN :CurrAcctIds AND Left_CA__c != TRUE]);
system.debug('@@@### - parentAcct Map:  '+parentAcct);
    if(parentAcct != null){
    
	for(Account_Addresses__c ca: trigger.new){
    	Account myParentAcct = parentAcct.get(ca.Account__c);
        if(ca.Current__c == TRUE && ca.State__c != 'CA'){
            myParentAcct.Left_CA__C = TRUE;
            myParentAcct.Date_Left_CA__C = system.TODAY();
        }
    }
}
}

 
Hi All,

I have written a trigger but i am unable to avoid the for loop inside the for loop. Can anyone please suggest me that how can i resolve this by using map or any other collection.

trigger OfferPartnerTrigger on Offer_Partner__c (After Insert,After Update,After Delete) {
    set<id>OfferId=new set<id>();
    If(Trigger.IsAfter && Trigger.IsInsert || Trigger.IsUpdate){
        for(Offer_Partner__c offr:Trigger.New){
            OfferId.add(offr.Offer__c);
        } 
    }     
    
    If(Trigger.IsAfter && Trigger.IsDelete){
        for(Offer_Partner__c offr:Trigger.old){
            OfferId.add(offr.Offer__c);
        }
    }  
    try{
        MAP<Id,Offers__c> offerMap = new MAP<Id,Offers__c>();
        list<string>partnerIdList=new list<string>();
        list<Offers__c>ofrList=new list<Offers__c>();
        list<Offers__c>offerList=[select id,Partners__c,(select id,name,Consumer__r.PartnerId__c from Offer_Partners__r) from Offers__c where id=:OfferId and id in (select Offer__c from Offer_Partner__c)];
        system.debug('offerList***'+offerList);            
        for(Offers__c ofr:offerList){
            for(Offer_Partner__c oosf:ofr.Offer_Partners__r){
                partnerIdList.add(oosf.Consumer__r.PartnerId__c);
                
                string allstring = string.join(partnerIdList,',');
                ofr.Partners__c=allstring;
                system.debug('oosf.Consumer__r.PartnerId__c***'+oosf.Consumer__r.PartnerId__c);            
                
                ofrList.add(ofr);
            }
            system.debug('partnerIdList***'+partnerIdList);            
        }

        offerMap.putall(ofrList);
        if(offerMap.size()>0){
            update offerMap.values();
        }
    }
    catch(Exception e){
        system.debug('OfferPartnerTrigger' +' '+e+' '+e.getLineNumber());
        
    }
}

Thanks
Hello,
Could anyone help me fix the bold portion of this visualforce email template code so that any document attached to the opportunity in the Notes & Attachments section gets included in the email alert as an attachment?

<messaging:emailTemplate recipientType="Contact"
    relatedToType="Opportunity"
    subject="CSF processing request for: {!relatedTo.name}"
    replyTo="xxxx.xxxx@xxx.net" >
   
<messaging:htmlEmailBody >       
    <html>
        <body>
         <STYLE type="text/css">
               TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center }
               TD  {font-size: 11px; font-face: verdana }
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
         </STYLE>
                  <font face="arial" size="2">
        <p>CSF PROCESSING REQUEST</p>
        <p>Please find attached the detailed CSF for:<p/>
        <p> Opportunity:<b> {!relatedTo.name}</b>
        <br/>Account: <i><b> {!relatedTo.Account.name}</b>  </i>         
        <br/>Opp ID:<b> {!relatedTo.Opp_ID__c} </b>
        <br/>Opportunity Owner: <b>{!relatedTo.owner.name}</b>
        <br/>Operating Region: <b> {!relatedTo.xxxxxx_Operating_Region2__c}</b>
        <p/>       
       <p />
 </font>
        </body>
    </html>
</messaging:htmlEmailBody>       
       
        <messaging:emailTemplate subject="Opps Signed Documents" recipientType="Contact" relatedToType="Opportunity">
    <messaging:htmlEmailBody >
        <p>Attachments</p>
        <apex:repeat value="{!relatedTo.Attachments}" var="a">
            <p><a href="{!URLFOR($Action.Attachment.Download, a)}">{!a.Name}</a> ({!a.BodyLength} B)</p>
        </apex:repeat>
    </messaging:htmlEmailBody>
I'm working on a contact search page and I have a problem. My console has no errors but when I run a search, the results don't generate and all my input validation errors prompt.

For Example: 

Jane Grey

TheSearchForJaneGrey


Here is my VisualForce Page:
 
<apex:page id="ContactPage" controller="Ctrl_ContactSearch">
  
     
      <apex:tabPanel id="ContactPanel">
             
        <apex:tab id="ContactTab" label="Contact Search"> 
            
                  
          <apex:form id="ContactForm">

              
              <!-- Input Fields -->
            <apex:pageBlock title="Contact Search Page" id="ContactBlock">
                                
                <apex:pageBlockSection id="contact-table" columns="3">
                                     
                    <apex:pageBlockSectionItem id="NameInputBlock">                    
                        <apex:outputLabel value="Name" />
                        <apex:inputText id="NameInputField" value="{!name}" />                   
                    </apex:pageBlockSectionItem>
    
                    <apex:pageBlockSectionItem id="PhoneInputBlock">                    
                        <apex:outputLabel value="Phone" />
                        <apex:inputText id="PhoneInputField" value="{!phone}" />                   
                    </apex:pageBlockSectionItem>
                    
                    <apex:pageBlockSectionItem id="EmailInputBlock">                    
                        <apex:outputLabel value="Email" />
                        <apex:inputText id="EmailInputField" value="{!email}" />                   
                    </apex:pageBlockSectionItem>
                       
                </apex:pageBlockSection>   
                
                
                 <!-- Buttons -->
                <apex:pageBlockButtons location="bottom">
                    <apex:commandButton value="Search Contacts" action="{!searchContacts}"  />
                    <apex:commandButton value="Clear Fields" action="{!ClearFields}" />   
                </apex:pageBlockButtons>
                
             </apex:pageBlock>
            

  
            <!-- Results Display -->
            <apex:pageBlock title="Results" rendered="{!contacts.size!=0}" > 
                
                <apex:pageBlockSection >
                
                    <apex:pageBlockTable value="{!contacts}" var="c" id="contact-table">
                            
                            <apex:column >
                                <apex:facet name="header">Name</apex:facet>
                                {!c.Name}
                            </apex:column>
        
                            <apex:column >
                                <apex:facet name="header">Phone Number</apex:facet>
                                {!c.Phone}
                            </apex:column>
                            
                            <apex:column >
                                <apex:facet name="header">Email</apex:facet>
                                {!c.Email}
                            </apex:column>
                            
                        </apex:pageBlockTable>
                    
                </apex:pageBlockSection>
   
            </apex:pageBlock>
              
              
              
          <!-- Error Display -->    
          <apex:pageBlock title="Errors" id="ErrorSection" >
              
                <apex:pageMessages id="ErrorsListing">
                  
                </apex:pageMessages>
              
          </apex:pageBlock>
              
              
              
                                                    
           </apex:form>

            
        </apex:tab>
                  
      </apex:tabPanel>      
        
    <script type = "text/javascript">
    
        var name = document.getElementByID("name");
        var phone = document.getElementByID("phone");
        var email = document.getElementByID("email");
        
    </script>
    
</apex:page>
Here is my Controller
 
public with sharing class Ctrl_ContactSearch
{
    public List<Contact> contacts { get; set; }
    
    public String name { get; set; }
    public String phone { get; set; }
    public String email { get; set; }   
       
    public integer MatchingContacts { get; set; }  
    
    public boolean ErrorsPresent = false;
    public boolean Error_NoResults = false;
    public boolean Error_FieldsEmpty = false;
    public boolean Error_NameSyntax = false;
    public boolean Error_PhoneSyntax = false;
    public boolean Error_EmailSyntax = false;
    
    
   /* Name Input Validation Regex*/
   public static Boolean ValidationName (String name)
            {
                Boolean NameIsValid = false;
                
              
                String nameRegex = '/^[a-zA-Z][a-zA-Z0-9]*(_[a-zA-Z0-9]+)*(__[cC])?$/';
                Pattern PatternName = Pattern.compile(nameRegex);
                Matcher nameMatcher = PatternName.matcher(name);
                
                if (nameMatcher.matches())
                    {
                        NameIsValid = true;
                    } 
 
                return NameIsValid; 
            }
    
     
    /* Phone Input Validation Regex*/
    public static Boolean ValidationPhone (String phone)
            {
                Boolean PhoneIsValid = false;
                
               
                String phoneRegex = '//^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$//';
                Pattern PatternPhone = Pattern.compile(phoneRegex);
                Matcher phoneMatcher = PatternPhone.matcher(phone);
                
                if (phoneMatcher.matches())
                    {
                        PhoneIsValid = true;
                    } 
                   
                return PhoneIsValid;        
            }          
    
   
     /* Email Input Validation Regex*/
     public static Boolean ValidationEmail (String email)
            {
                Boolean EmailIsValid = false;
                
               
                String emailRegex = '/^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$//';
                Pattern PatternEmail = Pattern.compile(emailRegex);
                Matcher emailMatcher = PatternEmail.matcher(email);
                
                if (emailMatcher.matches())
                    {
                        EmailIsValid = true;
                    } 
                    
                return EmailIsValid;    
            }       
    
    

    
    /* Runs when "Clear Fields" button is pressed*/
    public void ClearFields()
            {
               name = '';
               phone = '';
               email = ''; 
            }
    
    
    /* Runs when "Search Contacts" button is pressed*/
    public PageReference searchContacts()
        {
                           
            /* Checks if input fields are empty*/
            if (name == '' && phone == '' && email == '')
                {
                    Error_FieldsEmpty = true;   
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Your fields are blank. Please enter your information in the remainding fields to proceed'));
                }         
            else 
                {
                    /* Checks Input Validation Results*/                      
                    if (ValidationName(name) == false) 
                         {      
                              Error_NameSyntax = true;
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Inproper name format. Please enter name in following format : Firstname Lastname.'));
                          }
                                                                                 
                    if (ValidationPhone(phone) == false) 
                         {
                              Error_PhoneSyntax = true;
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Inproper phone number format. Please enter number in following format : XXX-XXX-XXXX.'));
                          }
                    
                    if (ValidationPhone(email) == false) 
                         {   
                              Error_EmailSyntax = true;
                              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Inproper email format. Please enter email in following format : XXX@emailprovider.com'));
                          }
                        
                    /* Runs if all Validation results are 'true'*/ 
                    if (ValidationName(name) == true && ValidationPhone(phone) == true && ValidationPhone(email) == true)
                        {
                              contacts = [select Name, Phone, Email from Contact where Name = :name or Phone = :phone or email = :email];
                              MatchingContacts = contacts.size();
                            
                              /* Checks if/how many matches were found from the search*/ 
                              if(MatchingContacts != 0)
                                  {  
                                     system.debug('There are currently ' + MatchingContacts + 'results found.' );
                                  }
                              
                              else
                                  {    
                                      Error_NoResults = false;
                                      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'No matching Contacts were found.'));   
                                  }
                        }
                    
                   
                }
                    

              
             /* Displays "Error" field if any errors are found*/
            if (Error_NoResults == true || Error_FieldsEmpty == true || Error_NameSyntax == true || Error_PhoneSyntax == true || Error_EmailSyntax == true)
                {
                    ErrorsPresent = true;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'There are errors present. Please read and follow instructions accordingly.'));                     
                }     
            
            
           return null;     
      }           
}


What do I have wrong here?
Hello,

I have a trigger where the 1st part is desiged to loop through custom object records of a Contact and prevent users from entering duplicate records for each account.  I have a statement that checks a map against the record being inserted/changed. When I look at my logs, I see that the IF statement returns a FALSE result, so the trigger should move on, but it is still throwing the addError message.  Does anyone know why this might be hapening?  The line is question is Line 48 below.
 
trigger UpdateAcctVIP on VIP_Type__c (after insert, after update, after delete){

Set<Id> acctIds = new Set<ID>();
Set<Id> contIds = new Set<ID>();
Set<String> vipTypes = new Set<String>();
    
Map<VIP_Type__c, VIP_Type__c> contactTypeMap = new Map<VIP_Type__c, VIP_Type__c>();
// Get all the Account & Contact Ids in the Set 

	if (Trigger.isDelete) {
		for(VIP_Type__c vip : Trigger.old){
			acctIds.add(vip.Account__c);
            contIds.add(vip.Contact__c);
		    VIP_Type__c key = new VIP_Type__c(Contact__c=vip.Contact__c, Account__c=vip.Account__c, VIP_Type__c=vip.VIP_Type__c);
		}
	}
	else{

    for(VIP_Type__c vip : Trigger.new) {
    	acctIds.add(vip.Account__c);
    	contIds.add(vip.Contact__c);
        vipTypes.add(vip.VIP_Type__c);
    	VIP_Type__c key = new VIP_Type__c(Contact__c=vip.Contact__c, Account__c=vip.Account__c, VIP_Type__c=vip.VIP_Type__c);
system.debug('@@@### - Key Check:  '+key);
system.debug('@@@### - vip Check:  '+vip);
system.debug('@@@### - 1st Map Check:  '+contactTypeMap.put( key, vip ));
system.debug('@@@### - 2nd Map Check:  '+contactTypeMap.get( key ));
system.debug('@@@### - 2nd Map Check:  '+contactTypeMap);

	        if(contactTypeMap.put( key, vip ) != null) {
	       		contactTypeMap.get( key ).addError( 'This type already exits for this Contact' );
    		}
     }
	 }

List<VIP_Type__c> vipRecs = [SELECT Id,Account__c,Contact__c,VIP_Type__c
                            FROM VIP_Type__c
                            WHERE Contact__c = :contIds AND Account__c = :acctIds AND ID NOT IN:trigger.new];

//Check for VIP Types already entered for Contact
for(VIP_Type__c vip: vipRecs) {
system.debug('@@@### - Check for Types:  '+vipRecs);
    VIP_Type__c key = new VIP_Type__c(Contact__c=vip.Contact__c, Account__c=vip.Account__c, VIP_Type__c=vip.VIP_Type__c);
system.debug('@@@### - Check for Types-key:  '+key);
system.debug('@@@### - Check contactTypeMap:  '+contactTypeMap);
system.debug('@@@### - Check contactTypeMap (key):  '+contactTypeMap.containsKey(key));

    if(contactTypeMap.containsKey(key)) {
        contactTypeMap.get(key).addError('This Type already exists for this Contact');
    }
}
    

// Query the Accounts
		List<Account> acct = new List<Account>();

// Use the VIP Types to get all the related Types for the Account 
			acct = [SELECT Id, VIP_Types__c,(Select VIP_Type__c FROM VIP_Types__r) 
					FROM Account 
					WHERE Id in :acctIds]; 

// Iterate over each Account and VIP record 
			for(Account a : acct){ 
				a.VIP_Types__c = ''; 

				for(VIP_Type__c vip: a.VIP_Types__r){ 

					if(!a.VIP_Types__c.contains(vip.VIP_Type__c) || a.VIP_Types__c == ''){ // Check if the Type is already in the Account Field. if not add it otherwise skip 

					a.VIP_Types__c += vip.VIP_Type__c + '; '; 
					} 
				} 
			} 
// Update the Account 
		update acct; 
}

 
Hello,

I have a trigger that is checking a picklist field on a custom object (VIP_Type__c) to make sure duplicate records are not allowed under the parent object (Contact).  I am getting an Apex error message related to the error message line in my trigger. Can anyone help me understand why?
 
trigger UpdateAcctVIP on VIP_Type__c (after insert, after update, after delete){

	Set<Id> acctIds = new Set<ID>();
	Set<Id> contIds = new Set<ID>();

	map<Id, set<String>> contact_type_map = new map<Id, set<String>>();

// Get all the Account & Contact Ids in the Set 
	if (Trigger.isDelete) {
		for(VIP_Type__c vip : Trigger.old){
			acctIds.add(vip.Account__c);
            contIds.add(vip.Contact__c);

			contact_type_map.put(vip.Contact__c , new set<String>());
		}
	}
	else{
        for(VIP_Type__c vip : Trigger.new){
			acctIds.add(vip.Account__c);
            contIds.add(vip.Contact__c);

            contact_type_map.put(vip.Contact__c, new set<String>{vip.VIP_Type__c});
System.Debug('@@@###-contact_Type_Map: '+contact_Type_Map);
	}
    }
		List<VIP_Type__c> vipRecs = [SELECT Id,Account__c,Contact__c,VIP_Type__c
                                    FROM VIP_Type__c
                                    WHERE Contact__c in:contIds];


//Check for VIP Types already entered for Contact
    for(VIP_Type__c objVIP: vipRecs){
		if(contact_type_map.get(objVIP.Contact__c).contains(objVIP.VIP_Type__c)){
system.debug('@@@### - Error message:  '+objVIP.VIP_Type__c);
                trigger.newMap.get(objVIP.Id).addError('This Type already exists for this Contact');
system.debug('@@@### - Error message:  '+trigger.newMap.get(objVIP.Id));
        }
        else{
            contact_type_map.get(objVIP.Contact__c).add(objVIP.VIP_Type__c);
        }
    }

 
Hi,

I have a pretty basic question (I think) about the use of a Set within a map.  I have a trigger with a piece of code:
 
map<Id, set<String>> newMap = new map<Id, set<String>>();

For(Custom_Object__c cust : Trigger.new){
newMap.put(cust.Contact__c, new set<String>());
}

I am trying to create a keyset of Contact ID & Type on a custom object so I can compare to ensure Contact records only allow 1 Type of each related custom object record.  When I run the Debug statements, the map is only populating the Contact ID.  I have 2 questions:

What are the set<string> in my map and new set<string> in my put statement designed to do, and how do I get the set<string> to populate?
Error -
ystem.AssertException: Assertion Failed: Expected: webhook_url,
Actual: url
Stack Trace: Class.PriceBookWebhookTriggerTest.testTrigger: line 71, column 1   
Scenario for trigger is that, if Opportunity Object having record with field stageName=='Prospecting ' and Parent Account name with,lets say XYZ.,so another record with same field value and same parent should not get duplicated.. I have written below trigger but it is showing error.

 
trigger TriggerOpp on Opportunity (before insert,before update) {
   set<id> setid=new set<id>();
    for(Opportunity opp:trigger.new)
    {
       setid.add(opp.AccountId);
    }
    
    Map<id,Account> acmap=new map<id,Account>();
    
    for(account acc:[select id,Name,(select id,Name,StageName from Opportunities) from Account where id in:setid])
    {
        acmap.put(acc.id,acc);
    }
    
    for(Opportunity opp:trigger.new)
    {
        if(acmap.containsKey(opp.AccountId))
        {
           if(acmap.get(opp.AccountId).StageName=='Prospecting')
           {
               (opp.AccountId).addError('Duplicate value');
           }
        }
    }
}
Hello,
I have created a trigger to update a field anytime a specific task is created.
But when trying to add another type of Task I have the following error
User-added imageThis is the line 11 causing the error 
if(t.whatId != null && t.callDisposition.containsIgnoreCase('aircall')) {

How can I fix the nullPointer exception:
Thanks.

Here is the trigger 
 

trigger AircallTaskTrigger on Task (after insert, after update) {

        List<Case> lstCase = new List<Case>();
     
     	//Get 'Case Concern' RecordType Name
        Id caseConcernRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get(label.Param_Case_Concern).getRecordTypeId();

        Map<Id, Case> caseWithAircallTaskMap = new Map<Id, Case>([SELECT Id, First_Aircall_Logged__c FROM Case WHERE RecordTypeId =:caseConcernRecordTypeId]);                           
        for(Task t : Trigger.New) { 
           
            if(t.whatId != null && t.callDisposition.containsIgnoreCase('aircall')) {
               System.debug('#### Aircall debug ' + t.whatId != null && t.callDisposition.containsIgnoreCase('aircall'));
                
                Case c = New Case();
                if(caseWithAircallTaskMap != null && caseWithAircallTaskMap.containsKey(t.whatId)){
                
                    c = caseWithAircallTaskMap.get(t.whatId);
                    if(c.first_Aircall_Logged__c == null){
                        c.first_Aircall_Logged__c = t.createdDate;
                        if(t.WhatId == c.Id) {
                            lstCase.add(c); 
                        }              
                    } 
                } 
            }     
        }
     
        if (lstCase.size() > 0) {
        	update lstCase;
     	}  
  }

Here is the Test Class
 
@isTest
public class AircallTaskTriggerTest {
    @isTest static void testAircallDateUpdate() {
        
        Contact con = new Contact (FirstName = 'First Name',LastName = 'Test');
        insert con;
        
        Case c = new Case(Status = 'New',ContactId = con.Id,Phone_Number__c = '123456789');
        insert c;
               
        Task t = new Task(Subject = 'Test', WhatId = c.Id, CreatedDate = System.today(), callDisposition = 'aircall');
        insert t;
        
        c.Id = t.WhatId;
        c.First_Aircall_Logged__c = t.CreatedDate;
        System.assertEquals(t.CreatedDate,  c.First_Aircall_Logged__c);
        update c;
       
    }
    
}

 
Hi 
I need to check a checkbox field "Has Phone" if the phone number field as at least 5 digits 
( The reason for 'at least 5' rather than just 'not blank' is to avoid including "1" and the reason for  '5 numbers' rather than '5 characters' is to avoid including words like "no number") 

We're just trying to check if the contact has a valid phone number but we want to leave the sales people the ability to write anything in the field like reception, ext., etc ... 

Any ideas ? 
Thanks a lot 

Hello,

I am unable to get the correct syntax for my SOQL request
I am trying to request all cases with of a specific record type by using a custom label.
But my syntax is wrong and I cannot quite figure it out.

Thanks
 

Id caseConcernRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get(label.Param_Case_Concern).getRecordTypeId();

        Map<Id, Case> caseWithAircallTaskMap = new Map<Id, Case>([SELECT Id, First_Aircall_Logged__c FROM Case WHERE RecordTypeId IN: caseConcernRecordTypeId]);
 


 

I have a requirement to create a new record of a custom object. This custom object should be populated with List Price field value of Standard Price Object. I was trying to create it with Process Builder. But process builder doesn't have option of Standard Price Object in add object section. Please help me what approach needs to be followed.
If it can be done through trigger, please share a sample code.

Thanks,
Mahesh
Hi,

I am writting a approval process, i would like to assign a approver from a sales Rep (User Lookup) of currecnt record.

In a standard process, it's a way to choose while create a approval process. But in my scenario i want to assign to record's sales Rep (User). 

Do i need to create any apex class ? Else can i achieve it from a standard way.

Regards,
Soundar.
Hi , In Contacts,  i have two picklist fields called PEP and AML Risk Assessment. If the options , 'Domestic' or 'Foreign' are chosen in the picklist field PEP, I want ot mandatory that the picklist on the AML Risk Assessment is 'High' How do I do this? Thank you.
Hi all, I am getting an error Id and Pricebook2Id not found. Can anyone help please.
I am doing devlopment in Scratch Org. Below is the code and Error snippet.
User-added image
Hi Everyone,

From last two weeks, I am not receiving any emails for the questions that I follow. It was working fine but suddenly the emails stopped coming.
I checked my profile and this checkbox "Email me when someone replies to posts I follow" is marked as true.
I also tried to change my email but that also doesn't work.

It is so frustrating to check the number of replies on questions that I follow and than see what users have posted. Can someone help me to resolve this problem as I sepnd a lot of time here and don't want to manually check each and every post.

Any help is greatly appreciated!

Thanks,
Abhishek Bansal
Account  picklist filed status__c changes to completed , when all fields are  not empty else status__c show as incomplete,,
If status__c changes to completed
,i want checkbox in all the related contact should be checked.
Hi,
I have a Lightning component form which consists of many fields and parts. What I need is to refresh a particular part of the Lightning component without refreshing the whole component.
User-added image
In the above image I have the Fetch Contact Info in one whole div so when I click the refresh icon it should empty all the fields if the values are present. Is there any possibility to do that, any information will be helpful.

Thanks,
Bharath Kumar Thota
I need to pick up the current value of the outputfield that is entered by the user 
I have tried using the component Id in JS but had no luck 
further have used other methods in the following part of the code
<apex:pageBlockTable value="{!Records}" var="record" id="thePageBlockTable" styleclass="slds-table slds-table_cell-buffer slds-table_bordered" > 
                <apex:column >
                    <span style="float:right">
                        <span style="float:right;">
                            <apex:commandLink value="Save"  onclick="editTermExtract()" id="saveButton" styleClass="slds-button slds-button_neutral">
                            <apex:param value="{!record.id}" name="standrdId"/>
                            <apex:param value="{!record.Body__c}" name="currentbody"/>
                            <apex:param value="{!record.Type__c}" name="recordType"/>
                            </apex:commandLink>
                        <apex:commandButton value="Cancel" action="{!cancel}"  id="cancelButton" style="display:none;" styleClass="slds-button slds-button_neutral"/> 
                    </span>
                        <apex:commandLink rendered="{!If(record.Standard_Term__c!=null,true,false)}" action="{!revert}" reRender="thePageBlockTable" styleClass="slds-button slds-button_neutral">Revert
                            <apex:param value="{!record.id}" name="revertId"/>
                        </apex:commandLink>
                   <!--      <apex:pageblock rendered="{!If(record.Standard_Term__c!=null,true,false)}">
                           <span class="slds-pill " style="background-color:#00396B;padding:0px 4px;">
                            <span class="slds-pill__label" style="color:#ffffff">Modified</span>
                            </span>
                        </apex:pageblock> -->
                    </span>
                    <div class="tdData">
                          <apex:outputField value="{!record.Body__c}" id="Quoteterm"  styleclass="slds-truncate"> 
                        <apex:inlineEditSupport id="inltd" event="onclick" 
                                            showOnEdit="saveButton,cancelButton" />
                    </apex:outputField>
                    </div>
                                           
                </apex:column>
            </apex:pageBlockTable> 
           

            
        </apex:pageBlock> 
        </html>
             <apex:actionFunction action="{!save}" name="saveMeth" reRender="thePageBlockTable">
               
                <apex:param value="" name="changedTerm"></apex:param>
            </apex:actionFunction>
        <script type="text/javascript">
         $(document).ready(function() {
              $('[id$=inltd]').change(function(e) {
                 alert(e.target.value);
            });
          });
        function editTermExtract(){
                     
            //alert(p);
            //alert($('[id$=Quoteterm]').val());
            //alert($('[id$=Quoteterm]').text()+' jq+text');
            //alert($('[id$=Quoteterm]').html()+' jq+html');
            //var jsV = document.getElementById('Quoteterm');
            //alert(document.getElementsByTagName('p')[0]);
            //alert(jsV);
            // saveMeth($('[id$=Quoteterm]').text());
        }
        </script>
    </apex:form>
    </div>
</apex:page>
 
public class QuoteTermEditorController {
    
    public string body{get;set;}
    public string recordId{get;set;}
    public Map<Id,Quote_term__c> revertMap {get;set;}
    public List<Quote_term__c> termList {get;set;}
    public String revertid {get;set;}
    public boolean showButton{get;set;}
    public boolean showButton1{get;set;}
    public string selectedTemplate{get;set;}
    public List<Quote_term__c> termExtract{get;set;}
    public List<Quote_term__c> PrevData{get;set;}
    ApexPages.StandardSetController acon;
    public QuoteTermEditorController(ApexPages.StandardSetController acon) {
        this.acon = acon;
        recordId = ApexPages.currentPage().getParameters().get('id');
        //system.debug(recordId);
        revertMap = new Map<Id,Quote_term__c>();
    }
    public List<Quote_term__c> getRecords(){
        if(recordId!=null){
        List<Quote_term__c> termExtract = [select id,name,print_order__c,type__c,Standard_Term__c,body__c,Quote_del__r.name,(select id,type__c,name,Standard_Term__c,body__c,Locked__c from Quote_Terms1__r where Quote_del__c=:recordId and Active__c=true) from Quote_term__c where Type__c='Standard' or Type__c='Custom' order by print_order__c asc];
        termList = new List<Quote_term__c>();
        for(Quote_term__c term:termExtract){
            if(term.Quote_terms1__r.size()>0 ){
                    termList.add(term.Quote_terms1__r);
                for(Quote_term__c q:term.Quote_terms1__r){
                   revertMap.put(q.id,term);                    
                }
            }
            else{
            termList.add(term);
            }
        }
        }
        PrevData = new List<Quote_term__c>(termList);
        return termList;
    }
    public pagereference revert(){
                  revertid = ApexPages.currentPage().getParameters().get('revertId');
          system.debug(revertid);
          update new Quote_term__c(id=revertid,Active__c=false);
        for(Quote_term__c q:termList){
            if(q.id==revertid){
                termList[termList.indexOf(q)] = revertMap.get(revertid);
            }
        }
          return null;
    }
    public pagereference save(){
     String standrdId = ApexPages.currentPage().getParameters().get('standrdId');
     String body = ApexPages.currentPage().getParameters().get('currentbody');
     String type = ApexPages.currentPage().getParameters().get('recordType');
        update termList;
        for(Quote_term__c quoTerm:termList){
           // update quoTerm;
            system.debug(quoTerm + 'out');
            if(!PrevData.contains(quoTerm)){
               system.debug(quoTerm);
            }
        }
        
        if(type=='Custom'){
            Quote_term__c Custom = new Quote_term__c(id=standrdId,body__c=body);
            //system.debug(Custom);
            //update Custom;
           //system.debug(termList);
          // update termList;
        }
        system.debug(type);
        system.debug(standrdId);
        system.debug(body);
     return null;
    }
    
    public pagereference cancel(){
       
       return null;
    }
    public List<SelectOption> getTemplateOptions() {
        List<SelectOption> countryOptions = new List<SelectOption>();
        countryOptions.add(new SelectOption('','-None-'));
        for(Quote_Template__c QtTem : [Select id,name from Quote_Template__c]){
            countryOptions.add(new SelectOption(QtTem.name,QtTem.name));
        }
        return countryOptions;
    }
}

Thanks
We have a custom object MyEvent__c with the following datetime fields StartDateTime__c and EndDateTime__c.

I am trying to get all of the current events and upcoming events.
 
For example, today is 9/14/2020   12:23 PM
 
Start Date/TimeEnd Date/TimeResults
9/14/20 1:00 PM9/14/20 2:00 PMInclude
9/14/20 9:00 AM9/14/20 1:00 PMInclude
9/14/20 8:00 AM9/14/20 8:30 AMDo Not Display
9/14/20 1:00 PM9/16/20 7:00 PMInclude
9/14/20 9:00 AM9/16/20 7:00 PMInclude
9/16/20 9:00 AM9/16/20 7:00 PMDo Not Display


Here is my query so far, but its not returning the correct results.
SELECT Id, Name FROM MyEvent__c WHERE StartDate__c = TODAY OR (StartDate__c >=TODAY AND EndDate__c <= TODAY)



 

Hey all. I'm having some trouble getting a commandButton to rerender a pageBlockTable which is inside an outputPanel that is always renderered

<apex:page controller="AirlockLookup" lightningStylesheets="true" showHeader="false" sidebar="false">
    <apex:form id="form">
            <apex:pageBlock id="block">
                <apex:pageBlockSection id="section1" columns="1">
                    <h1 style="font-size:18px;text-align:center;">Airlock Model Search</h1>
                </apex:pageBlockSection>
                <apex:pageBlockSection id="section2" columns="2">
                    <apex:inputText id="Make" label="Make" value="{!Make}" title="Leave Blank if Unknown">
                        <apex:actionSupport reRender="section2" event="onchange" />
                    </apex:inputText>
                    <apex:inputText label="OEM" value="{!OEM}" rendered="{!(Make == 'RAS')}" title="Leave Blank if Unknown"/>
                    <apex:inputText label="Series" value="{!Series}" title="Leave Blank if Unknown"/>
                    <apex:inputText label="Model Name" value="{!ModelName}" title="Leave Blank if Unknown"/>
                    <apex:selectList label="Flange Style" value="{!FlangeStyle}" size="1">
                        <apex:selectOption itemLabel="Unknown" itemValue="Unknown" title="Unknown"/>
                        <apex:selectOption itemLabel="Square" itemValue="Square" title="Square"/>
                        <apex:selectOption itemLabel="Round" itemValue="Round" title="Round"/>
                        <apex:selectOption itemLabel="Square Inlet/Round Outlet" itemValue="Square Inlet/Round Outlet" title="Square Inlet/Round Outlet"/>
                        <apex:selectOption itemLabel="Round Inlet/Square Outlet" itemValue="Round Inlet/Square Outlet" title="Round Inlet/Square Outlet"/>
                    </apex:selectList>
                    <apex:selectList label="Endcap Configuration" value="{!ECConfig}" size="1">
                        <apex:selectOption itemLabel="Unknown" itemValue="Unknown" title="Unknown"/>
                        <apex:selectOption itemLabel="Inboard" itemValue="Inboard" title="Inboard" />
                        <apex:selectOption itemLabel="Outboard" itemValue="Outboard" title="Outboard" />
                    </apex:selectList>
                    <apex:selectList label="Product Passage" value="{!ProductPassage}" size="1">
                        <apex:selectOption itemLabel="Unknown" itemValue="Unknown" title="Unknown"/>
                        <apex:selectOption itemLabel="Blow Thru" itemValue="Blow Thru" title="Blow Thru"/>
                        <apex:selectOption itemLabel="Drop Thru" itemValue="Drop Thru" title="Drop Thru"/>
                        <apex:selectOption itemLabel="Jet-Under" itemValue="Jet-Under" title="Jet-Under"/>
                        <apex:selectOption itemLabel="Offset" itemValue="Offset" title="Offset"/>
                    </apex:selectList>
                    <apex:selectList label="Cleaning Options" value="{!CleaningOptions}" size="1">
                        <apex:selectOption itemLabel="None" itemValue="None" title="None"/>
                        <apex:selectOption itemLabel="Quick Clean" itemValue="Quick Clean" title="Quick Clean"/>
                        <apex:selectOption itemLabel="Clean in Place" itemValue="Clean in Place" title="Clean in Place"/>
                    </apex:selectList>
                    <apex:selectList label="Housing Inspection Door?" value="{!HID}" size="1">
                        <apex:selectOption itemLabel="No" itemValue="No" title="No"/>
                        <apex:selectOption itemLabel="Yes" itemValue="Yes" title="Yes"/>
                    </apex:selectList>
                    <apex:selectList label="Steam Water Jacketed Endcaps?" value="{!SWJEndcaps}" size="1">
                        <apex:selectOption itemLabel="No" itemValue="No" title="No"/>
                        <apex:selectOption itemLabel="Yes" itemValue="Yes" title="Yes"/>
                    </apex:selectList>
                    <apex:selectList label="Steam Water Jacketed Housing?" value="{!SWJHousing}" size="1">
                        <apex:selectOption itemLabel="No" itemValue="No" title="No"/>
                        <apex:selectOption itemLabel="Yes" itemValue="Yes" title="Yes"/>
                    </apex:selectList>                    
                    <br/>
                </apex:pageBlockSection>
                <apex:pageBlockSection columns="1">
                    <apex:commandButton title="Search for Models" value="Search" action="{!SearchModels}" reRender="models" status="searchstatus"/>
                    <apex:actionStatus id="searchstatus" >
                        <apex:facet name="start">
                            <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.75; z-index: 1000; background-color: black;">
                                &nbsp;
                            </div>
                            <div style="position: fixed; left: 0; top: 0; bottom: 0; right: 0; z-index: 1001; margin: 30% 50%">
                                <img src="http://upload.wikimedia.org/wikipedia/commons/e/ed/Cursor_Windows_Vista.gif" />
                            </div>
                        </apex:facet>
                    </apex:actionStatus>
                    <apex:outputPanel id="models">
                        <apex:pageBlockTable value="{!models}" var="m" rendered="{!showModels}">
                            <apex:column headerValue="Model Name" value="{!m.Name}" />
                            <apex:column headerValue="Make" value="{!m.Make_Name__c}" />
                        </apex:pageBlockTable>
                    </apex:outputPanel>
                </apex:pageBlockSection>
            </apex:pageBlock>
    </apex:form>
    
</apex:page>
 
public class AirlockLookup {
    public String Make {get; set;}
    public Boolean showOEM {get; set{showOEM = false;}}
    public String OEM {get; set;} // Only if Make is RAS
    public String Series {get; set;} // Dependent on Make
    public String ModelName {get; set;} // Will need to use a Contains()
    public String FlangeStyle {get; set;} // Square, Round, Square Inlet/Round Outlet, Square Outlet/Round Inlet
    public String ProductPassage {get; set;} // Blow Thru, Drop Thru, Jet-Under, Offset
    public String ECConfig {get; set;} // Inboard, Outboard
    public String CleaningOptions {get; set;} // None, Quick Clean, Clean in Place
    public Decimal HousingHeight {get; set;} 
    public String HID {get; set;} // Housing Inspection Door: Yes, No
    public Decimal AIFlangeID {get; set;}
    public Decimal AIFlangeOD {get; set;}
    public Decimal RIFlangeID {get; set;}
    public Decimal RIFlangeOD {get; set;}
    public Decimal IFlangeID {get; set;}
    public Decimal IFlangeOD {get; set;} // All Decimal fields are 14 left, 4 right
    public Decimal AOFlangeID {get; set;}
    public Decimal AOFlangeOD {get; set;}
    public Decimal ROFlangeID {get; set;}
    public Decimal ROFlangeOD {get; set;}
    public Decimal OFlangeID {get; set;}
    public Decimal OFlangeOD {get; set;}
    public String SWJEndcaps {get; set;} // Steam Water Jacketed Endcaps: Yes, No
    public String SWJHousing {get; set;} // Steam Water Jacketed Housing: Yes, No
    public List<Model__c> models {get; set{models = new List<Model__c>();}}
    public Boolean showModels {get; set{showModels = false;}}
    
	public AirlockLookup() {
        
    }
    
    public PageReference SearchModels() {
        showModels = true;
        models = [SELECT Id, Name, Make_Name__c, OEM_Style__c, Series__c, Flange_Style__c, Product_Passage__c, Endcap_Configuration__c, Cleaning_Options__c, Housing_Height__c,
                 Housing_Inspection_Door__c, Axial_Inlet_Flange_ID__c, Axial_Inlet_Flange_OD__c, Radial_Inlet_Flange_ID__c, Radial_Inlet_Flange_OD__c, Inlet_Flange_ID__c,
                 Inlet_Flange_OD__c, Axial_Outlet_Flange_ID__c, Axial_Outlet_Flange_OD__c, Radial_Outlet_Flange_ID__c, Radial_Outlet_Flange_OD__c, Outlet_Flange_ID__c,
                 Outlet_Flange_OD__c, Steam_Water_Jacketed_Endcaps__c, Steam_Water_Jacketed_Housing__c FROM Model__c WHERE Make_Name__c = :Make];
        		
        return null;
    }
}
Hi,
I am trying to create an alert on a specific date field on an object that is time-based related. 

The issue is that both Process Builder and WorkFlow only fire when an object is updated or created, but not when a date becomes Today (naturally, without editing or creating the object's fields).

Here are my 3 separate use cases (each needs its own solution, but has the same problem):
1. On a custom object called "Project" we have a date-field called KICKOFF DATE.  When the date becomes today, we want an email alert to send out a reminder that today is kickoff date for this project.
2. When an Opp is in Stage 1 and it's Age = 60 days, we want to send an email alert that the Opportunity is 60 days old (from created date) and is in stage 1.
3. When an Opportunity is approaching the Close Date and is in a lower Stage, we want an alert to fire that says warns it is approaching.
So now I think I need a trigger to help fire this in Process Builder. 

Anybody ever had this need before or accomplished this?
<apex:page standardController="User" extensions="RegistrationExt">
  <apex:form >
  <div id="logo" >
          <img src="{!$Resource.logo}" width="20%"/>
          <hr  style="height:5px;background-color:orange"> </hr>
       </div>
  <div style="text-align: center;margin-top: 40px;" >
        <span style="margin-right: 10px;">First Name</span><apex:inputText value="{!user.Name}" />
        </div><br></br>
       <div style="text-align: center;">
        <span style="margin-right: 10px;">Last Name</span><apex:inputText value="{!User.Last_Name__c}" required="true" />
        </div><br></br>
        <div style="text-align: center;">
        <span style="margin-right:38px;">Email</span><apex:inputText value="{!User.Email__c}" required="true" />
        </div><br></br>
        <div style="text-align: center;">
        <span style="margin-right: 35px;">Phone</span><apex:inputText value="{!User.Phone}" required="true" />
        </div><br></br>
        <html>
                  <body>

                      <center>

                        <form >
                        <input type="checkbox" id="doc" value="{!USer.Profile}" />
                        <label for="doc"> Doctor</label>
                        <input type="checkbox" id="Nur" value="{!USer.Profile}" />
                        <label for="Nur"> Nurse</label>
                        <input type="checkbox" id="IntDoc"  value="{!USer.Profile}"/>
                        <label for="IntDoc">Intern Doctor </label>

                        </form>
                        </center>
                        </body>
                       
                        </html>

<!--Controller class-->

public with sharing class RegistrationExt {
  User us;
     public String confirmPwd {get;set;}
    
    public RegistrationExt(ApexPages.StandardController con){
        
       us = new User();
        us = (User)con.getRecord();
    }
     public PageReference save() {
          PageReference pr; //default value is null
         if(String.isBlank(us.Password__c) || String.isBlank(confirmPwd)) {

            ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,'Please enter both Password and Confirm Password.');
            ApexPages.addMessage(msg);
        }
        else if(us.Password__c != confirmPwd) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,'Password and Confirm Password mismatch.');
            ApexPages.addMessage(msg);
        }
        else {
            try {
                insert us;  
                   pr = Page.EMRPediatricsHome;
            }
             catch(Exception e) {
                ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.Error,e.getMessage());
                ApexPages.addMessage(msg);
            }
        }

        return pr;
    }
  }
my customer is keep getting the invalid login error .

even after we reset password and security token for them , the error still keep coming . 

is there any reason for this ? your help is much appreciated . 

===========================
INVALID_LOGIN:
Invalid username, password, security token; or user locked out.

The response status=500 of request which url=https://login.salesforce.com/services/Soap/u/42.0/ and method=POST. Retry after 4 seconds.
The response status=500 of request which url=https://test.salesforce.com/services/Soap/u/39.0/ and method=POST. Retry after 4 seconds.
=======================

=================
INVALID_LOGIN:Invalidusername, password, securitytoken; oruserlockedout.


Theresponsestatus=500forrequestwhichurl=https://test.salesforce.com/services/Soap/u/39.0/andmethod=POST.
=======================
Can I have a field that is both a picklist and formula?  The picklist values will be 1 to 72.

I need 1 field to be able to used 2 ways. 

1st – Formula to work out the number of months between 2 date fields and return the result as a number, eg Date 1 = 18 August 2021 / Date 2 is 7 February 2021 Result = 8 (representing 8 months).
AND
2nd - also need people to be able to manually select a value between 1 and 72 from the picklist.

Is this possible or do I need 2 separate fields
 

Hi,

I am migrating all tickets from Jira to Salesforce. I successfully imported cases and case comments. In order to upload a file to a case, I'm using ContentVersion object and writing a trigger to update FirstPublishLocationId to the Id of a case after insert. The files are uploaded to a case but the OwnerId field isn't affected. The owner is the user running the API by default.

I read some posts and they said that this OwnerId is only updatable, not creatable. 

I tried to export all records from ContentVersion object with the hope that I can get the ID and update the OwnerId. The problem is I don't see the file which I uploaded to Salesforce using the API in the report.

I am really stuck. Can you please advise how to update the owner of the file? Or you have any other approaches to upload files to a case. Please advise.

Thanks in advance.

 

Hello,

We would like to add text to the end of an account name upon creation or edit.  For example for an account name of "XYZ" entered by user if it is record type of ABC then the account name would be "XYZ (AB)" or something like that.  Is that possible via a process builder?  I am 99% sure it is, but not sure what the formula or what would be needed to append the (AB) to the end of an account upon creation or edit.  
Hello -

I have a VF Page with two Tabs (Tab1 and Tab2 ) , In each tab I am using VF components to display the data . When I initially load the Vf page , it will land on Tab1 .When I click on Tab 2 , it displays the data correctly , but after few seconds the data vanishes (i.e., the data disappears and it displays a blank screen )

Can someone help me on this?

Code Snippet -
<apex:form id="formId"  style="{!if(customStyle != null,if(guMessage == null,'width:100em;border-collapse:collapse;padding-inline-start:-80em;margin-left:-150px;margin-top:-60px;','width:100em;border-collapse:collapse;padding-inline-start:-80em;margin-left:160px;margin-top:60px;'),'width:100%')}" >
        <apex:actionFunction name="callTab1" action="{!tab1}" rerender="PBID"/>
        <apex:actionFunction name="callTab2" action="{!tab2}" rerender="PBID"/> 
        <apex:actionFunction name="refreshPageSize1" action="{!refreshPageSize1}" status="fetchStatus" reRender="" oncomplete="window.scrollTo(0,0);"/>
       <apex:pageBlock id="PBID" rendered="{!$CurrentPage.parameters.id != null && guMessage == null}" >
        <apex:pageMessages id="msg1" ></apex:pageMessages> 
           <apex:outputPanel rendered="{!if(gu == 'us' || gu =='canada' ,true,false)}">
                <apex:tabPanel switchType="client" value="{!selectedTab}"
                               id="AccountTabPanel" tabClass="activeTab" 
                               inactiveTabClass="inactiveTab"  headerSpacing="10"> 
                <apex:tab label="Tab1" name="Tab1Details" id="Tab1ID" style="background-color:white;border:0;font-family: Verdana;" ontabenter="callTab1();" >
                <c:MetricBlockComponent metvalues="{!MetricBlock_Tab1}" > </c:MetricBlockComponent>                           
                </apex:tab>
                    <apex:tab label="Tab2" name="Tab2Details" id="Tab2ID" style="background-color:white;border:0;font-family: Verdana;" ontabenter="callTab2();" >
                  <c:LocalDemoComponent metvalues="{!MetricBlock_Tab2}" > </c:LocalDemoComponent> 
                    </apex:tab>
                   
                </apex:tabPanel>
            </apex:outputPanel>
  • September 10, 2020
  • Like
  • 0

hi,
i am new to salesfoce here i got scenario like populate total revenue  in amount filed in account record which is having number opportunity childs

i am providing sample format also 

thanks in advance
trigger contactTrigger on opportunity ( after insert, after update, after delete, after Undelete) {
    Set<ID> accIdSet = new Set<ID>();
    
    // After Insert 
    if(Trigger.isAfter){   
        if(Trigger.isUndelete || Trigger.isInsert){
            for(opportunity c : Trigger.New){
                if(c.AccountId != Null){
                    accIdSet.add(c.AccountID);
                }
            }   
        }
        
        if(Trigger.isDelete){
            for(opportunity c : Trigger.Old){
                if(c.AccountId != Null){
                    accIdSet.add(c.AccountID);
                }
            }  
        }
    }
    
    
    List<Account> accList = [SELECT ID, No_of_opportunities__c, (SELECT Id , revenueFROM opportunites) FROM Account WHERE Id IN :accIdSet];
    
    if(accList.size() > 0 ){
        for(Account a : accList){           
            a.No_of_opportunities__c = a.contacts.size()    //which one i need to fill here;
        }
        update accList; 
    }
    
}

public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'];
Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc.Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}
I am trying to update the 'Number of contacts' field in Account object.
Tried to call the countContacts() from anonymous window, But this exception occurs
AccountProcessor.countContacts();