• Suraj Tripathi 47
  • SMARTIE
  • 1797 Points
  • Member since 2020
  • Salesforce Application Architect
  • Cloud Analogy


  • Chatter
    Feed
  • 55
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 413
    Replies
I could see in some scenarios developers using below code to map the child records with Parent.(e.x., Contact with Account)
for(Contact con: newcontact){
                    if(con.AccountId != null){
                        if(!maponobject.containsKey(con.AccountId)) {
                        maponobject.put(Con.AccountId, new List<Contact>());
                        } } }
but in some cases developer using the below code however the functionality is same as above,
for (Contact con: newcontact){
           if(con.AccountId != Oldcon.AccountId){
                  if(!maponobject.containsKey(con.AccountId)){
                   maponobject.put(con.AccountId, new List<Contact>{con});
                  } } }

What is difference on both code(why {con} added on second one but not in first ) and how the value is putting on the maponobject on both cases?
I am trying to send a mass welcome email (new customer template) to contacts after we save the contact. All I want is to know why I am getting the error and the solution for that. 
I have the following code with an error. Please advice!

class:
public class massEmail 

{
    public void mail(){
        list<contact> l= [SELECT ID FROM contact LIMIT 2];
        list<ID> I= new list<ID>();
        for(contact c: l){
            I.add(C.Id);    
        }
        
        EmailTemplate e = [SELECT ID FROM EmailTemplate WHERE Name = 'Sales: New Customer Email'];
        messaging.MassEmailMessage  m = new messaging.MassEmailMessage();
        m.setTargetObjectIds(I);
        m.setSenderDisplayName('System Admin');
        m.setTemplateId(e.Id);
        messaging.sendEmail(new messaging.MassEmailMessage [] {m});     
    }
}

Trigger:
trigger NewCustEmail on Contact (after insert)

{
    if(trigger.IsAfter){
         massEmail.mail(trigger.new);
    }
}

Error: 
Method does not exist or incorrect signature: void email(List<Contact>) from the type massEmail
I am creating a process builder that I want to have updated a date/time opendate_c field with the time when any of the leads fields in a section are modified. except for leadstatus_c (its a picklist)
I am trying to define the action so that the new Date/Time field is updated to be when the process fires.I want to work on edited and created. i create in the workflow but it's not working. now I want to do that in process builder so please help me.
  • May 15, 2021
  • Like
  • 0
Here my code  i want code in minimum lines 


public class Demo3 implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator('Select id, name, phone, (select id, name,phone from contacts)from account');
    }
    public void execute(Database.BatchableContext BC,List<Account> Acclist){
        set<id> AccIds = New set<id>();
        for(Account Acc:Acclist){
            AccIds.add(Acc.id);
        }
        map<Id,Account> Acct = new map<id,Account>(Acclist);
        for(Account AC:Acclist){
        if(Acct.get(AC.id).Contacts.size()>0){
            AC.adderror('ERROR');
        }
        }
    }
    public void finish(Database.BatchableContext BC){
        
    }


 
Hi alI,
I need to write test class for below apex class and I'm only getting 33% code coverage. I'm not able to cover the page reference in my test class.Please help.
public class TestControllerExtension{
        
         public Test2__c cca {get;set;}
        
        public TestControlleExtension() {
           cca =new Test2__c ();
         
        cca= [select Test2_Request_ID__c,Test2_RecordType__c,Test2_Suffix__c,Test2_DOB__c,Test2_Middle_Name__c,Test2_Flag__c,Test2_Sex__c,Test2_SSN__c,Test2_First_Name__c, Test2_Last_Name__c, Test2_Family_ID__c, Test2ReportDate__c,Test2_BENE_SSN1__c,
                from Test2__c Where Id = :ApexPages.currentPage().getParameters().get('RequestID')];                
        }
        
        public Test2__c  getcca() 
        {
            return cca;
            
        }
        public PageReference NextPage(){
       PageReference p = new PageReference('/apex/TestPageButtonNextPage?RequestID');
              p.setRedirect(false);
              return p;
            }
        
         public PageReference PreviousPage(){
         PageReference p1 = new PageReference('/apex/TestPageViewButton?RequestID');
          p1.setRedirect(false);
             return p1;
           }
        }

 
Hi All,
In my below code i have to get the count of 'unchecked' records whenever apex is executed in batch class. Please guide me how to get the count for only 'unchecked' records found.

if(t.Profile__c == null)
            {
        t.Status__c = 'Fill data';
            }
            else if(t.Profile__c != null && t.Check__c == 'No')
            {
                t.Verification_Status__c = 'Unchecked';
              
            }
  • May 12, 2021
  • Like
  • 0
please if you  are able to write it explain it littel bit in few words we need to write batch apex.
and the secound condition is 
Every morning at 7 AM for account we have to create Task record by using Batch class

 

Main Class:::

