• Lukesh Karmore
  • NEWBIE
  • 114 Points
  • Member since 2020

  • Chatter
    Feed
  • 3
    Best Answers
  • 2
    Likes Received
  • 1
    Likes Given
  • 74
    Questions
  • 96
    Replies
Here there is a Trigger which calls Trigger handler and in turn Trigger handler calls the apex class,this  apex class is to create tasks on Case record 
and the goal here is to prevent a Task from being created for 2 scenarios
  • First  Task with the Action__c field being ‘airtel account contact Research’ and once user creates a Task with Action__c as "‘airtel account contact Research’"
  • then they should only  able to create second  Task with Action__c as '1st airtel contact'',

Now after these 2 tasks creation is done then user can create any task with any picklist value in Action__c field

Here is Trigger which calls TaskTriggerHandler
TaskTrigger
trigger TaskTrigger on Task (before insert) {
    if(Trigger.isBefore&&Trigger.isInsert){
        TaskTriggerHandler.beforeInsert(Trigger.New);
    }    
}

Here is TaskTriggerHandler 
public class TaskTriggerHandler {
    
    public static void beforeInsert(List<Task> tasks){
        final string ERTTRECORDTYPENAME = 'ERTT_Task_Record_Type'; // Filter String to get the ERTT Task REcordType Id
        Id recordTypeId_ERT = [select id, DeveloperName from RecordType where sobjecttype = 'Task' AND developername =: ERTRECORDTYPENAME].Id;
        
        List<Task> ERTTasks = new List<Task>();
        Set<Id> caseIdset = new Set<Id>();
        
        for(Task taskProcess : tasks){
            
           
            // Functionality Added to Validate only the ERTT_Task_Record_Type Record type. 
            if(taskProcess.RecordTypeId == recordTypeId_ERT && taskProcess.Action__c != 'airtel account contact Research' )
            {
                ERTTasks.add(taskProcess);
                if(taskProcess.WhatId != null)
                {
                   caseIdset.add(taskProcess.WhatId);
                }
            }
        }
     
        // Making sure there is data in the ERTT Tasks and What Id of the Tasks 
        if(!ERTTasks.isEmpty() && !CaseIdset.isEmpty())
        {
           ERTT_TaskCreationValidation.isairtelAccountResearchcompleted_New(ERTTasks,CaseIdset);
           
            
           
        }
    }
    
}

Here is Apex class with Logic written
 
public class ERTT_TaskCreationValidation {
    
   
     public static void isairtelAccountResearchcompleted_New(List<Task> ERTTTasks,Set<Id> caseIdset)    {
        list<Task> lstTAsk=new list<Task>();
		map<Id, Case> mapCaseWithTaskList = new  map<Id, Case>([select id, (Select id, Action__c from Tasks )  from Case where Id in: caseIdset]); 
        for(Task t : ERTTTasks)
        {
            Boolean validationFlag = true;
            Boolean validationFlag2 = true;
            System.debug('mapCaseWithTaskList.gett.WhatId.tasks'+ mapCaseWithTaskList.get(t.WhatId).tasks);
            if(mapCaseWithTaskList.get(t.WhatId).tasks.size()>0)
            	lstTAsk.add(mapCaseWithTaskList.get(t.WhatId).tasks);
            for(Task t1:  mapCaseWithTaskList.get(t.WhatId).tasks){
                if(t1.Action__c == 'airtel account contact Research')
                {
                    validationFlag = false;
                }
            }
            if(validationFlag){
                t.addError('Please Create a task for airtel account contact Research before creating any other Task');
            }
System.debug(' lstTAsk' +lstTAsk);
            if(lstTAsk.size()==2 && t.Action__c == '2nd field'){
                     validationFlag2=false;
                 }
                 if(validationFlag2){
                    t.addError('Please Create a task for 2nd field before creating any other Task');
                 }
            
        }
    }
    

}

Now the problem is when Task is getting created at Case ,the second Error message is thrown which is "Please Create a task for 2nd field before creating any other Task" whereas requirment is to first show the first error message 'Please Create a task for airtel account contact Research before creating any other Task' and then the second error message
User-added image


'Please Create a task for 2nd field before creating any other Task'

Any idea what is going wrong in the apex class ?

Your reply with  resolution is appreciated

Regards

Fiona

 
Hi guys, When i am starting to connect my org and visualforce, i am getting the below error.

Starting SFDX: Authorize an Org
22:50:06.500 sfdx force:auth:web:login --setalias vscodeOrg --instanceurl https://login.salesforce.com --setdefaultusername
22:50:06.501 sfdx force:auth:web:login --setalias vscodeOrg --instanceurl https://login.salesforce.com --setdefaultusername
 ended with error spawn C:\WINDOWS\system32\cmd.exe ENOENT



