• Danish Hoda
  • SMARTIE
  • 1960 Points
  • Member since 2016
  • Salesforce Enthusiast|Lightning Champion
  • Infoglen LLC


  • Chatter
    Feed
  • 63
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 528
    Replies
Hi All,

I have a requiremnt to send bell notification once many records gets inserted(apprx 900) on weekly basis. so that the users will get to know new records are inseted 
Hi, I've built a trigger that will update the Owner for the Account and its related contacts based on the User Lookup field in the Account. I was able to update the Owner of related contacts with an update in the Account.
If I change the Account in any of the Contact then the new Accounts owner should be added as Contacts Owner. I tried using the Trigger.OldMap. Can someone help me with what needs to be changed in my trigger...
trigger AccountOwnerUpdate on Account (before insert, before update) {
    Set<Id> accIds = new Set<Id>();
    List<Contact> updatedConList = new List<Contact>();
    Map<Id, String> newOwnerIds = new Map<Id, String>();
    
    
    List<Contact> conList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: accIds];
    for(Account acc : trigger.new) {
        accIds.add(acc.Id);
        newOwnerIds.put(acc.Id, acc.Coverage_Lead__c);
        
        if(acc.Coverage_Lead__c != NULL) {
            acc.OwnerId = acc.Coverage_Lead__c;
        }
        if(acc.Coverage_Lead__c == NULL){
            acc.OwnerId = acc.LastModifiedById;                
        }
    }
    if(trigger.isUpdate) {
        for(Account acc : trigger.new) {
            for(Contact con : conList) {
                if(con.AccountId!= NULL) {
                    if(trigger.oldMap.get(con.Id).AccountId != con.AccountId) {
                        accIds.add(con.AccountId);
                    }
                }
                accIds.add(trigger.oldMap.get(con.Id).AccountId);
            }
        }
    }

    for(Account accs : [SELECT Id, LastModifiedById, (SELECT Id, Owner.Id, AccountId FROM Contacts) FROM Account WHERE Id IN:accIds]) {
        if(newOwnerIds.get(accs.Id) != NULL) {
            for(Contact con : accs.Contacts) {
                con.OwnerId = newOwnerIds.get(accs.Id);
                updatedConList.add(con);
            }
        }
        if(newOwnerIds.get(accs.Id) == NULL) {
            for(Contact con : accs.Contacts) {
                con.OwnerId = accs.LastModifiedById;
                updatedConList.add(con);
            }   
        }
        
    }
    update updatedConList;
}
Thanks in Advance.
  • March 04, 2021
  • Like
  • 0
Hello
In my org, we already have the standard email-to-case setup. It uses our customercare@mycompany.com email address.
We also have "Case Auto Response Rule" that catches all emails coming to customercare@mycompany.com and sends a templated response with the case id.
Now, I have written a custome InboundEmailHandler to catch all incoming emails, check the subject line and do stuff in code.

Problem/Question:
Instead of creating a new email address to use for this customer handler, I would like to connect this to our main customercare@mycompany.com email address.  Any emails sent to this address should first go through my custom handler and then do email-to-case and Case Auto Response.

Any help would be greatly appreciated
I am getting null as value after desearlise of the callout response
 
List<Map<String, Object>> myMaps = new List<Map<String, Object>>();
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://priyesh01.github.io/SampleJson/JsonDummy.json');
request.setMethod('GET');
HttpResponse response = http.send(request);
System.debug('$$Response'+response.getBody());
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
   System.debug('I am able to hit end point');
   Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
       		myMaps = new List<Map<String, Object>>();
      List<Object> draftAlarmsRequest = (List<Object>) results.get('draftAlarmsRequest');
  system.debug('$$ draftAlarmsRequest '+draftAlarmsRequest);
}
I am geeting null in the draftAlarmsRequest.

 
I am using Flow before save to update name field of opportunity and its causing my test classes fail FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]
Hi All,
I am learning the salesforce and wanted to understand the below which in the Trigger concept.

I get the below result
Code: [SELECT Id,Name,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
output: {0012w00000CWweoAAD=Account:{Id=0012w00000CWweoAAD, Name=Grapes & Melons}}

and then I tried accessing the Opportunities by useing the below code line
Code:
System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities);