public without sharing class Geotag {
    @AuraEnabled
    
    public static void updateFiles(String contentVersionIds, String Latitude, String Longitude) 
    {
        String[] contentVersionIdArr =     contentVersionIds.split(',');

        Set<String> contentDocumentIds = new Set<String>();

        for(String docId : contentVersionIdArr)
        {
            if(docId != null && docId.length() > 0)
                contentDocumentIds.add(docId);
        }

        List<ContentVersion> versionList = [SELECT FileExtension, Title FROM ContentVersion 
                                            WHERE ContentDocumentId IN :contentDocumentIds and IsLatest=true ] ;

        List<ContentVersion> contentVersionsToUpdate = new List<ContentVersion>();

        for(ContentVersion contVersion : versionList)
        {
            contVersion.Latitude__c = Decimal.valueOf(Latitude);
            contVersion.Longitude__c = Decimal.valueOf(Longitude);
        }

        update versionList;
    }
    @AuraEnabled(cacheable=true)
    public static Case getLatLong(String recordId){
        return [select Id,Latitude__c,Longitude__c from Case where Id=:recordId];
    }
}

\\\\\\\\\\\\\\\\\\\\\\My test class with 82% coverage////////////////////I need 85%

@isTest
public class GeotagTest {
   @isTest
    public static void updatefilestest(){
        
       // List<ContentVersion> cvlist = new List<ContentVersion>();
        
       // string[] idval = new string
        
        ContentVersion cv = new ContentVersion();
        cv.Title = 'Test Document';
        cv.PathOnClient = 'TestDocument.pdf';
        cv.VersionData = Blob.valueOf('Test Content');
        cv.IsMajorVersion = true;
        cv.Latitude__c = 23;
        cv.Longitude__c = 22;
        Insert cv;
        
        ContentVersion cv1 = new ContentVersion();
        cv1.Title = 'Test Document';
        cv1.PathOnClient = 'TestDocument.pdf';
        cv1.VersionData = Blob.valueOf('Test Content');
        cv1.IsMajorVersion = true;
        cv1.Latitude__c = 23;
        cv1.Longitude__c = 22;
        Insert cv1;
        
       // cvlist.add(cv);
        //cvlist.add(cv1);
        
      //  insert cvlist;
        
        
        Test.startTest();
        Geotag.updatefiles(cv.Id,'23','26');
        Test.stopTest();
    }
    @isTest
    public static void getlatlongtest(){
        
        Case c1 = new Case();
        c1.Address_Type__c = 'RESIDENCE ADDRESS';
        c1.AddressLine1__c = 'line1';
        c1.AddressLine2__c = 'line2';
        c1.AddressLine3__c = 'line3';
        c1.Agency_Name__c = 'agen1';
        insert c1;
        
        Test.startTest();
         Geotag.getlatlong(c1.Id);
        Test.stopTest();
    }
    
}

 

After execution of test ,Its showing errors for these two fields--

  FAM3.Fi_Agent__c='FAMagent3';
  FAM3.PinCode__c='400 003';

Main Class::::

public class AgentMappingTriggerHandlerException  extends Exception {
public static void afterInsert(map<Id, FI_Agent_Mapping__c> oldMap, map<Id, FI_Agent_Mapping__c> newMap, List<FI_Agent_Mapping__c> newList){
    
        Map<String,String> AgentMappingMap = new Map<String,String>();
        Map<String,String> GroupMap = new Map<String,String>();
        Map<String,String> agentmappingUserMap = new Map<String,String>();
        List<String> AgencyList  = new List<String>();
        
        for(Sobject obj : newList){
            AgentMappingMap.put(String.valueOf(obj.get('Id')),String.valueOf(obj.get('Agency_Name__c')));
            AgencyList.add(String.valueOf(obj.get('Agency_Name__c')));
        }
    system.debug('AgentMappingMap==='+AgentMappingMap);
    
        
        String groupquery='select id,name from Group where name in: AgencyList';
        List<Sobject> targetobj=Database.query(groupquery);
        if(targetobj.size() > 0){
            for(Sobject obj : targetobj){
                GroupMap.put(String.valueOf(obj.get('Name')),String.valueOf(obj.get('Id')));   
                
            }
            system.debug('Group Map==='+GroupMap);
        }
    
     for(Sobject obj : newList){
            agentmappingUserMap.put(String.valueOf(obj.get('Id')),GroupMap.get(String.valueOf(AgentMappingMap.get(String.valueOf(obj.get('Id'))))));
     system.debug('agentmappingUserMap=='+agentmappingUserMap);   
     }
    
        SharingUtility.agentMappingShareRecord(agentmappingUserMap,'Edit', 'Manual');        
     }
    
    public static void beforeUpdate(map<Id, FI_Agent_Mapping__c> oldMap, map<Id, FI_Agent_Mapping__c> newMap, List<FI_Agent_Mapping__c> newList){
           
    }

    public static void afterUpdate(map<Id, FI_Agent_Mapping__c> olaMap, map<Id, FI_Agent_Mapping__c> newMap, List<FI_Agent_Mapping__c> newList){
    }
   
    public static void beforeInsert(List<FI_Agent_Mapping__c> AgentMappingList){
       
        List<String> useridList = new List<String>();
        List<Id> pincodeList = new List<Id>();
        for(FI_Agent_Mapping__c obj : AgentMappingList){
            useridList.add(String.valueOf(obj.get('Fi_Agent__c')));
            pincodeList.add(obj.PinCode__c);
        }
        String agentmappingquery='select id,Pincode_Map__c,Fi_Agent__c from FI_Agent_Mapping__c where PinCode__c in: pincodeList';
        List<FI_Agent_Mapping__c> targetobj=Database.query(agentmappingquery);
        if(targetobj.size() > 0){
            AgentMappingList.get(0).addError( 'User Has already Mapped to the same pincode');   
        }
    } 
}

