• @ M Coder
  • NEWBIE
  • 70 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 34
    Questions
  • 23
    Replies
Hi Team , 
i want to iterate array and check each and every columns and segregate nulls . can you please post me the code how can we acheive it

i have an Array of objects which has 5 rows. i would like to split array  based on nulls into  two lists .
1. list named baddatalist which have nulls or blank records for example say 4 and 5th one highlighted 
2. goodlistarray - which donot have blank or nulls  

data= [
  {"Vehical_Name__c":"Audi","firstName":"James","lastName":"bond","Address":"1501 street","country__c":"USA","state__c":"Alberta","city":"test","phone_number__c":"1234569994"},
  {"Vehical_Name__c":"Benz","firstName":"ravi","lastName":"bond","Address":"1502 street","country__c":"USA","state__c":"Alberta","city":"test","phone_number__c":"1234569994"},
  {"Vehical_Name__c":"ace","firstName":"sam","lastName":"test1","Address":"1503 street","country__c":"USA","state__c":"Alberta","city":"test","phone_number__c":"1234569994"},
  
  {"Vehical_Name__c":"","firstName":"hans","lastName":"bond","Address":"1504 street","country__c":"USA","state__c":"Alberta","city":"test","phone_number__c":"1234569994"},
  
  {"Vehical_Name__c":"Commercial","firstName":"James","lastName":"bond","Address":"1505 street","country__c":"USA","state__c":"","city":"","phone_number__c":"1234569994"}
  ]
Hi Team , 

Can you fix this if  User  select a future date say tmoro date it should throw an error in UI.  user should only select todays date or previous date

somehow my snippet is working wrong

<lightning-input  type="date" name="Date entry" class="dateCls" value={Dateentry} data-name="Dateentry" onchange={handledate} > </lightning-input>
    
 handledate(event){
        console.log('event==called=');
        if(event.target.name === "Dateentry") {
          let psdate = this.template.querySelector(".dateCls"); 
            var today  = new Date();
            console.log('today==+++=='+today);
            if(event.target.value > today)
            {
               psdate.setCustomValidity("Please Select old Date.");
            }
            else{
            this.SelectedDate = event.target.value;
            console.log('this.SelectedDate =+==='+this.SelectedDate );
            }
        }
    }        
 
Hi Team ,
i would like to Restrict selecting future dates apart from today on lightning-input field in lwc 

 <lightning-input  type="date" name="Date Bought" variant="label-hidden" label="Date Bought"  value={DateBought} data-name="DateBought" > </lightning-input>
         
Expected: 
let us suppose say today is June 18 , i should be able to select old dates less than June 18 like june 17, 16,15 . 

User-added image
i should nt be able to select future dates like June 19 ...  it should be blur or non selectable like below for future dates 
User-added image
can you please let me know how to do it,
Hi Team , 
# urgent resolution needed.....
i am getting this problem , i want to send my date fields vale to my apex class and save to database. 
this is my json look like in console 
final data==[{"Name":"sita","first_date__c":"30-09-2023","second_date__c":"20-09-2023","attributes":{"type":"placing__c"}}]

and its fails with below error message not understanding how to proceed.... let us say if i have 100+ records how to do it 