output:
acctsWithOpps.get(a.Id).Opportunities.size()=(Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b2mCAAQ, Name=Grapes & Melons Opportunity}, Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b2mMAAQ, Name=Grapes & Melons Opty}, Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b44SAAQ, Name=Grapes & Melons Opportunity})

How do i need to write the code to access each opportunity field details if i wanted to access. Let say I wanted to check a particular type of opportunity is existed or not and then do an operation.

Thank you!
Hello, I have two record types: X1 and X2

Controling picklist: Type has values 1, 2, 3, 4, 5
Dependent picklist: Subtype has A, B, C, D, E

For record type X1 I need the Subtype value to equal A if Type equals value 1.
For record type X2 I need the Subtype alue to equal B if Type equals value 1.

Is this possible in any way or do I have to create twice as much values in Type field availible only for some record types?
Hello everyone!

I am using apex:commandLink for a VF list page but it is opening the wrong edit page. The edit button is currently opening the edit opportunity product details and I need it to open the Product Line Item schedules instead (this page: /related/OpportunityLineItemSchedules/view). I have tried using different actions, a custom URL, and a ton of other options but I can't get anything to work. Does anyone have an answer? 

Thanks! 

VF page with the button: 
User-added image
Current Code:
<apex:page standardController="Opportunity" action="{!getOLIS}" tabStyle="Opportunity" extensions="OpportunityScheduleExtension" lightningStylesheets="true">
 <apex:form >
     <apex:pageBlock >
     <apex:pageBlockTable value="{!lstOLIS}" var="lst" >
          <apex:column headerValue="Product" value="{!lst.OpportunityLineItem.Product2Id}"/>
          <apex:column headerValue="Date" value="{!lst.ScheduleDate}"/>
          <apex:column headerValue="Revenue" value="{!lst.Revenue}"/>
         <apex:column ><apex:commandLink action="{!edit}" value="Edit" id="EstablishOpportunityLineItemSchedules"/></apex:column>
     </apex:pageBlockTable>
     </apex:pageBlock>
 </apex:form>
</apex:page>
 
public with sharing class OpportunityScheduleExtension {
    Opportunity objOpp;
    public list<OpportunityLineItemSchedule> lstOLIS {get;set;}
    public OpportunityScheduleExtension(ApexPages.StandardController controller) {
        this.objOpp= (Opportunity)controller.getRecord();
    }
    
   
    public void getOLIS(){
        lstOLIS = new list<OpportunityLineItemSchedule >();
        system.debug('objOpp---------->'+objOpp);
        for(OpportunityLineItemSchedule objOLIS:[Select Id, ScheduleDate, Revenue,
                                                 OpportunityLineItem.Product2.Name,
                                                 Description,Product_Name2__c, NAME__c
                                                 from OpportunityLineItemSchedule 
                                                 where OpportunityLineItem.OpportunityId =:objOpp.Id] ){
            lstOLIS.add(objOLIS);                                             
        }
    }    
}

 
I tried learning Apex coding only to realize it will take a while to learn significant enough to create the triggers that I want which I can do with native declarative tools.

I want to know if Visualforce is faster to learn than Apex and if it's even possible to learn without learning Apex first? 
JS Controller :   method calling from Comp button.
 
createContact: function(component, event, helper){ //
         
         var createRecordEvent = $A.get('e.force:createRecord');
      
            createRecordEvent.setParams({
                'entityApiName': 'Contact',
                "defaultFieldValues": {
                    'Phone' : '415-240-6590'}
            });
            createRecordEvent.fire();
        
    }

Getting error : This page has an error. You might just need to refresh it. Action failed: c:getContactComp$controller$createContact [Cannot read property 'setParams' of undefined] Failing descriptor: {c:getContactComp$controller$createContact}



Requirmeent: on click of button, want to display create contact screen with default phone or any field.
Hi There,

I have created Email alerts with required informaiton(Template, sender and to Address etc.) on Work order object.
FYi, It redirected me to classic email alert page when clicked on "Creat new email alert" while I am building application in Lightning. I am using Play ground environent and with system administrator role.

Now once Email alert is created, I created a new process using process builder. Based on Criteria, I am calling a flow in action 1 and in action 2, i am trying to call a email alert. But when i select email alert, i dont see any existing email alerts coming up in drop down. I cross checked and objets referred are same for both email alert and process builder.