Please Correct my Test class:::

@isTest
public class AgentMappingTriggerHandlerExceptionTest {
    
@isTest         
    public static void afterInsertTest(){
    
     FI_Agent_Mapping__c FAM1 = new FI_Agent_Mapping__c();
      FAM1.Name ='FAMname1';
      FAM1.Agency_Name__c='A R ASSOCIATES';
      FAM1.Fi_Agent__c='FAMagent1';
      FAM1.PinCode__c='400 001';
      insert FAM1;
      
      FI_Agent_Mapping__c FAM2 = new FI_Agent_Mapping__c();
      FAM2.Name ='FAMname2';
      FAM2.Agency_Name__c= 'COGENT';
      FAM2.Fi_Agent__c='FAMagent2';
      FAM2.PinCode__c='400 002';
      insert FAM2;
       
      
      Map<Id,FI_Agent_Mapping__c> afterInsertMap  =  New Map<Id,FI_Agent_Mapping__c>();
      FI_Agent_Mapping__c FAM3 = new FI_Agent_Mapping__c();
      FAM3.Name ='FAMname3';
      FAM3.Agency_Name__c= 'BEST SERVICES';
      FAM3.Fi_Agent__c='FAMagent3';
      FAM3.PinCode__c='400 003';
      insert FAM3;
      afterInsertMap.put(FAM3.Id,FAM3);
      
      List<FI_Agent_Mapping__c> newListA = new List<FI_Agent_Mapping__c>();
      FI_Agent_Mapping__c FAM4 = new FI_Agent_Mapping__c();
      FAM4.Name ='FAMname4';
      FAM4.Agency_Name__c='BANRAD FINSERV';
      FAM4.Fi_Agent__c='FAMagent4';
      FAM4.PinCode__c='400 004';
      insert FAM4;
      newListA.add(FAM4);
        
       Test.startTest();
       AgentMappingTriggerHandlerException.afterInsert(afterInsertMap,afterInsertMap,newListA ); 
       Test.stopTest();
      
    }
@isTest
    public static void beforeUpdateTest(){
        
    }
@isTest
    public static void afterUpdateTest(){
        
    }
@isTest
    public static void beforeInsertTest(){
    
    }
}

 

Hi Developer Community ,
I have been working on a task in my project , i will share the ocde of component , js and apex function .
My scenario is , i have a standard object :OPPORTUNITY and
Custom object: competition__c
in my opportunity there is a custom field called “Main_Competitor” (text field ) and in my competition there is a field called “Competitor” (look up field)

i have created a custom aura component and displayed in opportunity record page
User-added image


in this above image u can see custom field : Main Competitor in details area,
on the right side u can see PRIMARY COMPETITION look up field (i have created a custom look up field )
in this primary competition , if i click on search , then it will show the list of Competitions ,if i select one of the competition name from them and click on set as primary , then this value is to be set a sprimary competition and in this particular selected competition i need to take value of competitor and assign that value to Main competitor in oppoertunity
i have already created all the necesaary requirements , but value is not updating , i think error is in apex code , i will share the code , plz check and let me know how to solve this


 

Competition.cmp:

<aura:component controller="oppcompquery" implements=" .......">
     <aura:attribute name="selectedId" type="String" />
         <aura:attribute name="competitionlist" type="String" />
<c:lookupField 
                    objectAPIName="Competition__c" 
                    label="PRIMARY COMPETITION"
                    returnFields="['Name']" 
                    queryFields="['Name']"
                    selectedId="{!v.selectedId}"
                    />
    <lightning:button label="set as primary" onclick="{!c.request1}" variant="brand" name="name2" class="slds-m-right_small"/>


controller.JS:

request1: function(component, event, helper) {
        var recId = component.get("v.selectedId");
        alert('hi');
        var action = component.get("c.fetchCompetitions");
        action.setParams({
            "recordId": component.get("v.recordId"),
            "recId": recId
        }); // Create a callback that is executed after 
        action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") { // Alert the user with the value returned 
                    // from the server 
                    alert("From server: " + response.getReturnValue());
                    // You would typically fire a event here to trigger 
                    // client-side notification that the server-side 
                    // action is complete 
                } else if (state === "INCOMPLETE") {
                    // do something 
                } else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
            });
                $A.enqueueAction(action);
        }



apex class:

 @AuraEnabled
    public static void fetchCompetitions(String recordId, String recId){
                  System.debug('hi');
                   system.debug('recordId' +recordId);
                    system.debug('recId' +recId);
        List<Opportunity> opp=new List<Opportunity>();
        Opportunity o = [select id,Name,MainCompetitors__c from Opportunity where id=:recordId];
        List<Competitor__c> cmptList=[select id,Name  from Competitor__c where id=:recId];
        for(Competitor__c comp : cmptList){
           Opportunity opList = new Opportunity();    
           opList.MainCompetitors__c = comp.Name;        
            opp.add(opList);
        }
       update opp; 
        system.debug('opp' +opp);

    }
 

please help me with solution
 

 public static void syncfields(list<contact> con1){
    map<String,contact> contacts=new map<String,contact>();
    list<user> userlist=new list<user>();
    for(contact con:con1)
    {
        if(con.phone!=null)
        {
            contacts.put(con.phone,con);
        }
    }
    list<user> users=[SELECT mobilePhone,fax,phone from user where phone IN:contacts.KeySet()];

    for(user uc:users)
    {
        contact con=contacts.get(uc.phone);
        uc.phone=con.Phone;
        uc.fax= con.Fax  ;
        uc.mobilePhone= con.MobilePhone;
        userlist.add(uc);
            }
    if(userlist.size()>0){
        update userlist;
    }   
    }