I am following this document for setup. please help
Hi,
I need to send email to the Opportunity owner with the list of Products (added in the Opportunity) when the Opportunity is Closed Won. I am unable to write the logic for iterating over the products.
Thanks.
I created  component which shows product data. I need productId on selection of checkbox.Please refer Image
User-added imageAny one give me a hint.
Thanks
I have component where I can select field values from multiselect picklist and this field value should map automatically in column of datatable. I tried below 
 
 var fieldNames=component.get("v.fieldslabel");//list of selected fields from picklist         console.log('****** '+fieldNames);   
      for (var i=0; i < fieldNames.length; i++) {
             var column=[                 
{label: fieldNames[i],fieldName:   fieldNames[i]  }     
        ]      
   }       
component.set('v.columns', this.column);
can any one give me idea.Thanks ! User-added imagevalue is visible  when I inspect , but not in component.
triggger:
public class DemoCaseClass{
 public  void  UpdateCaseQueueField(list<Case> newCases,map<Id,Case> oldMapCases){
 Id salesqueueId =     [select Id from Group where  Type = 'Queue' AND NAME = 'Sales Queue'].id;
  Id supportqueueId =   [select Id from Group where  Type = 'Queue' AND NAME = 'Support Queue'].id;           
   Id onboardqueueId =   [select Id from Group where  Type = 'Queue' AND NAME = 'Onboarding Queue'].id;
         Id interRecordtypeId=Schema.SObjectType.Case.getRecordTypeInfosByName().get('Interdepartmental').getRecordTypeId();
        for(Case c : newCases){
  if(c.Case_Queue__c!=oldMapCases.get(c.Id).Case_Queue__c && c.Case_Queue__c=='Sales Queue'  && c.RecordTypeId==interRecordtypeId ){
             //c.OwnerId='00G8D000000FtXsUAK'; 
            c.OwnerId=salesqueueId;
             system.debug('line 101 '+oldMapCases.get(c.Id).Owner.Name);
             c.Department__c = 'Sales';
             c.Case_From__c=string.valueOf(oldMapCases.get(c.Id).Case_Queue__c);
             }
          else if(c.Case_Queue__c!=oldMapCases.get(c.Id).Case_Queue__c && c.Case_Queue__c=='Support Queue'  && c.RecordTypeId==interRecordtypeId){
              c.OwnerId=supportqueueId;                        
             // c.OwnerId='00G8D000000EwIFUA0';
             c.Department__c = 'Support';
             c.Case_From__c=string.valueOf(oldMapCases.get(c.Id).Case_Queue__c);
            }
         
          else if(c.Case_Queue__c!=oldMapCases.get(c.Id).Case_Queue__c && c.Case_Queue__c=='Onboarding Queue'  && c.RecordTypeId==interRecordtypeId ){
             c.OwnerId= onboardqueueId;    
              // c.OwnerId='00G8D000000EwIPUA0';
             c.Department__c = 'Onboarding';
             c.Case_From__c=string.valueOf(oldMapCases.get(c.Id).Case_Queue__c);
           }         
          
       } 
    }
}


Test :

@isTest
public class InterdepartmentalCaseStatus_Test {
 @isTest(Seealldata=true)
    