{"status":500,"body":{"exceptionType":"System.JSONException","isUserDefinedException":false,"message":"Cannot deserialize instance of date from VALUE_STRING value 30-09-2023 or request may be missing a required field","stackTrace":"(System Code)\nClass

@Thanks in adv
I am getting this warning in VS code due to my which my simple apex class is not getting called in JS when i do a import . 

my apex class: 
public with sharing class CarController {

@AuraEnabled(Cacheable=true)
    public static List<Car__c> getCars(){
    
    return[SELECT Id, Name, MSRP__c, Description__c,Category__c, Picture_URL__c FROM Car__c];
    }
}

warning comming: 
Validate CRUD permission before SOQL/DML operation (rule: Security-ApexCRUDViolation)", 

My analysis: I am doing this in my own org via system admin . All the fields have FLS for the profile and class access at profile level. 

if i change the soql to 
 return[SELECT Id, Name, MSRP__c, Description__c,Category__c, Picture_URL__c FROM Car__c with SECURITY_ENFORCED];
       
then also i am unable to access my class in js import statement . 

can anyone please modify it what has to be done 

 
I am getting below error if i pass the template id as anyone of  below 
   mail.setTargetObjectId(Userinfo.getUserId());
   mail.setTargetObjectId(cs.owner.Id); 
   mail.setTargetObjectId(cs.ContactId);
except if i pass any dummy contact id  i am getting emails .
 mail.setTargetObjectId('0037f00001ZAvc9');

Error : 
Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Test_Case: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.:

code:
Trigger Test_Case on Chh__c (after insert) {



//newList contains case records which are inserted from above missin code

// piece of code starts here in 
 if(newList.size()>0)
    {   
        
        Map<String,Id> templateList  = new Map<String,Id>();
        for(EmailTemplate e : [Select Id,Name from EmailTemplate where Name LIKE 'Test Case%'])
        {
            templateList.put(e.Name,e.Id);
        }
    
    List<Messaging.SingleEmailMessage> masterListMails =  new List<Messaging.SingleEmailMessage>();
    for(Case cs :[select id,Owner.Id,ContactId,Account.Place__c,Account.Ac_Owner__r.email,subject from case where id in: newList AND subject ='Test Case' ]) 
       {
        if((cs.Account.Place__c == 'Banglore') && ((cs.Account.AC_Owner__r.email !=null && cs.Account.AC_Owner__r.email !='')))
        {
            system.debug('if Called====');
            list<String> sendTo = new list<String>();
           if(cs.Account.AC_Owner__r.email !=null )
            sendTo.add(cs.Account.AC_Owner__r.email);
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(sendTo);
        /*  mail.setTargetObjectId(Userinfo.getUserId());
            mail.setTargetObjectId(cs.owner.Id); 
            mail.setTargetObjectId(cs.ContactId);*/
            mail.setTargetObjectId('0037e00001ZAxc9');
            mail.setWhatId(cs.Id); 
            mail.setTreatTargetObjectAsRecipient(false);
            mail.setSaveAsActivity(false);
            mail.setTemplateId(templateList.get('Test Case')); 
            masterListMails.add(mail);
        }
       }    
       // Sends mass emails
        if(masterListMails.size()>0)
       Messaging.sendEmail(masterListMails);
     } 
}
Hi Team , 
scenario : I have a look up field on account to User object named
 Ac owner
so when ever a case record is created manually with this criteria 
Subject="Risk"  and Account.Type= "Other" then i have record trigger flow  on case which send emails on below conditions.
User-added image

1.If There is no Ac owner (lookup to user ) or Ac owner is null then i dont want this flow to run.
2. if Account has Ac owner (lookup to user )and his manager then emails will be triggered to Ac owner and his manager email ids 
3. if Account has Ac owner (lookup to user )  then emails will be triggered to Ac owner email id 
 
Issue is 1 and 3 are not working properly. can you help me fix 

my flow screenshots
User-added imageUser-added imageUser-added imageUser-added image

Thanks for helping me in Advance

 
Hello Team , 

I want to show a case link while sending out email from flow which we normally use in html email templates and below is the format.

Dear Team,
A New case has been created. Please find the link to the case
{!Case.Link} 

Issue : {!Case.Link}  is not comming from flow 
 
i have build  a new Text Template in flow under body, i selected the new text template and how to display the case link dynamically is what i need. 
User-added image
Note: Using email alert will not fit my requirements as i have recipients which email alert will not be helpful

Thanks in Advance
Hello Team , 

How to do this scenario using FLOWS???

when ever a  User is de activated ,i need to remove all the permision sets and Permission Set License Assignments assigned to that purticular user 
How to write a soql query to get All the records in Open Activites which are related list to a account.

User-added image 

 
Hello Guys , 
Basically i need to pass email ids present in my custom metadattype to CC in mailing logic when ever my label is IND .
in simple i need to emails  cc (those email id.) to users.

i just kept my piece of code whether i am getting the below error 

My custom metadatype contains two values 
1) label: Ind  2) Email_Address__c = ram@gmail.com sam@gmail.com hello@gmail.com
 
My piece of code  
  //calling custom metadata type
   map<string,string> emailmap = new map<string,string>();
   for(Email__mdt ce : [SELECT Label,Email_Address__c FROM Email__mdt])
   {  
   emailmap.put(ce.Label , ce.Email_Address__c);
   system.debug('emailmap====='+emailmap);
   }
    
   //Splitting CC email addresses and adding in array
     String[] ccAddresses = new String[]{};
    if(!emailmap.isEmpty())
    {
    system.debug('Map has values....');
    for(string ev:emailmap.Values())
      {
        system.debug('ev======'+ev);
        list<string> emailid = ev.split(',');
           ccAddresses.addAll(emailid);
        system.debug('ccAddresses======'+ccAddresses);
      }
    }
    
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(sendTo);
        mail.setTargetObjectId(Userinfo.getUserId());
        mail.setCCAddresses(ccAddresses);
        mail.setSaveAsActivity(false);
        mail.setWhatId(leadRecId );
       Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Error I am getting: 