working fine but , that last conditions are not matching  showing errors
Hi Team,

I have created a custom LWC component for Account records. I want to override the Account Standard New button with a custom LWC component.
Can anyone help me with this how-to achieve this?

Thanks in advance.
Lakshmi.
Friends,
I am trying to create LWC using VS Code. I am getting weird error msg.
"""Command 'SFDX: Create Lightning Web Component' resulted in an error (command 'sfdx.force.lightning.lwc.create' not found)"""
I tried to updating SFDX and uninstall/install Lightning Web Components extender. Still issue did not resolve. 
Thoughts to resolve my issue are much appreciated.
let validExpense = component.find('expenseform').reduce(function (validSoFar, inputCmp) {
inputCmp.showHelpMessageIfInvalid();
return validSoFar && inputCmp.get('v.validity').valid; }, true);
Hi all,

I focus more on the Admin side of things in our environment.  I've been messing around with a task to get an "eye popper" to appear on our Account Page Layout.  The goal is to bring in one field into a VF Page called "Account_Status__c".  This picklist contains the values "Active", "Dormant", "Inactive".  We want to place the VF Page in it's own section of the Account Page Layout.  For each value, we want to display them in large, bold letters with a colored highlight.  See highlights below:
  • Active = Green Highlight
  • Dormant = Yellow Highlight
  • Inactive = Red Highlight
Any advice on where to start or how to get this setup as a VF Page with a Controller would be sincerely appreciated.

Thank you~
Why  am I getting a Null Pointer Exception during iterating a map in a FOR loop, even if there are corresponding values in the map?
system.debug('**stdmap**' + stdIdToxyzMap.get(std.id)); //Prints the values correctly. No Null pointer exception          
for(xyz__c x : stdIdToxyzMap.get(std.Id)){  //Throws Null Pointer Exception at this line
	system.debug('x:'+x.id);
}
Hello All,
First of all this my first question posting here in this forum. If missed to follow any process please applogize and guide me the correct way.

I am verymuch new to sales force and I was trying out with trailhead module Apex & .Net Basics > Understand Execution Context.

while writing the code challege I faced an error like
---------------------------------------------------------------------------------
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger: execution of BeforeInsert

caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old

Class.AccountTriggerHandler.CreateAccounts: line 13, column 1
Trigger.AccountTrigger: line 3, column 1: []
----------------------------------------------------------------
WIth my limitted knowledge I tried all the possibility but could not succed. Please suggest what is wrong with my code. Thank you in advance.

AccountTriggerHandler class
public class AccountTriggerHandler {
    public static void CreateAccounts(List<Account> accts) {
        List<Account> newActs = new List<Account>();
        for (Account a : accts) {
            Account ac = new Account();
            ac = a;
            if(a.BillingState!=a.BillingState){
               a.ShippingStreet = a.BillingState ;
            }
            newActs.add(a);
        }
        if (newActs.size() > 0) {
            insert newActs;
        }
    }
}

Trigger
trigger AccountTrigger on Account (before insert) {
        System.debug('called trigger');
    if (Trigger.isBefore  && Trigger.isInsert) {
        System.debug('AccountTriggerHandler.CreateAccounts(Trigger.New)');
        AccountTriggerHandler.CreateAccounts(Trigger.New);
    }
}



AccountTriggerTest class

@isTest
public class AccountTriggerTest {
    @isTest static void TestCreateNewAccountInBulk() {
        List<Account> accts = new List<Account>();
        for(Integer i=0; i < 200; i++) {
            Account acct = new Account(Name='Test Account ' + i, BillingState = 'CA');
            accts.add(acct);
        }              
        // Perform Test
        Test.startTest();
        if(accts.size() > 0){
            insert accts;    
        }
        Test.stopTest();
        
       
        Boolean x = False;
        System.debug('data '+verifyAccts[0].BillingState);
        if (verifyAccts[0].BillingState == verifyAccts[0].BillingState ){
            x= True;
        }
           
        System.assertEquals(True, x);  
        
    }
}

 
I am trying to create a trigger where contact description will update when account object description is updated and my code is as below: but i am getting an error "Loop must iterate over collection: Map<Id,Account>"

trigger ContactFieldUpdate on Account (after update) {
  Set<ID> setAccId = new Set<ID>();
    List<contact> lstConUpdate = new List<Contact>();
    for(Account accl : Trigger.new)
    {    
            setAccId.add(accl.id);
    }
    
    Map<ID, Account> mapAccount = new Map<ID, Account>([select id,description,(select id,description from contacts ) from account where id in :setAccId ]);
    
    for(Account acc: mapAccount){
        for(Contact con : acc.contacts){
            con.Description = acc.Description;
            lstConUpdate.add(con);
        }
    }
    
     update lstConUpdate;
        
    }


    
    
       
      
        
        

 
I could see in some scenarios developers using below code to map the child records with Parent.(e.x., Contact with Account)
for(Contact con: newcontact){
                    if(con.AccountId != null){
                        if(!maponobject.containsKey(con.AccountId)) {
                        maponobject.put(Con.AccountId, new List<Contact>());
                        } } }