Am I missing anything with regards to permissions, page layout etc,.? Why my email alerts are not showing up in auto search control? Any help pls.?

Thanks,
Ravi
Hi All,
I'm little confused to choose  trigger/process builder with my scenario could you please help me with this.
I have parent and child objects with Lookup relationship. I need to auto update parent picklist field with conditions as follows
1.If parent has child records created in last 2 months from todays date update to valueA
2.If parent has child records in the past and there have not been any childs in last 2 months from todays date then ValueB
3.If parent never have any childs update to valueC

I hope we cant  use process builder for this and trigger is preferred to write on child object but which trigger context i should use.
Could any one please give me an idea how to do this.
thank you.
<apex:page controller="Task2Apex">
    <apex:form >
        <apex:pageBlock title="Account Name" >
            <apex:selectList value="{!selectedAccId}" size="1">
                <apex:selectOptions value="{!AccountNames}" />
                <apex:actionSupport event="onchange" action="{!showContacts}" reRender="op" />
            </apex:selectList><br/><br/>
            
         <apex:outputPanel id="op">
            <b><apex:outputText value="Related Contacts" rendered="{!renderPBtable}"/></b>
            <b><apex:outputText value="No Contacts on this Account" rendered="{!noContact}" style="color: red;"/></b>
            <apex:pageblockTable title="Contacts" value="{!conlist}" var="sc" id="relatedContactsBlock" rendered="{!renderPBtable}">
                <apex:column value="{!sc.name}"/>
                <apex:column value="{!sc.phone}"/>
            </apex:pageblockTable>
        </apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class Task2Apex {

    public Id selectedAccId{get;set;} 

    public List<Contact> conlist {get;set;}   
    
    public Boolean renderPBtable {get;set;}
    
    public Boolean noContact {get;set;}

    public List<SelectOption> getAccountNames() {
        List<SelectOption> accOptions= new List<SelectOption>();
        system.debug(selectedAccId);
        accOptions.add( new SelectOption('','--Select--'));
        for(Account acc : [select Id,name from Account ] ) {
            accOptions.add(new SelectOption(acc.Id,acc.name));
        }
        return accOptions;
    }

    public PageReference showContacts(){
        conlist=[select name,phone from Contact where Accountid=: selectedAccId];
        if(conlist.size() > 0)
        {
            renderPBtable = true; 
            noContact = false;
        }
        else
        {
            renderPBtable = false;
            noContact = true;
        }
        return null;   
    }
  
}

I want to Include edit link on each child record.
Thanks in Advance.
I have a situation where i want to display the field value which should show sub string value of field inside aura iteration eg email field is test1.user1@gmail.com i want to display value as test1.user1. ho can i achieve this?
<th data-label="Id" scope="row">
          <div class="slds-truncate" title="Cloudhub">
        <a href="{!'/one/one.app?#/sObject/'+ singleRec.Id + '/view'}" target="_blank">{!singleRec.Email}</a>                                           </div>
                                        </th>

 