    public static void updateCloseStatus(){
        
        Account acc =new Account();
        acc.Name='Test1';
        acc.Installation_Date__c=Date.today();
        acc.Owner_Email__c='test@gmail.com.invalid';
        acc.Account_Status__c='Pending Installation';
        acc.Store_Phone__c='88811122';
        acc.Installation_Type__c='New Construction';
        insert acc;
        System.debug('Account'+acc);
        
        Contact con=new Contact();
        con.LastName='Test';
        con.Email='test@gmail.com.invalid';
        con.AccountId=acc.Id;
        insert con;
        
         //Queue
        Group testGroup = new Group(Name='Sales Queue', Type='Queue');
        insert testGroup;
        
        
        Id supportId=Schema.SObjectType.Case.getRecordTypeInfosByName().get('Support Case').getRecordTypeId(); 
        Case c = new Case();
        c.RecordTypeId= supportId; 
        c.AccountId = acc.id;
        c.ContactId= con.Id;
        c.Status='Open';
        c.Subject='Test';
        c.Comments='Testing';
        insert c;
        
         list<case> caseList1=new list<case>();
         map<Id ,case> oldMapcase1=new  map<Id,case>();
         
        
        Id interRecId=Schema.SObjectType.Case.getRecordTypeInfosByName().get('Interdepartmental').getRecordTypeId();   
       //interdepartmental 1
        Case inter = new Case();
        inter.RecordTypeId= interRecId; 
        inter.AccountId = acc.id;
        inter.ContactId= con.Id;
        inter.Case_Queue__c='Support Queue';       
       // inter.Department__c = 'Support';        
        inter.Status='Open';
        inter.Subject='Test';
        inter.Comments='Testing';
        inter.Related_Case__c= c.id;
        insert inter;
        
        map<id,case> oldCaseMap1=new map<id,case>();
        oldCaseMap1.put(inter.Id,inter);
        //list<case> newCase=new list<case>();
        
        Test.startTest();
     inter.Case_Queue__c= 'Sales Queue';
        caseList1.add(inter);
        update caseList1;
          DemoCaseClass cc = new DemoCaseClass();
        cc.UpdateCaseQueueField(caseList1,oldMapcase1);
          
        Test.stopTest();        
    }
}
can any one help me with the test class
Thank you
How to query Approval Process Name.
SELECT Id,TargetObjectid, Status,a FROM ProcessInstance   
In below image I need to query this label Approval Request Submitted ,is there any way .
User-added image
Hii,
I send email using email alert in flow builder, but receive output as None.
not receive any email even if condition is trueyou can see Output: NOneThank You
I  have  2 levels of approval process ,Team 1 And Team 2. I need to restrict Team 2, Team 2 not able to approve the Opportunity  on certain condition . I mention criteria in  2 level  of approval process but it not works. is there any another way to restrict it.
can we use code to restrict it.
Thank You
I created record trigger flow which fires when checkbox is checked which is updated by Approval process ,but flow does not fire it does not catch the checkbox which is updated by approval process
I dont know what is the issue.
I use the trigger to update the checkbox from approval process

Thank you
I am using
finalBody+='<b>'+'Link : '+'</b>'+URL.getSalesforceBaseUrl().toExternalForm() + '/' +cl.id;
It is working on Android but not in Iphone.
Is there any way that links is works on both Android and iphone
Via setHtmlBody in  Messaging.SingleEmailMessage.



Thank you
hii can we use CSS in setHtmlBody  in Messaging.singleEmailMessage
I  am tryingh it but when send mail Css is not working
thank you
How to Fetch product releted Entitlement Process . Let say I have one Entitlement process called 'Premium support ' . I added it to product via Entitlement template . so i need to fetch it . any one have idea , i need product id  and Entitlement process Id .



Thank you
I have  Entitlement Template Releted list on product . I need to fetch Product With entitlement ,How can i do that .
Thank you
How to implement  Entitlement with Contract , It is available with service Contract but what about contract . Any one have idea how to implement with contract.


Thank you
I need Labels on Line charts ,How can i Add this labels my code is :

 <apex:chart height="400" width="700" data="{!ChartData}" animate="true" >
          <apex:axis type="Numeric" position="left" fields="data1" 
            title="Opportunities Closed" grid="false" gridFill="true"/>
          <apex:axis type="Category" position="bottom" fields="name" 
            title="Month of the Year">
        </apex:axis>
        <apex:lineSeries  tips="true" axis="left" fill="true" xField="name" yField="data1"
                         markerType="cross" markerSize="4" markerFill="#FF0000"  showInLegend="true" highlight="true" fillColor="blue">
         <apex:chartTips height="25" width="150"/>
                       <apex:chartLabel field="data1" display="outside" font="bold 14px Helvetica"  />
 </apex:lineSeries>
        
   </apex:chart>
Please relevent ans only,dont wase my question
Thank you 
This is my code :
String JSONStr = res.getbody();
System.debug('Json String '+res.getbody());
if(res.getstatusCode() == 200 && res.getbody() != null){
List<Object> fmap = (List<Object>)JSON.deserializeUntyped(JSONStr);
System.debug('First Json Map' + fmap);
for(Object o : fmap){
System.debug('Each Object '+ o);


}

}
debug shows duplicate id values but json contain unique Ids
how to store it. 
Thank you
User-added image
Hii Forum ,I have json as follow