but in some cases developer using the below code however the functionality is same as above,
for (Contact con: newcontact){
           if(con.AccountId != Oldcon.AccountId){
                  if(!maponobject.containsKey(con.AccountId)){
                   maponobject.put(con.AccountId, new List<Contact>{con});
                  } } }

What is difference on both code(why {con} added on second one but not in first ) and how the value is putting on the maponobject on both cases?
Hi All,
In my below code else part is not working though status field is blank. Please guide where i'm going wrong.
===============
<apex:page standardController="Detail__c" extensions="WarningPage" action="{!displayWarning}">

<apex:form >
    <apex:pageBlock >
    
        <apex:pageMessages ></apex:pageMessages>
</apex:pageBlock>
</apex:form>
</apex:page>

==============================================


public with sharing class WarningPage {
 
    public WarningPage(ApexPages.StandardController controller) {
    }
    public void displayWarning(){
   
    list<Detail__c> stud = [select id,name,Status__c  from Detail__c ];
    
        for(Detail__c s : stud)
        {
        
            
                if(s.Status__c == 'More details needed')
                {
                   
                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'More details needed'));
                }
                else if(s.Status__c == '')
                {
                    
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Verified'));
                }
                }
                }
                }
  • May 15, 2021
  • Like
  • 0
I am trying to send a mass welcome email (new customer template) to contacts after we save the contact. All I want is to know why I am getting the error and the solution for that. 
I have the following code with an error. Please advice!

class:
public class massEmail 

{
    public void mail(){
        list<contact> l= [SELECT ID FROM contact LIMIT 2];
        list<ID> I= new list<ID>();
        for(contact c: l){
            I.add(C.Id);    
        }
        
        EmailTemplate e = [SELECT ID FROM EmailTemplate WHERE Name = 'Sales: New Customer Email'];
        messaging.MassEmailMessage  m = new messaging.MassEmailMessage();
        m.setTargetObjectIds(I);
        m.setSenderDisplayName('System Admin');
        m.setTemplateId(e.Id);
        messaging.sendEmail(new messaging.MassEmailMessage [] {m});     
    }
}

Trigger:
trigger NewCustEmail on Contact (after insert)

{
    if(trigger.IsAfter){
         massEmail.mail(trigger.new);
    }
}

Error: 
Method does not exist or incorrect signature: void email(List<Contact>) from the type massEmail
Apex Class:
_______________
global with sharing class FlowListController {

    @AuraEnabled(cacheable=true)
    public static List<FlowDefinitionView> getFlowNamesApex(String filtersString) {

        String queryString = 'SELECT Id, ApiName, Label FROM FlowDefinitionView ';

        if (filtersString != null) {
            Map<String, List<String>> filters = (Map<String, List<String>>) JSON.deserialize(filtersString, Map<String, List<String>>.class);
            if (!filters.isEmpty()) {
                queryString += ' WHERE ';
                Boolean isFirst = true;
                for (String fieldName : filters.keySet()) {
                    List<String> values = filters.get(fieldName);
                    String negativeClause = fieldName.contains('!') ? (values.size() > 1 ? 'NOT ' : '!') : '';
                    String operator = values.size() == 1 ? '= ' : 'IN ';
                    String value = values.size() == 1 ? values[0] : '(\'' + String.join(values, '\',\'') + '\')';
                    queryString += (!isFirst ? ' AND ' : ' ') + fieldName.replace('!', '') + ' ' + negativeClause + operator + value;
                    isFirst = false;
                }
            }
        }

        return (List<FlowDefinitionView>) Database.query(queryString);
    }
}
I need help in writing a code to send email both single and mass email with LWC and apex both? Please correct me and advice me. 
I want to be able to create a custom component where we can attach a file (template) and send it. 
I also want to write a trigger with/without a helper class to be able to send a mass email. 
Any use case is fine, please mention the use case so that my silly brain can co-relate.
 
Hi, I want to create a formula field for the following scenario... I have 4 fields:
0. Reported Start Date(date datatype)
1. Reported Start Time(time datatype)
3. Reported End Date(Date datatype)
4. Reported End Time(time datatype)

Only the following interval of time is relevant, from 22:00(10PM) - 00:00(12 AM, next day). This interval is important because I want to display the value from formula field based on this interval of time.

Example: I have from 10:00 PM - 01:00 AM,  display show 120 minutes, because we only count  minutes in this interval of time.
Example 2: I have from 08:00 PM - 10:00 PM, display nothing(blank), because is not included in this interval of time.
Example 3: I have from 11:00 PM - 00:00 AM, display 60 minutes.

And so on.... Is it possible?
I created a class scheduled to run once a week to let task owners know which tasks are open for them.
I am trying to compose the body of the email only with the open tasks of that specific user. With what I have so far, I am composing the email with all open tasks for all users. How can I do this?
public EmailTasksWeekly() {
        Map<Id, List<Task>> tasksByUser = new Map<Id, List<Task>>();
    for(Task taskRecord: [SELECT OwnerId, Id, Status, Subject, What.Name, ActivityDate FROM Task WHERE 
                          IsClosed = false AND Owner.IsActive = true]) {
        List<Task> userTasks = tasksByUser.get(taskRecord.OwnerId);
        if(userTasks == null) {
            tasksByUser.put(taskRecord.OwnerId, userTasks = new List<Task>());
        }
                              
        userTasks.add(taskRecord);
    }
tasks = [Select ID, OwnerId, Status, Subject, What.Name, ActivityDate FROM Task WHERE 
                 Status = 'Open' AND OwnerId = :tasksByUser.keySet()];
        }

 