Hello, I need to delete certain documents. This is the code I've been using:
    List<ContentDocumentLink > docs;
        docs = [SELECT Id, Linkedentity.name, Linkedentity.id,ContentDocument.CreatedDate  
                FROM contentDocumentLink 
                WHERE Linkedentityid 
                IN (SELECT Id FROM lead where createddate < Last_N_Days:7  ];  
            delete docs;

After I execute this, it looks like the contentDocumentLinks become deleted, however my storage usage is still the same number and percentage.Will the above code completely delete those files? 
On a visual-force page of a workorder record, I've to display list of workorders created for the same location where the createddate is within the last 30 days of the creationdate of the current record.
For ex: If the current record was created on Jan 31st for a location A, I want to display all the workorders that were created from Jan 1st to 31st for location A.

This is the query I've but it obviously displays records created in last 30 days but not the records created in last 30 days of createddate of the current record. How can I modify my query?
CWOs=[SELECT Id, Status, location.Name, createddate FROM WorkOrder WHERE location.Name = : getwo().location.Name and id != : getwo().id and recordtype.name = 'Child' and createddate = LAST_N_DAYS:30 ORDER BY CreatedDate asc];

 
  • April 13, 2020
  • Like
  • 0
<apex:page standardController="Campaign" extensions="ForSaleLookupOnCampaignController"> 
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");                  
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
   
}
    </script>
    <apex:form >
        <apex:pageBlock >
             <apex:pageBlockButtons >
                <apex:commandButton value="Save" style="width: 100px; height: 30px" action="{!processSelected}" rerender="table2"/>
            </apex:pageBlockButtons>
            <p style="font-size: 15px;font-weight: bold;">Select FID :</p><apex:inputfield style="width: 200px; height: 30px" value="{!Campaign.For_Sale__c}" id="forsaleid"/><br/>
            <apex:pageblockSection title="Related Campaign Members" collapsible="false">
                <apex:pageBlockTable value="{!wrapcontactList}" var="conWrap" id="table" title="All Related Campaign Members">     
                    <apex:column >
                        <!--apex:facet name="header">
                          <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                         </apex:facet-->
                        <apex:inputCheckbox value="{!conWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!conWrap.con.Name}" />
                    <apex:column value="{!conWrap.con.Account.name}" />
                </apex:pageBlockTable>
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
public class ForSaleLookupOnCampaignController { 
    public List<CampaignMember> Campaignmemberlist{get;set;} 
    public Campaign cmp {get;set;} 
    public List<wrapContact> wrapcontactList {get; set;}
    public List<Contact> selectedcontacts{get;set;}
    set<id>conid=new set<ID>();
    public String ID { get; set;}
    set<id>ForSaleid=new set<id>();
    public ForSaleLookupOnCampaignController (ApexPages.StandardController standardControllerParam) {
        this.cmp = (Campaign)standardControllerParam.getRecord();
        Campaignmemberlist = [SELECT id,name,Campaignid,Company__c,type,For_Sale__c,Contact.For_Sale__c  FROM CampaignMember WHERE Campaignid = : ApexPages.currentPage().getParameters().get('id') ];
        for(CampaignMember cm:Campaignmemberlist){
            conid.add(cm.ContactId);
            ForSaleid.add(cm.For_Sale__c);
        }
        //
        if(wrapContactList == null) {
            wrapContactList = new List<wrapContact>();
            for(Contact c: [select Id,Name,Account.name,For_Sale__c from Contact where id=:conid]) {
                wrapContactList.add(new wrapContact(c));
            }
        }
        
    }
    public PageReference processSelected() {
        PageReference pr;
        selectedcontacts = new List<contact>();
        system.debug('for sale '+cmp.For_Sale__c);
        for(wrapContact wrapcontactObj : wrapcontactList) {
            if(wrapcontactObj.selected == true) {
                selectedcontacts.add(wrapcontactObj.con);
                
            }
        }
        for(contact s:selectedcontacts){
            s.For_Sale__c=cmp.For_Sale__c;
        }
            try{
                
                database.update(selectedcontacts);
                
            }catch( Exception e ){
                ApexPages.addMessages(e);
            }
            system.debug('selectedcontacts'+selectedcontacts);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'FID Update on Contact'));
      return pr;   
    }
    public class wrapContact {
        public Contact con {get; set;}
        public string forsaleid{get;set;}
        public Boolean selected {get; set;}
        
        public wrapContact(Contact c) {
            con = c;
            forsaleid=c.For_Sale__c;
            selected = false;
        }
    }
}
How should I show success message on VF Page
& another thing is
here <apex:inputfield style="width: 200px; height: 30px" value="{!Campaign.For_Sale__c}" id="forsaleid"/> when I click on button & page is load the value is already populate on this but I want to clear this value when page populate how can I do that?


 

I have 2 array

-> The First array consists of all the values.

-> In the second array, consist of selected values  Here I need to filter the value which is already present

I have a picklist which gives the below error when trying to select a value.
User-added image
Component:
<lightning:select aura:id="Productreg" name="select" label="Gender" onchange="{!c.onSelectChange}">
                        <option value="">choose one...</option>
                        <option value="male">Male</option>
                        <option value="female">Female</option>