[{"recordType":"cashsale","id":"200724","values":{"tranid":"Memorized","entity":[{"value":"3155","text":"100032 EJ's Pizzeria"}],"trandate":"03/04/2020","postingperiod":[{"value":"90","text":"Mar 2020"}],"amount":"140.00","item.itemid":"300-52-3100-S","item.displayname":"Revention Software Maintenance Monthly Subscription","item.salesdescription":"Revention Software Maintenance Monthly","type":[{"value":"CashSale","text":"Cash Sale"}]}}
VF code :
[15:08] Rahul Manjhi
 <apex:column headerValue="tranid" value="{!wrap.values.tranid}​​​​​​​"/>     <apex:column headerValue="item" value="{​​​​​​​!wrap.values.item.itemid}​​​​​​​"/> 
<apex:column headerValue="item" value="{​​​​​​​!wrap.item.itemid}​​​​​​​"/>          <apex:column headerValue="trandate" value="{​​​​​​​!wrap.values.trandate}​​​​​​​"/>                 
<apex:column headerValue="entity" value="{​​​​​​​!wrap.values.entity}​​​​​​​"/>                values.item.itemid gives null value how to get it any one have idea.
Thank you
Hii , I Integrate with external system   Post Call , With trigger when case status is Closed send CaseID__c (Custom Object) external system . i wrote trigger but found debug like Response---Method Not Allowed. Can any one sloved this problem.

public class SendCaseToNetSuite {
     @future (callout=true) 
    public static void UpdateCaseStatus(set<id>  SendCaseId){
       if(!SendCaseId.isEmpty()){ 
    List<case> caseList=[select id,caseId__c,Status from case where caseId__c != null And Id IN :SendCaseId];
         System.debug('caseList'+caseList);
        for(case c:caseList){ 
          //  JSONGenerator gen = JSON.createGenerator(true);
          // Write data to the JSON string.
         // gen.writeStartObject();
         // gen.writeNumberField('caseId',  c.caseId__c);
         // gen.writeEndObject();
          // Get the JSON string.
         // String pretty = gen.getAsString();
         
           Map<String, Integer> tags = new Map<String, Integer>();
            tags.put('caseId',Integer.valueOf(c.caseId__c));
            string endpoint = 'https://1074624-sb1.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=913&deploy=1&compid=1074624_SB1&h=9a5b4f34527b28b1f43d';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endpoint);
                req.setMethod('POST');
                req.setHeader('Content-type', 'application/json');
                //req.setBody(pretty);
               req.setbody(JSON.serialize(tags));
                Http http = new Http();
                HttpResponse res=new HttpResponse();
            try{
                res= http.send(req);
                system.debug('Output response:  ' +res.getBody());
            }
            catch(Exception e){
             system.debug('Error......' +e.getMessage());
            }
             
}
}
        
    }


}

Trigger;

trigger SendCaseToNetsuite on Case (before Update) {
    
    if(trigger.isBefore && trigger.isUpdate){
        set<id> SendCaseId=new set<id>();
         for(Case cases:trigger.new){
        if(cases.Status!=null && cases.Status=='Closed'){
            SendCaseId.add(cases.Id);
        }
         }
         if(!SendCaseId.isEmpty()){ 
        SendCaseToNetSuite.UpdateCaseStatus( SendCaseId);
    }
}
    }

Debug is:
Debug
Hi..If we need to get new data from external api and store in a new custom object in salesforce and run batch on daily basis how do we pass the list of data to start method from callout and response and insert?
i have  custom field product type on Opportunity  , when oppolineItem is created  i have to checck productFamily equal to product type  if not  then show error my code is