Apex Class:
______________

public class AskEDD_ArticleAction {
    @InvocableMethod
    public static List<FlowOutputs> updateArticleTypeForDataCategories(List<FlowInputs> articleType) 
    {
        List<Knowledge__kav> lstArticleType = [SELECT Id, Title, AskEDD_Category__c FROM Knowledge__kav WHERE Id =:articleType[0].recordId AND (PublishStatus = 'draft' OR Approval_Status__c = 'Pending Approval')];

        List<Knowledge__DataCategorySelection> lstDC = [SELECT ParentId, DataCategoryName   FROM Knowledge__DataCategorySelection
                                                            WHERE ParentId =:articleType[0].recordId];
List<FlowOutputs> outputlist = new List<FlowOutputs>();
        
        FlowOutputs output = new FlowOutputs();
        
        Map<Id, String> datacategoryNameMap = new Map<Id, String>();

        for(Knowledge__DataCategorySelection dcObj:lstDC)
        {   
            if(datacategoryNameMap.containsKey(dcObj.ParentId))
            {
                String str =  datacategoryNameMap.get(dcObj.ParentId);
                datacategoryNameMap.put(dcObj.ParentId, str + ',' + dcObj.DataCategoryName);
            }
            else
            {
                datacategoryNameMap.put(dcObj.ParentId, dcObj.DataCategoryName);
            }
        }

        for(Knowledge__kav artObj:lstArticleType)
        {
            if(datacategoryNameMap.containsKey(artObj.Id))
            {
                artObj.AskEDD_Category__c = datacategoryNameMap.get(artObj.Id);
                
                if (String.isEmpty(artObj.AskEDD_Category__c)){
                     output.noCategory = true;
                    outputlist.add(output);
                    return outputlist;
                } 
                else {
                     output.noCategory = false;
                    outputlist.add(output);
                }
         //     output.categoryString  = artObj.AskEDD_Category__c;
            }
        }

     //   update lstArticleType;
        return outputlist;
       }  
    public class FlowInputs {
        @InvocableVariable
        public string recordId;
    }
    public class FlowOutputs {
        @InvocableVariable
        public boolean noCategory;
    }
}
Apex Class:
____________
public class EDDKMSCreateArticleFromTemplate {
  @AuraEnabled
    public static List<Knowledge_Article_Template__c> getKnowledgeArticleTemplates() {
        try {
          return [SELECT Id, Name FROM Knowledge_Article_Template__c];
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
    
    @AuraEnabled
    public static TemplateWrapper getKnowledgeArticleTemplateBody(String templateId, String templateName) {
        try {
            TemplateWrapper wrapper = new TemplateWrapper();
            if(Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get(templateName) != null) 
                wrapper.recordTypeId = Schema.SObjectType.Knowledge__kav.getRecordTypeInfosByName().get(templateName).getRecordTypeId(); 
            else
                wrapper.recordTypeId = '';
            
            wrapper.template = [SELECT   Id, Name, Template_Body__c, OT_Body__c, CF_Body__c, DET_Body__c,
                                    ADJ_Body__c, MGR_OT_EPR_Body__c, MGR_UISD_Body__c
                                FROM  Knowledge_Article_Template__c
                                WHERE  Id =: templateId];
            return wrapper;
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }        
    }
    
    public class TemplateWrapper {
        @AuraEnabled public String recordTypeId {get;set;}
        @AuraEnabled public Knowledge_Article_Template__c template {get;set;}
    }
}

Who can help in this situation?

Class:  

public static List<ObjectName> MethosName(Map <Id, objectName> objectNameNewMap){logic}
trigger(beforeUpdate):

Trigger:

List<OnjectName> ObjectNameList = ClassName.methodName(Trigger.newMap);

ERROR:

Method does not exist or incorrect signature: void MethodeName(Map<Id,SObject>) from the type Classname

Hi Team,

Below apex trigger Getting the error message System.LimitException: Too many SOQL queries: 201.can you please help me to bulkified the code.
trigger InvestigatorObjectTrigger on Investigator__c (before update, after insert, after update, before insert){
    
    List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
    EmailTemplate etmpltmgr = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_mgr_vf' limit 1];
    EmailTemplate etmpltPrimary = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_unit_vf' limit 1];
    EmailTemplate etmpltAlt = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_alter_vf' limit 1];
    //List<Contact> lstAccount = [select id,Name from Contact limit 1];
    
    
    //for record attachments. 
    if(Trigger.isUpdate && Trigger.isBefore){
       //Set<String> lstIds = new Set<String>();
        profile sAdmID = [select id from profile  where name ='System Administrator'];
        for(Investigator__c inv : trigger.new){
            
            //Complaint__c cmpl = [select id,Name, Complaint_status__c from Complaint__c where Id =: inv.Complaint__c];
            
            /*if(cmpl.Complaint_status__c == 'Investigator / Reviewer'){
                if(inv.Investigation_Report_Attached__c == true || inv.Additional_Document_Attached__c == true){
                    lstIds.add(inv.Id);
                }
             }
             else{
                 inv.addError('You cannot update the record as case is at another stage.');
             } */
             if(inv.Investigation_Status__c == 'Investigation Closed'){
                
                    if(UserInfo.getProfileId() != sAdmID.Id){
                        inv.Investigator_Name1_c__c = UserInfo.getFirstName()+' '+UserInfo.getLastName();
                        inv.Date_of_review__c = System.Today();
                    } 
             }  
        }
        
         /*
        if(lstIds.size()>0){
            List<Attachment> lstAttchment = [select id,Name,parentId from attachment where ParentId IN : lstIds];
            map<String,Attachment> mapOfAttachment = new map<String,Attachment>();
            
            for(Attachment att : lstAttchment){
            
                mapOfAttachment.put(att.ParentId,att);
            }
            
            for(Investigator__c inv : trigger.new){
            
                if(inv.Investigation_Report_Attached__c == true || inv.Additional_Document_Attached__c == true){
                    if(!mapOfAttachment.containsKey(inv.id)){
                        string Url = System.URL.getSalesforceBaseUrl().toExternalForm();                            
                        String str = '<html><Head><script>window.onload = function (){document.getElementById("errorDiv_ep").style.display = "none";window.open("/apex/AttachmentForAllObject?Id='+inv.Id+'","test","Height=400,width=800,top=200,left=300");}</script></Head><Body></Body></html>';
                        inv.addError('Please Attach File '+str, false);
                    }
                }                     
            }
        } */ 
    }
     
    // The following code is for shooting mails to investigator unit and chain and sharing of records .
    if(Trigger.isInsert){
    boolean myb = false;
        if(!test.isrunningtest()){
            notification_chain_enable_disable__c mc = notification_chain_enable_disable__c.getValues('Investigator Notification Chain');
            myb = mc.Is_Active__c;
        }
        else{
            myb = true;
        }      
          
        if(Trigger.isAfter){
        allMails = new List<Messaging.SingleEmailMessage>();
        List<Investigator__share> lastRecShare = new List<Investigator__share>();        
        String caseownername ='';
        
        for(Investigator__c inv : trigger.new){
            
            if(inv.PCC_Role__c != null){
            
            List<Sub_Directory__c> lstUser = [select id,SF_User__c,SF_User_Email__c,Category__c,SF_User_Name__c from Sub_Directory__c where Master_Directory__c =:inv.PCC_Role__c AND isActive__c = true  ];
            Complaint__c cmpl = [select id,Country__c,name,Contact_Person__c,epersonname__c ,Entry_Person_Email__c,Entry_Person_Phone__c,Company_Name__c,Contact_Email__c,Complaint_Type__c,Complaint_Date__c,Other_Comments__c from Complaint__c where id =: inv.Complaint__c];
            
            /*for(Sub_Directory__c usr : lstUser){
            
                if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternate'){
                    caseownername = caseownername+', '+usr.SF_User_Name__c;
                }
            }*/
            
            for(Sub_Directory__c usr : lstUser){
                Boolean check = false;                
               // caseownername = caseownername.removestart(', ');
                if(inv.ownerId != usr.SF_User__c){
                    Investigator__share recShare = new Investigator__share();
                    
                    if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternative'){
                        recShare.AccessLevel = 'Edit';
                         caseownername = caseownername+', '+usr.SF_User_Name__c;
                          check = true;
                    } 
                       
                    if(caseownername.contains(usr.SF_User_Name__c) == false){
                         check = true;
                        recShare.AccessLevel = 'Read';
                    }                 
                   
                    if(check){
                        recShare.ParentId = inv.Id;                  
                        recShare.UserOrGroupId = usr.SF_User__c;
                        lastRecShare.add(recShare);
                    }
                }
                
                if(myb){
                    Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                    string Url = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+cmpl.Id;
                    msg.settargetObjectId(usr.SF_User__c);
                    msg.setWhatId(cmpl.Id);
                    if(usr.Category__c == 'Primary'){  
                       msg.setTemplateId(etmpltPrimary.Id);
                    }
                    if(usr.Category__c == 'Alternative'){
                        msg.setTemplateId(etmpltAlt.Id);
                    }
                    if(usr.Category__c == 'Manager'){
                       msg.setTemplateId(etmpltmgr.Id);
                    }
                    //msg.setToAddresses(new String[]{usr.SF_User_Email__c });
                    msg.setsaveAsActivity(false);
                    allMails.add(msg); 
                }         
          }              
        } 
        }
        
        if(lastRecShare.size()>0){
            System.debug('lastREcShare====>>>> '+lastRecShare);
            insert lastRecShare;
        }
        if(allMails.size()>0){
           Messaging.sendEmail(allMails);
        }
        }
    }
    
    //For status updation of complaint according to investigator status update.
    if(Trigger.isUpdate && Trigger.isAfter){
        Boolean chkStk = false;
        Boolean chkSales = false;
        Boolean chkNOreviewer = true;
        Boolean lastChk = false;
        List<Stakeholder__c> ReviewerRcds = new List<Stakeholder__c>();
        List<String> RevwCmpledLst = new List<String>();
         
        for(Investigator__c inv : trigger.new){
            
            if(inv.Investigation_Status__c == 'Investigation Closed' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Investigation Closed'){
                
               Complaint__c cmpl = [select id,Investigation_Review_completed__c,name,Complaint_status__c,isSales__c,isReviewer__c,isStakeholder__c from Complaint__c where id =:inv.Complaint__c];
               
               if(cmpl.isReviewer__c == true){
                    system.debug('came inside rwchk truee loop');
                    chkNOreviewer = false;
                    //To check for reviewer records if they are present.
                    ReviewerRcds = [select id,name,Review_Completed__c,Complaint_for_Reviewer__c from Stakeholder__c where recordType.DeveloperName='Reviewer' and Complaint_for_Reviewer__c=:inv.Complaint__c ];
                    for(Stakeholder__c st :ReviewerRcds){
                        if(st.Review_Completed__c == true){
                            RevwCmpledLst.add(st.Id);
                        }
                    }
                    
                    if(RevwCmpledLst.size() != ReviewerRcds.size()){
                        cmpl.Complaint_status__c = 'Investigator / Reviewer';
                        update cmpl;
                    }
                    
                    if(RevwCmpledLst.size() == ReviewerRcds.size()){
                        cmpl.Investigation_Review_completed__c = DateTime.Now();
                        if(cmpl.isStakeholder__c == true){
                            chkStk = true;
                            chkSales = false;
                            lastChk = false;
                        }
                    
                    if(chkStk){
                        cmpl.Complaint_status__c = 'Stakeholder';
                        update cmpl;
                    }
                    if(!chkStk){
                        if(cmpl.isSales__c == true){
                            chkSales = true;
                            lastChk = false;
                        }
                        else{
                            lastChk = true;
                        }
                       
                    }
                    if(chkSales){
                        cmpl.Complaint_status__c = 'Sales';
                        update cmpl;
                    }
                    if(lastChk){
                        cmpl.Complaint_status__c = 'Complaint Closed';
                        update cmpl;
                    }
                   } 
                }
                if(chkNOreviewer){
                    cmpl.Investigation_Review_completed__c = DateTime.Now();
                    if(cmpl.isStakeholder__c == true){
                          chkStk = true;
                          chkSales = false;
                          lastChk = false;
                    }
                    if(chkStk){
                        cmpl.Complaint_status__c = 'Stakeholder';
                        update cmpl;
                    }
                    if(!chkStk){
                        if(cmpl.isSales__c == true){
                            chkSales = true;
                            lastChk = false;
                        }
                        else{
                            lastChk = true;
                        }
                    }
                    if(chkSales){
                        cmpl.Complaint_status__c = 'Sales';
                        update cmpl;
                    }
                    if(lastChk){
                        cmpl.Complaint_status__c = 'Complaint Closed';
                        update cmpl;
                    }
                }
            }
            if(inv.Investigation_Status__c == 'Send back to QRC' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Send back to QRC'){
                Complaint__c cmp = new Complaint__c();
                cmp.id = inv.Complaint__c;
                cmp.Complaint_status__c = 'Assigned to QRC Postmaster';
                String Comment = '';
                if(inv.Comments__c != null){
                    if(inv.Comments__c.length() > 255){
                        Comment  = inv.Comments__c.substring(0,254);
                    }
                    else{
                        Comment  = inv.Comments__c;
                    }
                    cmp.Iu_send_back2qrc__c = Comment;
                }
                cmp.IU_Send_back_to_QRC_CHECKBOX__c = true;
                update cmp;
            }
            if(inv.Investigation_Status__c == 'Investigation / Review' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Investigation / Review'){
                Complaint__c cmp = new Complaint__c();
                cmp.id = inv.Complaint__c;
                cmp.Complaint_status__c = 'Investigator / Reviewer';
                update cmp;
            }
        }    
    }
    
    //// added for batch sharing
    if(Trigger.isUpdate && Trigger.isAfter){
        List<Investigator__share> lastRecShare = new List<Investigator__share>();
        SET<Investigator__share> SetRecShare = new SEt<Investigator__share>();        
        List<Sub_Directory__c> lstUser = new List<Sub_Directory__c>();
        String caseownername ='';
        for(Investigator__c inv : trigger.new){
            
            
                lstUser = [select id,SF_User__c,SF_User_Email__c,Category__c,SF_User_Name__c from Sub_Directory__c where Master_Directory__c =:inv.PCC_Role__c AND isActive__c = true  ];
                for(Sub_Directory__c usr : lstUser){
                    Boolean check = false;                
                    if(inv.ownerId != usr.SF_User__c){
                        Investigator__share  recShare = new Investigator__share();
                        if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternative'){
                            recShare.AccessLevel = 'Edit';
                            caseownername = caseownername+', '+usr.SF_User_Name__c;
                            check = true;
                        } 
                        if(caseownername.contains(usr.SF_User_Name__c) == false){
                            check = true;
                            recShare.AccessLevel = 'Read';
                        }                 
                        if(check){
                            recShare.ParentId = inv.Id;                  
                            recShare.UserOrGroupId = usr.SF_User__c;
                            SetRecShare.add(recShare);
                        }
                    }
                }
        }
        if(SetRecShare.size() > 0){
            lastRecShare.addall(SetRecShare);
            Upsert lastRecShare;
        }
    }    
}

 
Hi everyone,

Actually we have one task,we need to Upload Document data which where in salesforce we need to get that data in other application using API"s.If any one know how to send that data please respond.

Thanks inadvance,
RajuBalaji.