Controller:
 onSelectChange: function (cmp, evt, helper) {
        //alert(cmp.find('select').get('v.value') );
        
        var genderVal = cmp.find('select').get('v.value');
        cmp.set('v.genderVal',genderVal);
        
    },
    afterload: function (cmp, evt, helper) {
        alert('new function test' );
        
        
        
    },
    handleCreateProductReg: function (cmp, evt, helper) {
        
        var CreatePassableItem = component.get('c.CreatePassableItem');
        $A.enqueueAction(CreatePassableItem);
        console.log(CreatePassableItem);
        
        var prodObj = cmp.get("v.ProductRegObj");
        console.log(prodObj);
        var genderVal = cmp.get("v.genderVal")?cmp.get("v.genderVal"):''; 
        prodObj.Gender__c = genderVal;
 
Hi,
I have 2 objects which are completely unrelated to each other. Howerver, they both are related to the Contact object. How do I find the records from Contact which are common to both the objects.
Hi,
I am working on lightning flow and i have to validate a custom LWC component value while my Flow is in action ; if user has selected the value before clicking on next button.
For standard flow component there are ways to validate the value but how can we validate for custom component ?

Any suggestions..

Thanks.
Hi, 
I am working on Lightning datatable. Is there any way to default select the checkbox in lightning datatable? 

User-added image
I have created a lightning component on Opportunity record page that is visible on desktop but not on Mobile app.
i can preview the component fine in Lightning App builder for phone form factor. But it is not visible on the device. 
What am i missing here?
Hi

I have got stuck in a process where cases should be opened on new case comments but only on some criteria, listed below:

1. Open if comment is from a customer
2. Do not open if comment is posted by a support engineer
3. Do not open if the comment is made by a flow 

I seem not to be able to filter out the different user types and the case is opened regardless of who the user is. I have tried using the field 

HasCommentsUnreadByOwner

but this does not take in consideration which type of user made the comment. How can I get a process builder to look at the user type for this?

#Sales Cloud#Batch Apex Class

I have a batch class and it throws an error for different picklist value assignment. Invalid integer whereas those fields are picklist and should be dealt as text field.
Please check the class...
Error 1 : invalid integer for 'noch k.A' & '6-25' and so on.
Error 2 : it is also not updating the field partially. no partial success.
Error 3. It's not triggering an email from Finish method. i tried then in execute method. it does not trigger there as well.

I shall be grateful to you for your kind cooperation. Thanks in advance.

global class PicklistCleaning implements Database.Batchable<sObject>, database.stateful {
    Exception[] errors = new Exception[0];
    global Database.QueryLocator start(Database.BatchableContext bc) {
        // collect the batches of records or objects to be passed to execute
        string Query = 'select NoOfEmployees__c from Account where NoOfEmployees__c !=\'noch k. A.\' AND NoOfEmployees__c !=\'1 - 5\' AND NoOfEmployees__c !=\'6 - 25\'AND NoOfEmployees__c !=\'26 - 50\' AND NoOfEmployees__c !=\'51 - 250\' AND NoOfEmployees__c !=\'251 - 500\' AND NoOfEmployees__c !=\'501 - 1.000\' AND NoOfEmployees__c !=\'1001 - 9999\' AND NoOfEmployees__c !=\'> 10.000\'';
        system.debug(Query);
            return database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext bc, List<Account> records){
        // process each batch of records
        List<Account> Acclist = New List<Account>();
        for(Account Acc : records){
            if(acc.NoOfEmployees__c == null || acc.NoOfEmployees__c == ''){ 
                acc.NoOfEmployees__c = 'noch k. A.';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=5 || integer.valueof(acc.NoOfEmployees__c) == 1){
                acc.NoOfEmployees__c = '1 - 5';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=25 || integer.valueof(acc.NoOfEmployees__c) >= 6){
                acc.NoOfEmployees__c = '6 - 25';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=50 || integer.valueof(acc.NoOfEmployees__c) >= 26){
                acc.NoOfEmployees__c = '26 - 50';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=250 || integer.valueof(acc.NoOfEmployees__c) >= 51){
                acc.NoOfEmployees__c = '51 - 250';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=500 || integer.valueof(acc.NoOfEmployees__c) >= 251){
                acc.NoOfEmployees__c = '251 - 500';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=1000 || integer.valueof(acc.NoOfEmployees__c) >= 501){
                acc.NoOfEmployees__c = '501 - 1.000';
            }
            if(integer.valueof(acc.NoOfEmployees__c) <=9999 || integer.valueof(acc.NoOfEmployees__c) >= 1001){
                acc.NoOfEmployees__c = '1001 - 9999';
            }
            if(integer.valueof(acc.NoOfEmployees__c) >=10000){
                acc.NoOfEmployees__c = '> 10.000';
            }
            Acclist.add(acc);
        }
        try{
           Database.upsert(Acclist, false);
           Database.SaveResult[] sr = Database.update(Acclist, false);
            for(Database.SaveResult srr :  sr){
                if(srr.isSuccess()){
                    system.debug(srr.getId());
                }
                else{
                    for(Database.Error err : srr.getErrors()){
                        system.debug(err.getFields());
                        system.debug(err.message);
                        system.debug(err.getMessage());
                    }
                }
            }
        }
        catch(system.dmlexception e){
            errors.add(e);
            if(!errors.isEmpty()){
           Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           string[] adds = new string[]{'////@test.com///'};
            mail.setSubject('Errors occurred during batch process.');
            mail.setPlainTextBody(''+errors);
            mail.setToaddresses(adds);
             List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
             mails.add(mail);
            if(mails.size() > 0){
                Messaging.sendEmail(mails);
            }
       }
        }
    }    
    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
         if(!errors.isEmpty()){
           Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           string[] adds = new string[]{'///////@test.com///'};
            mail.setSubject('Errors occurred during batch process.');
            mail.setPlainTextBody(''+errors);
            mail.setToaddresses(adds);
             List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
             mails.add(mail);
            if(mails.size() > 0){
                Messaging.sendEmail(mails);
            }
       }
    }    
}