trigger CheckProductTypeonOppLineItem_whenItIsCreated on OpportunityLineItem (after insert) {
set<id> setIds=new set<id>();
for(OpportunityLineItem opp:Trigger.new){
    setIds.add(opp.Id);

list<OpportunityLineItem> opplist=[select id,opportunity.Product_type__c, Product2.Family from OpportunityLineItem where id In:setIds];
for(OpportunityLineItem o:opplist){
    if(o.Product2.Family != o.opportunity.Product_type__c){
      o.addError('Product family must be same ');
    }
}
}
any other way ot writing above trigger .
Thank you
i am Creating visulaForce page which shows selected opportunity
but my code is not working it not shows  selected opp
iam unable to find out where is the mistake
Help should be appriciated. Thank You
Here is my code :
<apex:page standardController="Opportunity" recordSetVar="Opps"  sidebar="false" showHeader="false" 
                                      extensions="ParamReceive" >
<apex:form>
    <apex:pageBlock>
        <apex:pageBlockSection>
           <apex:pageBlockTable value="{!Opps}" var="o" id="panel">
             <apex:column>
                 <apex:inputCheckbox>
                     <apex:actionSupport event="Onclick" action="{!doActionSupport}"  reRender="block,panel">
                     <apex:param name="names" value="{!o.Id}" assignTo="{!vfParam}" />
</apex:actionSupport>
                 </apex:inputCheckbox>
             </apex:column>
             <apex:column value="{!o.Name}"/>
             <apex:column value="{!o.stageName}"/>
             <apex:column value="{!o.CloseDate}"/>
             <apex:column value="{!o.Amount}"/>
             <apex:column value="{!o.AccountId}"/>
          </apex:pageBlockTable>
          <apex:outputPanel id="block">
          
          Selected Opportunity  : {!vfParam}<br></br>
        </apex:outputPanel>
        
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>

Controller:
public  class ParamReceive {
        public String vfParam{get; set;}
        public ParamReceive(ApexPages.StandardSetController controller){
          
        }
        public PageReference doActionSupport(){
          // Do Something...
          System.debug('vfParam : ' + vfParam);
          return null;
        }
    }
      
      
Hello forum,
I want to know when to use Apex:ActionFunction .
we call  the controller method from javascript function using ActionFunction . I read this line in many blogs but why i call  controller method from javascript function, when actually i need it .
can any one explain me thank you in advance.
 
Can any one explain me what is the use of picklistValueInfo  and EntityParticleId   can't  find any documents or provide me a document
Thank you
my edit commandLink i s not working , when click no response  check the below code  help me to find error:
controller class:
public class contactSaveandEditClass {
    public List<wrapperclass> contactList{get; set;}
    public integer RowIndex{get; set;}
    public wrapperclass objwrapper;
    public  contactSaveandEditClass(){
        list<contact> contacts=[select id,FirstName,LastName,Phone,Title from contact];
        contactList=new list<wrapperclass>();
    for(integer i=0;i<contacts.size(); i++){
        objwrapper=new wrapperclass(); 
        objwrapper.con=contacts[i];
        objwrapper.doEdit=false;
        objwrapper.RowNo=contacts.size();
        contactList.add(objwrapper);
    }
    }
        public PageReference  EditMethod(){
            if(contactList.size()>RowIndex){
                contactList[RowIndex].doEdit=true;
            }
            return null;
        }
         public pageReference SaveMethod(){
            if(contactList.size()>RowIndex){
                contactList[RowIndex].doEdit=false;
            }
            return null;
        }
         public class wrapperclass{
        public contact con{get; set;}
        public boolean doEdit{get; set;}
        public integer RowNo{get; set;}
    }
}

VF class:
<apex:page controller="contactSaveandEditClass">
    <apex:sectionHeader title="Contacts"/>
    <apex:form >
        <apex:pageblock id="acc" title="Contact List">
            <apex:pageBlockSection >
                <apex:pageblocktable value="{!contactList}" var="a">
                    <apex:column headerValue="Action">
                         <apex:commandlink action="{!EditMethod}" value="Edit" reRender="acc"  rendered="{!NOT(a.doEdit)}">
                             <apex:param Name="rowNumber"  Value="{!a.RowNo}"  assignTo="{!RowIndex}"/>
                        </apex:commandlink>
                     <apex:commandlink action="{!SaveMethod}" value="Save" reRender="acc"  rendered="{!(a.doEdit)}">
                             <apex:param Name="rowNumber"  Value="{!a.RowNo}"  assignTo="{!RowIndex}"/>
                        </apex:commandlink>
                    </apex:column>
                    <apex:column headerValue="FirstName" >
                        <apex:outputField value="{!a.con.FirstName}" rendered="{!NOT(a.doEdit)}" />
                        <apex:inputField value="{!a.con.FirstName}" rendered="{!(a.doEdit)}"/>
                     </apex:column>
                     <apex:column headerValue="LastName" >
                    <apex:outputField value="{!a.con.LastName}" rendered="{!NOT(a.doEdit)}" />
                     <apex:inputField value="{!a.con.LastName}" rendered="{!(a.doEdit)}"/>
                     </apex:column>
                    <apex:column headerValue="Phone">
                     <apex:outputField value="{!a.con.Phone}"  rendered="{!NOT(a.doEdit)}"/>
                     <apex:inputField value="{!a.con.Phone}" rendered="{!(a.doEdit)}"/>
                    </apex:column>
                    <apex:column headerValue="Title" > 
                     <apex:outputField value="{!a.con.Title}" rendered="{!NOT(a.doEdit)}"/>
                     <apex:inputField value="{!a.con.Title}"  rendered="{!(a.doEdit)}"/>
                    </apex:column>
                </apex:pageblocktable>
             </apex:pageBlockSection>
         </apex:pageblock>
     </apex:form>
</apex:page>
Thank You
Is it possible to have a list of contacts from an account as a picklist value in an object populated automatically once any new contact is added?
Hello!
I am trying to build an After Save Flow that triggers on creation with 1 minute delay, on the object Event.
My flow checks on has multiple decisions and updates the Event record at the end, also updates the WhoId(Lead or Contact) record related to the record that I got through a get action.
However, even though I have the schedule path created as shown in the picture, the record updates instantly. I tried adding more minutes or hours to the scheduled path, and it didn't work either.
Is this the expected behaviour?
I am not sure I am understanding the process of the Scheduled Paths correctly so I appreciate any help on making a flow that updates the record with delay. Thank you!

User-added image

Beginner user here.
I use flows to raise important tasks when accounts or Opportunities meet specific criteria. Generally speaking, I only ever need the flow to run once per record to avoid a flow creating duplicate tasks. Is there an easy option inside flows to ensure a specific flow runs once per record?
Instead of doing a lookup on the record to see if this task already exists to avoid the flow running multiple times on same record? (I dont know how to do this)
(Part 1)
Let us suppose that our Salesforce users are physicians working in a private clinic. Our Salesforce org is the clinic’s system with its own database and internal applications. Each physician has various in clinic visits with patients scheduled throughout the day. Physicians should be differentiated by other types of users like the System Administrator. A physician with the name John Doe needs to be registered on this Salesforce Org. Physicians can view and modify their own visit records, by changing time and date of the visit, description, or even the patient of the visit. They cannot, however, see or modify the records of their colleagues. The following information should be mandatory on every visit: Date/Time of visit and patient information (must include first name, last name and email). It should also have a timespan value of 15 minutes, 30 minutes or 1 hour. An optional information to be filled for patients will also be a ranking value which can vary between values: Low, Mid, High. Only the physician John Doe should be able to rank the patients, other physicians should not be able to see or interact with this ranking value. When a physician’s logs into the Salesforce log, they should be able to see directly on login, the interface to register the patient’s visitations.(Part2)
The visit records (from the first task) of the same physician are not allowed to overlap with each other.
(For example, if visit #1 is scheduled today on 13:30 and has a timespan of 1 hour, then if visit #2 has a timespan of 30 minutes, it should not be allowed to have a start time at 13: 15 or 14:00, but it can before 13:00 or after 14:30).
When a user creates, updates, or deletes a visit record on Salesforce, the patient receives an email notification letting them know the new time/date of the visit, or that the visit has been canceled.
In addition, every morning at 7:00AM, physicians must receive an email with their scheduled visits of the day.
  • July 22, 2022
  • Like
  • 0
write trigger for:
Creates the number of contacts which are equal to the number which we will enter in the Number of Locations field on the Account Object.
Create Custom field called “Number of Locations” on the Account Object (Data Type=Number). can anyone provide code for this requirement
 
trigger TaskTrigger on Task (after insert,before delete,after update) {
    public List<Task> ltask1 = new List<Task>();
    public id acid;
    public integer clo=0;   
    public integer ope=0;
    public integer blk=0;
    if(trigger.isinsert || trigger.isupdate){  
    for(Task t:Trigger.New){
        acid = t.WhatId;
        system.debug('accid'+acid);
        
    }
    ltask1 = [select id,Status from task where whatid=:acid];
    system.debug('acsize'+ltask1.size());
    
    
    for(task t:ltask1){
        if(t.Status=='Completed'){
            clo = clo+1;
            system.debug(clo);
        } else if(t.Status=='In Progress'){
            ope = ope +1;
            system.debug(ope);
        }else if(t.Status=='Deferred')
        {
             blk = blk+1;
            system.debug(blk);
        }                
    } List<Account> acc = new List<Account>();    
    List<Account> ac = [select id from Account where id = :acid];
    system.debug('oppsize'+ac.size());
    for(Account a: ac){
        a.Open_Task__c = ope;
        a.Closed_Tasks__c = clo;
        a.Blocked_Tasks__c=blk;
        acc.add(a);  
    } if(acc.size()>0){
        update acc;
    }   
    }
        //ltask = [select id,Status from task where whatid=:acid];
        
   
   
    if (Trigger.isDelete){
              for (Task t : trigger.Old) {
                   acid=t.whatid;
               }
    ltask1 = [select id,Status from task where whatid=:acid];
    system.debug('acsize'+ltask1.size());
    
    
    for(task t:ltask1){
        if(t.Status=='Completed'){
            clo = clo-1;
            system.debug(clo);
        } else if(t.Status=='In Progress'){
            ope = ope -1;
            system.debug(ope);
        }else if(t.Status=='Deferred')
        {
             blk = blk-1;
            system.debug(blk);
        }                
    } List<Account> acc = new List<Account>();    
    List<Account> ac = [select id from Account where id = :acid];
    system.debug('oppsize'+ac.size());
    for(Account a: ac){
        a.Open_Task__c = ope;
        a.Closed_Tasks__c = clo;
        a.Blocked_Tasks__c=blk;
        acc.add(a);  
    } if(acc.size()>0){
        update acc;
    }   
    }
      
    system.debug('No of Tasks'+ope+ clo+blk);

    }
        
Here there is a Trigger which calls Trigger handler and in turn Trigger handler calls the apex class,this  apex class is to create tasks on Case record 
and the goal here is to prevent a Task from being created for 2 scenarios
  • First  Task with the Action__c field being ‘airtel account contact Research’ and once user creates a Task with Action__c as "‘airtel account contact Research’"
  • then they should only  able to create second  Task with Action__c as '1st airtel contact'',

Now after these 2 tasks creation is done then user can create any task with any picklist value in Action__c field

Here is Trigger which calls TaskTriggerHandler
TaskTrigger
trigger TaskTrigger on Task (before insert) {
    if(Trigger.isBefore&&Trigger.isInsert){
        TaskTriggerHandler.beforeInsert(Trigger.New);
    }    
}

Here is TaskTriggerHandler 
public class TaskTriggerHandler {
    
    public static void beforeInsert(List<Task> tasks){
        final string ERTTRECORDTYPENAME = 'ERTT_Task_Record_Type'; // Filter String to get the ERTT Task REcordType Id
        Id recordTypeId_ERT = [select id, DeveloperName from RecordType where sobjecttype = 'Task' AND developername =: ERTRECORDTYPENAME].Id;
        
        List<Task> ERTTasks = new List<Task>();
        Set<Id> caseIdset = new Set<Id>();
        
        for(Task taskProcess : tasks){
            
           
            // Functionality Added to Validate only the ERTT_Task_Record_Type Record type. 
            if(taskProcess.RecordTypeId == recordTypeId_ERT && taskProcess.Action__c != 'airtel account contact Research' )
            {
                ERTTasks.add(taskProcess);
                if(taskProcess.WhatId != null)
                {
                   caseIdset.add(taskProcess.WhatId);
                }
            }
        }
     
        // Making sure there is data in the ERTT Tasks and What Id of the Tasks 
        if(!ERTTasks.isEmpty() && !CaseIdset.isEmpty())
        {
           ERTT_TaskCreationValidation.isairtelAccountResearchcompleted_New(ERTTasks,CaseIdset);
           
            
           
        }
    }
    
}

Here is Apex class with Logic written
 
public class ERTT_TaskCreationValidation {
    
   
     public static void isairtelAccountResearchcompleted_New(List<Task> ERTTTasks,Set<Id> caseIdset)    {
        list<Task> lstTAsk=new list<Task>();
		map<Id, Case> mapCaseWithTaskList = new  map<Id, Case>([select id, (Select id, Action__c from Tasks )  from Case where Id in: caseIdset]); 
        for(Task t : ERTTTasks)
        {
            Boolean validationFlag = true;
            Boolean validationFlag2 = true;
            System.debug('mapCaseWithTaskList.gett.WhatId.tasks'+ mapCaseWithTaskList.get(t.WhatId).tasks);
            if(mapCaseWithTaskList.get(t.WhatId).tasks.size()>0)
            	lstTAsk.add(mapCaseWithTaskList.get(t.WhatId).tasks);
            for(Task t1:  mapCaseWithTaskList.get(t.WhatId).tasks){
                if(t1.Action__c == 'airtel account contact Research')
                {
                    validationFlag = false;
                }
            }
            if(validationFlag){
                t.addError('Please Create a task for airtel account contact Research before creating any other Task');
            }
System.debug(' lstTAsk' +lstTAsk);
            if(lstTAsk.size()==2 && t.Action__c == '2nd field'){
                     validationFlag2=false;
                 }
                 if(validationFlag2){
                    t.addError('Please Create a task for 2nd field before creating any other Task');
                 }
            
        }
    }
    

}

Now the problem is when Task is getting created at Case ,the second Error message is thrown which is "Please Create a task for 2nd field before creating any other Task" whereas requirment is to first show the first error message 'Please Create a task for airtel account contact Research before creating any other Task' and then the second error message
User-added image


'Please Create a task for 2nd field before creating any other Task'

Any idea what is going wrong in the apex class ?

Your reply with  resolution is appreciated

Regards

Fiona

 
Hi folks,

How to resolve the this error in the  logic of the trigger handler class
 
Method does not exist or incorrect signature: void add(Object) from the type Set<Id>

Here is trigger apex
 

trigger TaskTrigger on Task (before insert) {
    if(Trigger.isBefore&&Trigger.isInsert){
        TaskTriggerHandler.beforeInsert(Trigger.New);
    }    
    
    Map<Id, Task> mapTaskWithRelatedTask = new Map<Id, Task>();
Set<Id> setWhatIds = new Set<Id>();

for (Task objTask : Trigger.New) {
    mapTaskWithRelatedTask.put(objTask.whatId, objTask);
}
for (AggregateResult ar : [SELECT whatId FROM Task WHERE whatId IN: mapTaskWithRelatedTask.keySet() AND Action__c = 'Airtel  contact' GROUP BY whatId]) 
{
    setWhatIds.add(ar.get('whatId'));
}
for (Task objTask : mapTaskWithRelatedTask.values()) {
    if (!setWhatIds.contains(objTask.whatId)) {
        objTask.addError('Please Create a task for airtel account contact Research before creating any other Task');
    }
}
}
Your help is appreciated

Regards

Fiona
 

Hello,

We would like to deactivate two apex triggers that are obsolete and are causing issues on our account and preventing us from using the a connector correctly. I went into a Sandbox to create a change set to deactivate these two triggers and made the change set available to production. Unfortunatly when I try to deploy it I am getting errors saying that my coverage is only of 69%. I try to run the fulls tests but am getting errors on things that are completely unrelated. I would really need to deactivate these two apex triggers. How can I proceed? 

 

I noticed the code coverage is at 0% in the sandbox... I don't really understand.

 

PS- I'm not a developper. The developper who coded this apex trigger has left the company.

I have  Entitlement Template Releted list on product . I need to fetch Product With entitlement ,How can i do that .
Thank you
Problem is when case raise along with attachmnet file is uploded but its fileextension is blank because of this im not able to view the file I try with trigger but shhowing error fileextension field is not writable
Hii , I Integrate with external system   Post Call , With trigger when case status is Closed send CaseID__c (Custom Object) external system . i wrote trigger but found debug like Response---Method Not Allowed. Can any one sloved this problem.

public class SendCaseToNetSuite {
     @future (callout=true) 
    public static void UpdateCaseStatus(set<id>  SendCaseId){
       if(!SendCaseId.isEmpty()){ 
    List<case> caseList=[select id,caseId__c,Status from case where caseId__c != null And Id IN :SendCaseId];
         System.debug('caseList'+caseList);
        for(case c:caseList){ 
          //  JSONGenerator gen = JSON.createGenerator(true);
          // Write data to the JSON string.
         // gen.writeStartObject();
         // gen.writeNumberField('caseId',  c.caseId__c);
         // gen.writeEndObject();
          // Get the JSON string.
         // String pretty = gen.getAsString();
         
           Map<String, Integer> tags = new Map<String, Integer>();
            tags.put('caseId',Integer.valueOf(c.caseId__c));
            string endpoint = 'https://1074624-sb1.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=913&deploy=1&compid=1074624_SB1&h=9a5b4f34527b28b1f43d';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endpoint);
                req.setMethod('POST');
                req.setHeader('Content-type', 'application/json');
                //req.setBody(pretty);
               req.setbody(JSON.serialize(tags));
                Http http = new Http();
                HttpResponse res=new HttpResponse();
            try{
                res= http.send(req);
                system.debug('Output response:  ' +res.getBody());
            }
            catch(Exception e){
             system.debug('Error......' +e.getMessage());
            }
             
}
}
        
    }


}

Trigger;

trigger SendCaseToNetsuite on Case (before Update) {
    
    if(trigger.isBefore && trigger.isUpdate){
        set<id> SendCaseId=new set<id>();
         for(Case cases:trigger.new){
        if(cases.Status!=null && cases.Status=='Closed'){
            SendCaseId.add(cases.Id);
        }
         }
         if(!SendCaseId.isEmpty()){ 
        SendCaseToNetSuite.UpdateCaseStatus( SendCaseId);
    }
}
    }

Debug is:
Debug
Hi all,
I was created the trigger on contentDocument obj for after insert . But when i upoload document from UI in Dev environment the created trigger was not firiing . please help
i have  custom field product type on Opportunity  , when oppolineItem is created  i have to checck productFamily equal to product type  if not  then show error my code is

trigger CheckProductTypeonOppLineItem_whenItIsCreated on OpportunityLineItem (after insert) {
set<id> setIds=new set<id>();
for(OpportunityLineItem opp:Trigger.new){
    setIds.add(opp.Id);

list<OpportunityLineItem> opplist=[select id,opportunity.Product_type__c, Product2.Family from OpportunityLineItem where id In:setIds];
for(OpportunityLineItem o:opplist){
    if(o.Product2.Family != o.opportunity.Product_type__c){
      o.addError('Product family must be same ');
    }
}
}
any other way ot writing above trigger .
Thank you

Hi all, 
I have a custom object "Custom1" on which we added an Approval process. The process is easy when the object is approved by the approver then I have a Final Approval Actions that is set to update a field in "Custom1" Called is_approved ( True/False - Checkbox)

Then using a Flow builder I set that if the field is is_approved: True then it should trigger the flow that will update a field in many records linked to "Custom1"

For some reason, the Flow Builder is not triggered when it happens after the approval process. However, if I edit the field is_approved to TRUE manually then the flow is triggered 

Could you please help me to trigger it after the approval process?

 

FYI: User-added image