System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : ram2929@gmail.com sam@gmail.com hello@gmail.com 

My analysis: i think split string is not working fine in my logic , can anyone please modify the piece of code.

 
Hello Guys , 

my scenario : 

On click of button (quick action) on account layout in lightning , based on the account id  as input , my dashboard data has to be seen in a new window  . 
basically i need to pass record id dynamicaly to dashboard
for example: account has 3 opportunities and 3 assets

User-added image
Hello All , 
How to write trigger ??

Under Account we have open activities, where we create Task and events. 
Scenario: i need to take Duedate value which is comming nearby from the below ones into a customfield Named NearbyDate__c. 

I need to write Trigger logic insuch away that for N number of Activities if i either Add or delete the activities it should sort and  gimme the result. 

for example: 

My output  should be from below example
NearbyDate__c = 9/15/2020 

User-added image

can anyone show some insights on this please. 

@thanks in adv
Hello Folks , 

Is there any soql query to retrieve all my Pagelayout Names under a recordtype in salesforce . 

or whats is the easiest way to find them . 

 
I want my workflow rule to fire based on below criteria. 
Scenario : User on  creation of case with type "Mechanical" and created time should NOT be in between  10 AM to 6 PM.  in other than above mentioned hrs i have a wf field update which will fire. I am stuck with rule how to fire .

My formula: 
ISPICKVAL( Type ,'Mechanical') && (VALUE(MID(TEXT(CreatedDate+ 0.2208),12,2))  <10.00 && VALUE(MID(TEXT(CreatedDate+ 0.2208),12,2)) < 22.00)