this is my code i want to give count of contacts associate with account but when i changed contacts account(lookup) it update new owner count value but not updating the value in old account count

this is my code
handler:
public class ContactRollupSummaryHandler {
    public static void afterInsert(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    public static void afterUpdate(list<Contact> contacts,Map<Id,Contact> oldMap){
        list<Contact> conlist = new list<Contact>();
        for(Contact c: contacts){
            if(c.AccountId != oldMap.get(c.Id).AccountId){
                conlist.add(c);
            }
        }
        if(conlist.size()>0){
            NumberofContacts(conlist);
        }
    }
    public static void afterDelete(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    public static void afterUndelete(list<Contact> contacts){
        NumberofContacts(contacts);
    }
    
    
    public static void NumberofContacts(list<Contact> con){
        set<id> accIds = new set<id>();
        for(Contact c: con){
            if(c.AccountId != null){
            accIds.add(c.AccountId);
            } 
        }
        
        if(accIds.size()>0){
            list<Account> acclist = new list<Account>();
        for(Account ac: [SELECT id,Number_of_Contacts__c,(SELECT id from Contacts) from Account where id IN:accIds]){
            ac.Number_of_Contacts__c = ac.Contacts.size();
            acclist.add(ac);
        }
            if(acclist.size()>0){
                update acclist;
            }    
        
        }
    }

}

Trigger:
trigger ContactTrigger on Contact (after insert,after update,after delete, after undelete) {
    if(Trigger.isAfter && Trigger.isInsert){
       ContactRollupSummaryHandler.afterInsert(Trigger.new);
    }
    if(Trigger.isAfter && Trigger.isUpdate){
       ContactRollupSummaryHandler.afterUpdate(Trigger.new,Trigger.oldMap);
    }
    if(Trigger.isAfter && Trigger.isDelete){
       ContactRollupSummaryHandler.afterDelete(Trigger.old);
    }
    if(Trigger.isAfter && Trigger.isUndelete){
       ContactRollupSummaryHandler.afterUndelete(Trigger.new);
    }
    
}
CLASS:
public class Currencyconverter {
    public static decimal CurrencyconverterfromEUROtoINR(decimal eur){
        decimal inr = 0.0;
        HTTP http = new HTTP();
        HTTPRequest req= new HTTPRequest();
        req.setEndpoint('https://api.exchangeratesapi.io/latest');
        req.setMethod('GET');
        HTTPResponse res = http.send(req);
        Map <string,object> Jsonbody=(Map <string,object>)Json.deserializeUntyped(res.getBody());
        system.debug(Jsonbody);
        Map <string,object> rates=(Map<string,object>)Jsonbody.get('rates');
        decimal conversionrate= (decimal)rates.get('INR');                    
        inr = eur * conversionrate;      
        return inr;
    
}
}

Testing at anonymous window:
decimal conversionrate = Currencyconverter.CurrencyconverterfromEUROtoINR(150);
system.debug('conversionrate'+conversionrate);

ERROR:
System.NullPointerException: Attempt to de-reference a null object
Hi All,

I have a requiremnt to send bell notification once many records gets inserted(apprx 900) on weekly basis. so that the users will get to know new records are inseted 
Hi,

I have a requirement to make it so that users can only select a certain Opportunity Record Type depending on what the Account Record type is.  We have 3 Account Record Types: Prospecting, Sales Pipeline and Onboarding.  I need these 3 Account Record types limited to the following Opportuinity Record Types:

(Acount Record Type) - (Oppportiunity Record Type)
Prospecting - Original, Expansion
Sales Pipeline - Upsell
Onboarding - Customer, Upsell

I know I need to write an IF statement for each picklist value, but I'm running into trouble when trying to bring in the second variable (Oppportunity Record Type).

Thanks!
I am trying to create a validation rule that stops a second person being added to the Account Team if there is already someone else on the Account Team in that same role.
 
For example, there should never be more than 1 Pre-Sales Lead (Account Team role) on any 1 SFDC Account. 
 
Any "No Code" approach possible? Validation rules, as VR are now available onto AccountTeamMember object? Can someone help figure out a way for this?   
 
#AwesomeAdmins  #Ask An Expert  #DiscussSalesforceQueries
Hey All,

I've been searching for days for a solution to my problem. All I can seem to find is a couple people having a similar issue with no clear resolution. I set my OWD settings to "Public Read Only" for my accounts object. However, users who are not owners of the accounts can still edit the fields. So I thought ok, lets try setting it to "Private" and just share with a specific user role that has "Read Only" access. I ran into the same problem. The users in that role could still edit the fields on the account. My profile permissions are not set to "View All" or "Modify All." The profile object settings for Accounts are "create, read, edit" only. 

I'm not kidding when I say I've read hundreds of posts about sharing settings and permissions, and I genuinely have no idea what I am missing. And to make sure this wasn't something specific with the accounts object, I ran into the same issue with leads. This is maybe a huge error in my SF org or it is a small setting somewhere else that I have missed.

Please help!

P.S.
I checked the "Sharing Hierarchy" and it is telling me the user should have "Read Only" access...but they don't.
I am attempting to integrate Salesforce using some middleware. 

What the integration does it take an Excel sheet, and from that sheet create a Work Order, Service Appointment and Assigned Resource record for each row.

When I run this integration, the Work Order and Service Appointments are created as expected - however, the AssignedResource creation fails, with the following error message: 
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:FSL.TR021_AssignedResource_AfterInsert: System.LimitException: Apex CPU time limit exceeded:--

Judging from this error message, it seems that there is a trigger on the AssignedResource object which is exceeding the CPU time limit. The trigger is part of the FSL managed package, so it can't be disabled or changed.

Does anyone know what this trigger does, and if there is a way to disable it or work around the issue to avoid the error?
Hi All,

I have created below formula field in the flow for field assignment for screen component in flow. Formula is working fine for picklist field but formula is not working for multi select picklist.  

Picklist formula :  IF((TEXT({!LanguageChoice})==NULL), TEXT({!Get_Account.Language__c}),TEXT({!LanguageChoice}))  

Multiselect Picklist formula: IF((TEXT({!VehicleChoice})==NULL), TEXT({!Get_Account.Vehicle__c}),TEXT({!VehicleChoice}))

Thanks,
Anil Kumar 
Hello,
 
I have a custom field in accounts, a pick list with multiple choice option. For every item that has been chosen, I want to create a related case. Could someone give me a hint? Please not a whole code, I want to do it on my own but I don't know how :D
 
Thanks a lot for your time
Since being upgraded to the Spring '20 release, a process that we have has stopped saving BR() in a formula to the Rich Text field it is populating. 

Formula in Process:
"... next steps." + BR() + "<b>Next Step - ..."
Saved value on the record:
"... next steps.<b>Next Step - ..."
Furthermore, the saved value is different in scratch orgs:
... next steps.<br>&lt;/b&gt;Next Step - ..."
Expected output:
... next steps._BR_ENCODED_<b>Next Step - ..."
The last known time we have it saving correctly is Friday before our Spring 20 release. We began having abnormal results the morning after the release. The last time this process was modified was 12/18/2019.

Was there a change in behaviour that I missed included with this release? Has anyone else experienced this issue?