if i create a case at 11pm , we get VALUE(MID(TEXT(CreatedDate+ 0.2208),12,2) = 23. 

can you please correct my formuale
Hello Folks , 

I have a requirement where i need to write a formula field in workflow based on below scenario. 

part 1:My office hours are from 9AM to 6PM .
part2:  apart from these hours any New  lead  created , i want to assign alead owner to a queue (This we can do via a field update).

solution i need is for part 1 , how to write a formula for creating a new lead other than office hours and weekends to trigger my wf rule . 
can any one please help.
My formula criteria should be like :

AND (ISPICKVAL(Status, "New"), time should not be in between 9 AM to 6PM)
Hello Friends , 

I am getting the below issue in Vscode after new version update . 

"The JAVA_HOME environment variable points to a missing folder. For information on how to setup the Salesforce Apex extension, see Set Your Java Version."

I have my java version in below path :
User-added image

i have installed again ,  vscode cli , extention pack . 

can you please tell the highlighted one is corect ?
User-added image
do i need to put anything in workspace as well ???

please help me .... if any one wanted i can screen share you in gmail , my id is salesforceseekar@gmail.com .... please feel free to ping as i wanted to resolve this issue .

 
Hello Folks , 

if anyone has any idea please send me an email to salesforceseekar@gmail.com will screenshare show you the error , not understanding how to reolve.


I am getting Vscode  performance issue , i am unable to do any work due to this , i have installed the steps given below .
https://github.com/forcedotcom/salesforcedx-vscode/issues/2110 . 

please find the below error screen shots
User-added imageUser-added imageUser-added image
how to a display lookupfield and picklist values in Lightning datatable - LWC??? 

Any sample code please
Hi folks any one facing  " Extension causes high cpu load " when i updated the vs ocde to new version. 

I have copied the files to c:/user/admin as said in below 
https://github.com//forcedotcom/salesforcedx-vscode/issues?utf8=%E2%9C%93&q=is:issue+state:open+%22Extension+causes+high+cpu+load%22

my main issue is : if i  deploy anything to the server , it keeps on running ,  but in backend code is getting deployed but in front end it will not show that operation completed.
 
Hi Team ,
i would like to Restrict selecting future dates apart from today on lightning-input field in lwc 

 <lightning-input  type="date" name="Date Bought" variant="label-hidden" label="Date Bought"  value={DateBought} data-name="DateBought" > </lightning-input>
         
Expected: 
let us suppose say today is June 18 , i should be able to select old dates less than June 18 like june 17, 16,15 . 

User-added image
i should nt be able to select future dates like June 19 ...  it should be blur or non selectable like below for future dates 
User-added image
can you please let me know how to do it,
One component is publishing the id of the contact and Other component needs to Update Account Id in the the Contact to Null based on the Id Published through Lightning Message Service.
======================================================
Html File:::
<template>
  <lightning-card title="Record view from for Account">
    <lightning-layout>
      <lightning-layout-item>
        <lightning-record-view-form
          record-id={contacts}
          object-api-name="Contact"
        >
          <lightning-output-field
            field-name="FirstName"
          ></lightning-output-field>
          <lightning-output-field
            field-name="LastName"
          ></lightning-output-field>
          <lightning-output-field
            field-name="AccountId"
          ></lightning-output-field>
          <lightning-output-field
            field-name="LastModifiedById"
          ></lightning-output-field>
        </lightning-record-view-form>
      </lightning-layout-item>
    </lightning-layout>
  </lightning-card>
</template>
======================================================
======================================================
 
JS File::::
import { LightningElement, wire } from "lwc";
import UpdateContact from "@salesforce/apex/AccountContactController.updateContact";
import {
  subscribe,
  unsubscribe,
  MessageContext
} from "lightning/messageService";
import SimpleChannel from "@salesforce/messageChannel/SimpleChannel__c";
export default class DisplayContact extends LightningElement {
  subscription = null;
  strCapturedText;
  @wire(MessageContext) messageContext;
  @wire(UpdateContact, { contactId: "$strCapturedText" }) contacts;
  subscribeToMessageChannel() {
    if (!this.subscription) {
      this.subscription = subscribe(
        this.messageContext,
        SimpleChannel,
        (message) => this.setCaptureText(message)
      );
    }
  }
  unsubscribeToMessageChannel() {
    unsubscribe(this.subscription);
    this.subscription = null;
  }
  connectedCallback() {
    this.subscribeToMessageChannel();
  }
  // This method will run once the component is removed from DOM.
  disconnectedCallback() {
    this.unsubscribeToMessageChannel();
  }
  // This method will update the value once event is captured.
  setCaptureText(message) {
    this.strCapturedText = message.data;
  }
}
============================================================================================================
 
Apex Method:
@AuraEnabled(cacheable=true)
    public static Id updateContact(string contactId){
        Contact c = [select Id,AccountId from Contact where Id =: contactId];
        c.AccountId =Null;
        update c;
        return c.Id;
    }
======================
 I am getting the data from the publish component and able to show the data What I receive  but when I want to Update with the help of Apex Method it is not working and not showing any data
==============
 
Can anyone suggest me how to resolve this
I am getting this warning in VS code due to my which my simple apex class is not getting called in JS when i do a import . 

my apex class: 
public with sharing class CarController {

@AuraEnabled(Cacheable=true)
    public static List<Car__c> getCars(){
    
    return[SELECT Id, Name, MSRP__c, Description__c,Category__c, Picture_URL__c FROM Car__c];
    }
}

warning comming: 
Validate CRUD permission before SOQL/DML operation (rule: Security-ApexCRUDViolation)", 

My analysis: I am doing this in my own org via system admin . All the fields have FLS for the profile and class access at profile level. 

if i change the soql to 
 return[SELECT Id, Name, MSRP__c, Description__c,Category__c, Picture_URL__c FROM Car__c with SECURITY_ENFORCED];
       
then also i am unable to access my class in js import statement . 

can anyone please modify it what has to be done 

 
How to write a soql query to get All the records in Open Activites which are related list to a account.

User-added image 

 
Hello All , 
How to write trigger ??

Under Account we have open activities, where we create Task and events. 
Scenario: i need to take Duedate value which is comming nearby from the below ones into a customfield Named NearbyDate__c. 

I need to write Trigger logic insuch away that for N number of Activities if i either Add or delete the activities it should sort and  gimme the result. 

for example: 

My output  should be from below example
NearbyDate__c = 9/15/2020 

User-added image

can anyone show some insights on this please. 

@thanks in adv
Hello Folks , 

Is there any soql query to retrieve all my Pagelayout Names under a recordtype in salesforce . 

or whats is the easiest way to find them . 

 
how to a display lookupfield and picklist values in Lightning datatable - LWC??? 

Any sample code please
Hi,

I am trying to update records using data loader but not update,but when i do on single record its been updating.

I am written an trigger on task.
public class UpdateActivityHistoryCallCount {
    
    
    //To update the Count of Activity History in Lead object
    
    public static void countActivityHistoryOnLead(list<Task> newTaskList,list<Task> oldTaskList){
        system.debug('<<<<<test>>>>>');
        set<Id> LeadIds=new set<Id>();
        list<Lead> leadList=new list<Lead>();
        // Map<Id, String> error = new Map<Id, String>();
        
        if(trigger.isInsert || trigger.isUnDelete ){
            for(Task tsk:newTaskList){
                if(tsk.WhoId!=null){
                    if(string.valueOf(tsk.WhoId).startsWith('00Q'))
                        LeadIds.add(tsk.WhoId);
                    
                    
                }
                system.debug('Lead Ids' +LeadIds);
            }
        }
        if(trigger.isDelete || trigger.isUpdate){
            for(Task tk:oldTaskList){
                if(tk.WhoId!=null){
                    if(string.valueOf(tk.WhoId).startsWith('00Q'))
                        LeadIds.add(tk.whoId);
                    
                }
            }
            system.Debug('Test LeadIds' +LeadIds);
        }
        if(LeadIds.size()>0){
            for(Lead l:[select id,(select id,subject,Due_Date__c,CreatedDate
                                   from tasks where (subject='Call' and status='Completed'
                                                     and  Due_Date__c < Today) or (subject='Call' and status='Completed' and Due_Date__c =  null)  ) 
                        from lead where id in :LeadIds ])
                leadList.add(new lead(id=l.Id,Call_count__c=l.tasks.size()));
             update leadList;
            
            system.debug('Test');
        }
       
        
    }
    
    
Hi Everyone,

I am trying to reproduce the scenario as below link. Created a user as Salesforce Platform licence, trigger and when I logged in as Salesforce Platform User licence and created contact and updated not able to get the error.

https://www.sundoginteractive.com/blog/triggers-updating-restricted-records

Can anyone suggest me on this?

Thanks,
Sirisha
Hello,

First time to post so apologies if this is not in the correct area.

I am working on some code executed in anonymous that will insert some records in a charity's org.   The charity has job records, on those jobs exist shifts, and those shifts can have hours, for context.

The problem at the moment is that several jobs exist in the org which have shifts, but the hours were not correctly added, so I created the script below which can create those hour records and successfully copy over all the information that is needed from the shift/job record.  However, when I attempt to run this in the live version on a single record (which has 21 shifts)  I am getting Error:System.LimitException: Too many SOQL queries:101.

Below is my script:
List<GW_Volunteers__Volunteer_Job__c> badJobs = new list<GW_Volunteers__Volunteer_Job__c>();
badJobs=[SELECT Id FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__First_Shift__c!=NULL AND GW_Volunteers__Number_of_Completed_Hours__c=0]; //jobs that have shift with no hr
    
List<GW_Volunteers__Volunteer_Shift__c> needsHr = new list <GW_Volunteers__Volunteer_Shift__c>();
needsHr=[SELECT Id, GW_Volunteers__Start_Date_Time__c,GW_Volunteers__Duration__c, GW_Volunteers__Volunteer_Job__r.Volunteer__c FROM GW_Volunteers__Volunteer_Shift__c WHERE GW_Volunteers__Volunteer_Job__c in :badJobs]; //shift records with no hrs
for (GW_Volunteers__Volunteer_Shift__c s :needsHr){
    DateTime dT = s.GW_Volunteers__Start_Date_Time__c;
    Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
    GW_Volunteers__Volunteer_Hours__c hour = new GW_Volunteers__Volunteer_Hours__c(
        GW_Volunteers__Contact__c=s.GW_Volunteers__Volunteer_Job__r.Volunteer__c,
    	GW_Volunteers__Status__c='Completed',
    	GW_Volunteers__Hours_Worked__c=s.GW_Volunteers__Duration__c,
    	GW_Volunteers__Volunteer_Job__c=s.GW_Volunteers__Volunteer_Job__c,
        GW_Volunteers__Volunteer_Shift__c=s.Id,
    	GW_Volunteers__Start_Date__c=myDate,
        GW_Volunteers__End_Date__c=myDate
        
        
    
    );
    insert hour;
}

I believe I need to adjust this so that it is calling fewer queries, but I am not entirely sure what I can do other than put a LIMIT which won't really work for me as I need to run through all of the shifts on a given job record in one go.
When I change the shift query to the following, the script will run fine and insert hours corresponding to the correct shift records:
needsHr=[SELECT Id, GW_Volunteers__Start_Date_Time__c,GW_Volunteers__Duration__c, GW_Volunteers__Volunteer_Job__r.Volunteer__c FROM GW_Volunteers__Volunteer_Shift__c WHERE GW_Volunteers__Volunteer_Job__c ='a0T3Y00000SLivnUAD' LIMIT 10];

I am grateful for any assistance on this.

Thank you.
El
 
  • March 03, 2020
  • Like
  • 0
Hi,
I have an apex trigger to count the total Opportunities related to an Account and Sum of Opportunity Amount related to Account. I am trying to implement "after undelete" in my trigger. But it isn't working. Can someone help to do this?
Below is my Trigger

trigger OpportunityCount on Opportunity (after insert, after delete, after update, after Undelete) {
    Map<Id, List<Opportunity>> acctIdOpptyListMap = new Map<Id, List<Opportunity>>();
    Set<Id> acctIds = new Set<Id>();
    List<Opportunity> opptyList = new List<Opportunity>();
    if(trigger.isUpdate && trigger.isInsert){
        for(Opportunity oppty : trigger.New){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(trigger.isDelete){
        for(Opportunity oppty : trigger.old){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(acctIds.size() > 0){
        opptyList = [SELECT Amount, AccountId 
                     FROM Opportunity 
                     WHERE AccountId IN : acctIds];
        for(Opportunity oppty : opptyList){
            if(!acctIdOpptyListMap.containsKey(oppty.AccountId)){
                acctIdOpptyListMap.put(oppty.AccountId, new List<Opportunity>());
            }
            acctIdOpptyListMap.get(oppty.AccountId).add(oppty); 
        }
       
        List<AggregateResult> lstResult = [SELECT AccountId, COUNT(Id) countId 
                                           FROM Opportunity 
                                           WHERE AccountId IN:acctIds
                                           GROUP BY AccountId];
        
        List<Account> lstAccount = new List<Account>();
        for(AggregateResult result:lstResult){
            Account acct = new Account (Id=(Id)result.get('AccountId'), Total_Opportunities__c = (Integer)result.get('countId'));
            lstAccount.add(acct);
        }
        update lstAccount;  
        
        List<Account> acctList = new List<Account>();
        acctList = [SELECT Total_Amount__c 
                    FROM Account 
                    WHERE Id IN: acctIds];
        for(Account acct : acctList){
            List<Opportunity> tempOpptyList = new List<Opportunity>();
            tempOpptyList = acctIdOpptyListMap.get(acct.Id);
            Double totalOpptyAmount = 0;
            for(Opportunity oppty : tempOpptyList){
                if(oppty.Amount != null){
                    totalOpptyAmount += oppty.Amount;
                }
            }
            acct.Total_Amount__c = totalOpptyAmount;
        }
        update acctList;
    }
}
  • March 02, 2020
  • Like
  • 0
Hello folks , 
I want to show a custom message or toast message if no contacts are found for an account . could you please correct my code . 

please tell how to check the size or length of the  returned contacts .  

below code displays Contacts if present under an account . 

html code:
<template>
<lightning-card title="Apex Method With Parameters">
<lightning-layout>
<lightning-layout-item flexibility="auto" padding="around-small">
<lightning-layout-item flexibility="grow">
<lightning-input label="Enter Account Name" type="search" onchange={searchContact} value={searchKey}> </lightning-input>
</lightning-layout-item>
                <lightning-layout-item class="slds-p-left_xx-small">
<lightning-button label="Search" onclick={doSearch} ></lightning-button> </lightning-layout-item>
<lightning-layout-item class="slds-m-bottom_small">
<template if:true={contacts}>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}> {contact.Name} </p>
</template>
</template>
<template if:false={contacts}>
<p> No Contacts found for this Account </p>
</template>
<template if:true={error}>
{error}>
</template>
</lightning-layout-item>
         </lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>

js code: 

import { LightningElement, track } from 'lwc';
import SearchContactList from '@salesforce/apex/ApexMethodWithParameters.SearchContactList';
export default class ShowContactsIMP extends LightningElement {
/* eslint-disable no-console */
/* eslint-disable no-alert */
@track contacts;
@track error;
searchContact(event){
this.searchKey = event.target.value;
}
doSearch() {
SearchContactList({ accountName: this.searchKey })
.then(
result => {
this.contacts = result;
console.log('contacts => ', JSON.stringify(this.contacts));
alert('contacts => ', JSON.stringify(this.contacts));
this.error = undefined;
}
)
.catch(error => {
this.error = error;
this.contacts = undefined;
});
}
}
 
hi folks,  Very Urgent requirement 
on Account object , i have a custom button " contact form" . 
On click of that button opens a Modal window which has  contact form (basically fields from contact object) , i have few fields  Name ,  phone number , className etc . in the bottom i have Save and Save & New buttons,

i want custom functionality of Save
and Save & New buttons 
Requirement 1:
On click of save button on contact form , i need to save all the parameter (Name ,  phone number , className )  custom way , i need to store the contact form data as Record in contact object and in  related list of Account record. .
Hello Folks , 

Need help in implementing using maps ,  Not understanding how to do it . Can anyone please help me with code

If I have Account1 and Contact1 and Contact2 are related to Account1. Then, in account object detail page, i have a text box named Account.ContactName__c =  Contact1, Contact2  etc . i need to diaplay the related contact names on Account .  i did it in list but not able to do it in maps . 

Using  List : 
for(Account  a:acclist )
      {
          String contactName = '';
          for(contact  c :a.contacts )  
           {
           contactName = c.name+',' ;
           }
       a.ContactName__c = contactName;
       
      }
      update acclist; 
HI All , 
can any one help me with this requirement ,
1)  where when i click on parent checkbox , need to select all child checkbox
2) when i unselect parent checkbox , need to unselect all childs 
3) let us suppose i click on parent checkbox that selects all child checkbox , when i unselect one checkbox in child , the parent checkbox has to get deselected.




User-added image


 
Hi Friends,

I need help in completing below trigger.
I have a requirement, Two custom objects Obj A and Obj B which Obj A is Parent and Obj B is child. I am creating a child record based on daysbetween two dates Start Date and End Date in Parent object. This is working fine.
Now, If I edit the end date 
Eg: Start Date = 20/03/2020 and End Date = 22/03/2020. Daysbetween = 3. I will create 3 records in child Obj.
I am editing End Date = 25/03/2020.
Now Daysbetween = 6.
I want to create 3 more records. 
If I delete a date. Eg: End Date = 21/03/2020. Daysbetween = 2. I want to delete 1 record in child obj.
 
trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
        if(String.isNotBlank(sp.Phase_Start_Date__c) && String.isNotBlank(sp.Phase_End_Date__c) {

            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c);
            
            System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
            for(integer i=0; i<=daycount; i++)
            {
                Daily_Practice__c dps = new Daily_Practice__c();
                dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
                dps.StudyPlan__c = sp.Id;
                dps.Status__c = 'Assigned';
                dplist.add(dps);
            }    
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Let me know your suggestions to complete this requirement.

Thanks in advance.
Hello all

i am trying to Design a Trigger where it should throw an error upon duplicate record creation, i know this can be achived with Duplicate management, but i have Custom Lookup field(User) which is not showing in the matching rules, Hence i am trying to write trigger, basically i have 3 Custom fields User(Assignedto__c ) which is 
Lookup(User) and other fields are 
Quater_Year__c which is picklist and Month (
Month__c) which is picklist field, 

Please Help with the trigger
trigger contactDuplicatePreventer on Contact(before insert, before update) 
{
	Set<String> setEmailID = new set<String>();
	Set<Id> setContID = new set<ID>();
    for (Contact Contact : System.Trigger.new) 
	{
        if ((Contact.Email != null) &&  (System.Trigger.isInsert ||  (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email))) 
		{
			setEmailID.add(Contact.Email);
			setContID.add(Contact.id);
		}
    }

	List<Contact> lstCOntact = [select id ,email from contact where email in :setEmailID and id not in :setContID ];
    Map<String, Contact> contactMap = new Map<String, Contact>();

	for(Contact cont : lstCOntact)
	{
		contactMap.put(cont.email, cont);
	}	

    for (Contact Contact : System.Trigger.new) 
	{
        if ((Contact.Email != null) &&  (System.Trigger.isInsert ||  (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email))) 
		{
			if(contactMap.containsKey(Contact.Email))
			{
				Contact.Email.addError('A Contact with this email address already exists.');
			}
		}	
	}	
}