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


  • Chatter
    Feed
  • 285
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 1
    Questions
  • 1431
    Replies
Hello,
I am unable to fix the error 
System.NullPointerException: Attempt to de-reference a null object on my trigger.

Could someone help?
Thanks
 
trigger Knowledge_kavKnownErrorSubscription on Knowledge__kav (after insert, after update) {
    
    List<Known_Error_Subscription__c> kesList = new List<Known_Error_Subscription__c>();
    
    for(Knowledge__kav kav : [SELECT KnowledgeArticleId, Known_Error_Status__c, VersionNumber, (SELECT Knowledge__c FROM Known_Errors_Subscriptions__r)
                              FROM Knowledge__kav WHERE Id IN :Trigger.New]) {
                                                                              
            if(kav.KnowledgeArticleId != null && (Trigger.oldMap.get(kav.Id).LastPublishedDate != Trigger.newMap.get(kav.Id).LastPublishedDate)) {
            Known_Error_Subscription__c kes = kav.Known_Errors_Subscriptions__r;
            kes.Knowledge__c = kav.KnowledgeArticleId;
            kesList.add(kes);
            
        }
                                  
    }
    if(kesList.size() > 0) {
        update kesList;
    }
    

}

 
I'm using the following code:


global class SendNotificationBatch implements Database.Batchable<sObject>, Schedulable, Database.Stateful { //Variable Section global FINAL String strQuery; global List<String> errorMessages = new List<String>(); global SendNotificationBatch() { this.strQuery = getBatchQuery(); } //Returns the Query String to Batch constructor to fetch right records. private String getBatchQuery() { String strQuery = 'SELECT Id, CloseDate, Owner.Email FROM Opportunity WHERE CloseDate < TODAY'; return strQuery; } //Batch Start method global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator(strQuery); } //Batch Execute method calls findCostForWoD method global void execute(Database.BatchableContext BC, List<sObject> scopeList) { System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size()); List<Opportunity> oppList = (List<Opportunity>) scopeList; if(!oppList.isEmpty()) { List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>(); for (Opportunity prod : oppList) { Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {prod.Owner.Email}; Message.setToAddresses(toAddresses); Message.SaveAsActivity = false; mailList.add(Message); } if(!mailList.isEmpty()) { try{ Messaging.sendEmail(mailList); } catch (Exception ex) { errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString()); } } } } //Batch Finish method for after execution of batch work global void finish(Database.BatchableContext BC) { AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()]; // Send an email to the Apex job's submitter notifying of job completion. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {aaj.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('JOB Salesforce Send Notification Batch: ' + aaj.Status); String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n'; bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n'; bodyText += 'Error Message' + String.join(errorMessages, '\n'); mail.setPlainTextBody(bodyText); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } //Method which schedules the ProductDownloadBatch global void execute(SchedulableContext sc) { SendNotificationBatch snInstance = new SendNotificationBatch(); ID batchprocessid = Database.executeBatch(snInstance); } }

but I get this error when executing:

Error MessageUnable to send email to Tech: Class.SendNotificationBatch.execute: line 41, column 1

I'm assuming it has to do with opportunity products, when I just want to look at the CloseDate field on the Opportunity object. Any ideas on what to change?  Thanks!

Hi, I am new to development and and stuck with two different scenario for a trigger on before insert & before update context variables.

SCENARIO 1 - BEFORE INSERT

I have created 2 objects, 1 is for Course and another is Student.
Trigger is on the student object which will check the open vacancies(formula field on course i.e. Total strength - Total no of students(which is again a roll up summary of count of students)) for the course he/she will apply for.
If the open vacancy == 0 then the admin should get error while creating record. 

set<Id> courseIds = new set<Id>();
            System.debug('Before insert trigger fired');
            for(Student__c student : Trigger.New){
                courseIds.add(student.Course_Name__c);
            }
            for(Course__c course : [SELECT Id, Name, Open_Vacancies__c FROM Course__c WHERE Id IN: courseIds]){
                if(course.Open_Vacancies__c == 0){
                    System.debug('Seats are full');
                }
            }


Please refer the above code snippet I have wrote but the problem is I can not add addError() method on the student record as it is out of for loop. Debug is working fine but also create the record. SInce it is creating record open vacacy is field's value is going in negative but it should not happen until and unless open vacancy > 0.

SCENARIO 2 - BEFORE UPDATE

For this scenario also facing same issue wih addError() method. Here the scenario is to restrict the admin from updating the enrollment no.(field on student object). If the enrollment no is updating then it should give an error message

if(Trigger.isUpdate){
            for(Student__c student : Trigger.old){
                System.debug('Before Update trigger fired');
                if(Trigger.oldMap.get(student.Id).Enrollment_Number__c != Trigger.NewMap.get(student.Id).Enrollment_Number__c){
                    System.debug('You can not update the enrollment number');
                    
                    //One way to show error
                    student.addError('You can not update enrollment number');
                    
                    //Another way to show error
                    Student__c record = Trigger.oldMap.get(student.ID);
                    record.addError('You can not update enrollment number');
                }
            } 
        }


Please refer the above code snippet I have wrote here also, debug is working fine, but addError Method is not working.

Thanks.

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

 
Hi All,

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

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

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

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

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

For Example: 

Jane Grey

TheSearchForJaneGrey


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

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

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

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

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

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


What do I have wrong here?
Hello,

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

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

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

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

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

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

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

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

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

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

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

				for(VIP_Type__c vip: a.VIP_Types__r){ 

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

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

 
Hello,

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

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

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

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

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

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


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

 
Hi,

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

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

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

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

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

How can I fix the nullPointer exception:
Thanks.

Here is the trigger 
 

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

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

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

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

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

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

Any ideas ? 
Thanks a lot 

Hello,

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

Thanks
 

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

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


 

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

Thanks,
Mahesh
Hi Everyone,

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

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

Any help is greatly appreciated!

Thanks,
Abhishek Bansal
Hello, I am no developer, but I am trying to turn off an existing apex class by just commenting it out. I'm able to do that, and when I push it into production, I keep getting an error realted to the actual apex class: 

System.DmlException: Process failed. First exception on row 0; first error: NO_APPLICABLE_PROCESS, No applicable approval process was found.: []
Stack Trace: Class.NewcostsheetwithapprovalTest.testallmethodwithNoInitialvaluesET: line 563, column 1

Any suggestions on removing the error?

First line of apex class: 

public class NewcostsheetwithapprovalTest
{    
/*
  
I need help creating an alert to an account/opportunity so the owner of the account or opportunity receives an alert if they haven't touched the account (phone or email) in 30 days.
Hello Guys

I need a small help, I am trying to design an aura component for my client where he needs to access the content documents while creating the new case, I have overridden the button and tried to show the aura component with Dynamic search functionality, Now my Issue is that when i search with the keyword,  I am not getting the documents with Preview and hyperlink options,I have referred several website links but could not find the solution

https://sfdcmonkey.com/2018/10/29/open-files-lightning-component/

https://www.forcetalks.com/blog/implementation-of-dynamic-search-in-lightning-component/

My Component
 
<aura:component controller="FilesListApexController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:actionOverride" access="global">
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchListOfRecordTypes}"/>
    
    <aura:attribute name="lstOfRecordType" type="String[]" />
    <aura:attribute name="isOpen" type="boolean" default="false" />
    <div style="font-size: 30px;">
    <div class="slds-align_absolute-center">Welcome to the Case Portal</div>
    </div>
     <h1 class="slds-page-header__title slds-m-right_small slds-align-middle slds-truncate"  title="Case Help Documents">Please click the below button to create a New Case</h1>
  <div class="slds-m-around--x-large">
    <lightning:button label="Create a Case" onclick="{!c.openModal}" />
  </div>   
    
    <h1 class="slds-page-header__title slds-m-right_small slds-align-middle slds-truncate"  title="Case Help Documents">Case Help Documents</h1>
   <!-- Model Box Start -->    
    <aura:if isTrue="{!v.isOpen}">
        <div role="dialog" tabindex="-1" aria-labelledby="header43" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <div class="slds-modal__header">
                    <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="{!c.closeModal}">
                        X<span class="slds-assistive-text">Cancel</span>
                    </button>
                    <h2 id="header43" class="slds-text-heading--medium">New Case</h2>
                </div>
                
                <div class="slds-modal__content slds-p-around--medium">
                    <div class="slds-grid slds-wrap">
                        <div class="slds-size--1-of-2 slds-large-size--1-of-2">
                             <div class="slds-align--absolute-center">Select a Record Type</div>                            
                        </div>
                        <div class="slds-size--1-of-2 slds-large-size--1-of-2">
                            <ui:inputSelect aura:id="selectid">
                                <aura:iteration items="{!v.lstOfRecordType}" var="Cases__c">                            
                                    <ui:inputSelectOption text="{!Cases__c}" label="{!Cases__c}"  />
                                </aura:iteration>
                            </ui:inputSelect>
                        </div>&nbsp; &nbsp;
                    </div>                  
                </div>
                
                <div class="slds-modal__footer">
                    <lightning:button class="slds-button slds-button--neutral" onclick="{!c.closeModal}">Cancel</lightning:button>
                    <lightning:button class="slds-button slds-button--brand" onclick="{!c.createRecord}">Next</lightning:button>
                </div>
            </div>
        </div>
        <div class="slds-backdrop slds-backdrop--open"></div>
    </aura:if>
    
    <aura:attribute name="Documents" type="List" />
    <aura:attribute name="key" type="String" /> 
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />        
    <lightning:input type="text" name="searchKey" aura:id="searchKey" onchange="{!c.searchKeyChange}" placeholder="Search" />          
    <table class="slds-table slds-table_bordered slds-table_striped slds-table_cell-buffer slds-table_fixed-layout">
        <thead>
            <tr class="slds-text-heading_label">              
                <th scope="col"><div class="slds-truncate" title="Name">Title</div></th>
                <th scope="col"><div class="slds-truncate" title="File Type">FileType</div></th>         
                <th scope="col"><div class="slds-truncate" title="Created By">Created By</div></th>            
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.Documents}" var="Document">
                <tr>  
                    <td><div class="slds-truncate" title="{!Document.Title}">{!Document.Title}</div></td>
                    <td><div class="slds-truncate" title="{!Document.Type}">{!Document.FileType}</div></td>                   
                    <td><div class="slds-truncate" title="{!Document.CreatedBy.Name}">{!Document.CreatedBy.Name}</div></td>                    
                </tr>
            </aura:iteration>
        </tbody>
    </table>    
    
    <aura:if isTrue="{!v.hasModalOpen}">
        <section onclick="{!c.closeModel}"
                 role="dialog"
                 aria-modal="true"
                 class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <div class="slds-modal__content slds-p-around_medium slds-text-align_center"
                     style="background: transparent;">
                    <div style="width: 50%; margin: 0 auto; text-align: left">
                        <!--<lightning:fileCard> to preview file using content document Id -->
                        <lightning:fileCard fileId="{!v.Documents}"/>
                    </div>
                </div>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </aura:if>
    
    
</aura:component>

My Controller
 
({
    
    /* On the component Load this function call the apex class method,
    * which is return the list of RecordTypes of object
    * and set it to the lstOfRecordType attribute to display record Type values
    * on ui:inputSelect component. */
    
    fetchListOfRecordTypes: function(component, event, helper) {
        var action = component.get("c.fetchRecordTypeValues");
        action.setCallback(this, function(response) {
            component.set("v.lstOfRecordType", response.getReturnValue());
        });
        $A.enqueueAction(action);
    },
    
    /* In this "createRecord" function, first we have call apex class method
    * and pass the selected RecordType values[label] and this "getRecTypeId"
    * apex method return the selected recordType ID.
    * When RecordType ID comes, we have call  "e.force:createRecord"
    * event and pass object API Name and
    * set the record type ID in recordTypeId parameter. and fire this event
    * if response state is not equal = "SUCCESS" then display message on various situations.
    */
    createRecord: function(component, event, helper) {
        component.set("v.isOpen", true);
        
        var action = component.get("c.getRecTypeId");
        var recordTypeLabel = component.find("selectid").get("v.value");
        action.setParams({
            "recordTypeLabel": recordTypeLabel
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var createRecordEvent = $A.get("e.force:createRecord");
                var RecTypeID  = response.getReturnValue();
                createRecordEvent.setParams({
                    "entityApiName": 'Cases__c',
                    "recordTypeId": RecTypeID
                });
                createRecordEvent.fire();
                
            } else if (state == "INCOMPLETE") {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Oops!",
                    "message": "No Internet Connection"
                });
                toastEvent.fire();
                
            } else if (state == "ERROR") {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Error!",
                    "message": "Please contact your administrator"
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);
    },
    
    closeModal: function(component, event, helper) {
        // set "isOpen" attribute to false for hide/close model box
        component.set("v.isOpen", false);
    },
    
    openModal: function(component, event, helper) {
        // set "isOpen" attribute to true to show model box
        component.set("v.isOpen", true);
    },
    
    doInit: function(component, event, helper) {
        helper.getDocumentList(component);
    },
    searchKeyChange: function(component, event) {
        var searchKey = component.find("searchKey").get("v.value");
        console.log('searchKey:::::'+searchKey);
        var action = component.get("c.findByTitle");
        action.setParams({
            "searchKey": searchKey
        });
        action.setCallback(this, function(a) {
            component.set("v.Documents", a.getReturnValue());
        });
        $A.enqueueAction(action);
    },   
     getSelected : function(component,event,helper){
        // display modle and set seletedDocumentId attribute with selected record Id   
        component.set("v.hasModalOpen" , true);
        component.set("v.Documents" , event.currentTarget.getAttribute("data-Id")); 
        
    },
    closeModel: function(component, event, helper) {
        // for Close Model, set the "hasModalOpen" attribute to "FALSE"  
        component.set("v.hasModalOpen", false);
        component.set("v.Documents" , null); 
    },
    
    doInit : function(component, event, helper) {
        var action = component.get("c.getDocuments");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.Documents', response.getReturnValue());
            }
            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);  
    },
    getSelected : function(component,event,helper){
        // display modle and set seletedDocumentId attribute with selected record Id   
        component.set("v.hasModalOpen" , true);
        component.set("v.Documents" , event.currentTarget.getAttribute("data-Id")); 
        
    },
    closeModel: function(component, event, helper) {
        // for Close Model, set the "hasModalOpen" attribute to "FALSE"  
        component.set("v.hasModalOpen", false);
        component.set("v.Documents" , null); 
    },
    
})

My Helper
 
({      
    getDocumentList: function(component) {
        var action = component.get('c.getDocuments');
        var self = this;
        action.setCallback(this, function(actionResult) {
            component.set('v.Documents', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})

My Apex codee
 
public class FilesListApexController {
    
    @AuraEnabled
    public static Cases__c getsharechatcases(String recordId){
        Cases__c c = [SELECT Id,Name,Status__c,Parent_cases__c,OwnerId,Priority__c,Email__c,
                      RecordTypeId,Problem_Description__c,Internal_comments__c,Asset_category__c,Case_closed_date__c,Other_Software_Details__c FROM Cases__c WHERE Id =: recordId];
        return c;
    }
    public static Map<Id, String> recordtypemap {get;set;}
    
   @AuraEnabled        
    public static List<String> fetchRecordTypeValues(){
        List<Schema.RecordTypeInfo> recordtypes = Cases__c.SObjectType.getDescribe().getRecordTypeInfos();    
        recordtypemap = new Map<Id, String>();
        for(RecordTypeInfo rt : recordtypes){
            if(rt.getName() != 'Master')
            recordtypemap.put(rt.getRecordTypeId(), rt.getName());
        }        
        return recordtypemap.values();
    }
    
    @AuraEnabled
    public static Id getRecTypeId(String recordTypeLabel){
        Id recid = Schema.SObjectType.Cases__c.getRecordTypeInfosByName().get(recordTypeLabel).getRecordTypeId();        
        return recid;
    }
    @AuraEnabled
    public static List <contentDocument> getDocuments(Id arecordId) {
        List<ContentDocumentLink> CDLs = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :arecordId];
        if (CDLs.size() < 1) return new List<ContentDocument>(); 

        // Make a List of ContentDocument IDs
        List <Id> CDIdList = new List <Id> ();
        for (ContentDocumentLink nextCDL : CDLs) {
            CDIdList.add(nextCDL.ContentDocumentId); }        

        List<ContentDocument> entries = [SELECT Id, Title, FileType FROM ContentDocument WHERE ContentDocument.Id IN :CDIdList];
        return entries;
    }
        
    @AuraEnabled
    public static List<contentDocument> findByTitle(String searchKey) {
        String Title =  + searchKey + '%';
        List<contentDocument> DocList = [Select id,Title,FileType,CreatedBy.Name,ContentSize From contentDocument WHERE Title LIKE :Title];
        return DocList;
    }
}

My Error Snapshot

User-added imageI need Preview, hyperlink, and download options just like we do in the files object​​​​​​​
 
Hi,

I am trying to query SObjectType field from Duplicate Record Set object but getting below error
No such column 'SObjectType' on entity 'DuplicateRecordSet'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names."

here is the dev refrence for that field https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_duplicaterecordset.htm.

Salesforce Support is also not much helpful. Has any one had this issue? If any one can help it would be great

 
Hi all, if anyone spot what is the cause of in the following code error?
debug log tells me that is "argument can not be null."

User-added image
and it seems it null pointer exception issue in the loop of for (Billing__c due : dueBillings) part, but not sure what can fix this.

The logic is Apex Controller is called by controller.js fetchDueBalance method, pass the return value to the controller.js, then set component dueBalance (Decimal) in the component.

Apex Controller
@AuraEnabled
    public static Decimal fetchDueBalance(Id recordId) {
        // check which object started the apex class
        Decimal dueBalance;
        String sObjName = recordId.getSObjectType().getDescribe().getName();
        List<Billing__c> dueBillings = new List<Billing__c>();
        System.debug('dueBlalance: initial point: ' + dueBalance); //passed

        if (sObjName == 'Billing__c') {
            Billing__c bl = [
            SELECT Id, Case__c
            FROM Billing__c 
            WHERE Id =:recordId
            LIMIT 1
            ];

            dueBillings = [
                SELECT Id, Due_Balance__c
                FROM Billing__c
                WHERE Case__c = :bl.Case__c AND Due_Balance__c !=0 AND User_Due_Date__c < :Date.today()
                ORDER BY User_Due_Date__c ASC
            ];
            System.debug('dueBlalance: list search: ' + dueBalance); // passed

            if (dueBillings != null){
                System.debug('dueBlalance: nullcheck: ' + dueBalance); // passed
                dueBalance = 0;

                for (Billing__c due: dueBillings) {
                    dueBalance += due.Due_Balance__c;

                    System.debug('dueBlalance: loop point: ' + dueBalance); /passed
                }
            }
        }     
    return dueBalance;
    }
It passes to the final debug log, but not returning the dueBalance value (Decimal) to the component via controller.

Component
<aura:component controller="BillingCheckController" implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes">
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
   <aura:attribute name="recordId" type="Id" />
   <aura:attribute name="dueBalance" type="Decimal" />
   <aura:attribute name="billings" type="Billing__c[]" description="store accounts with there child contacts"/>
   
   <h1><lightning:formattedNumber value="{!v.dueBalance}"></lightning:formattedNumber></h1>
Controller.js
({
    doInit: function(component, event, helper) {
       //call apex class method
        var recordId = component.get("v.recordId");
        var action = component.get('c.fetchBillings');
        action.setParams({recordId :recordId});
        action.setCallback(this, function(response) {
            var state = response.getState();
                if (state === "SUCCESS") {
                    component.set('v.billings', response.getReturnValue());
                }
        });
        $A.enqueueAction(action);

        /* action1 for the sumup number of the overdue billings */
        var recordId = component.get("v.recordId");
        var action = component.get('c.fetchDueBalance');
        action.setParams({recordId :recordId});
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
                if (state === "SUCCESS") {
                    component.set('v.dueBalance', response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
})
Help me sleep...

 
  • February 28, 2021
  • Like
  • 0
Hello,
I am unable to fix the error 
System.NullPointerException: Attempt to de-reference a null object on my trigger.

Could someone help?
Thanks
 
trigger Knowledge_kavKnownErrorSubscription on Knowledge__kav (after insert, after update) {
    
    List<Known_Error_Subscription__c> kesList = new List<Known_Error_Subscription__c>();
    
    for(Knowledge__kav kav : [SELECT KnowledgeArticleId, Known_Error_Status__c, VersionNumber, (SELECT Knowledge__c FROM Known_Errors_Subscriptions__r)
                              FROM Knowledge__kav WHERE Id IN :Trigger.New]) {
                                                                              
            if(kav.KnowledgeArticleId != null && (Trigger.oldMap.get(kav.Id).LastPublishedDate != Trigger.newMap.get(kav.Id).LastPublishedDate)) {
            Known_Error_Subscription__c kes = kav.Known_Errors_Subscriptions__r;
            kes.Knowledge__c = kav.KnowledgeArticleId;
            kesList.add(kes);
            
        }
                                  
    }
    if(kesList.size() > 0) {
        update kesList;
    }
    

}

 
Can user create a record If he don't have access on object and executing apex class(Creates new record on that object) having with sharing keyword?

Hello, I am writing a trigger with the following requirements:

 

Write a trigger that automatically sets Tasks to the “Completed” status whenever their associated Leads are set to any Closed status. Make sure your trigger is bulkified - there should be no SOQL queries inside any loops.


I have written the following trigger - it works well if the task is 'Closed - Not Converted' however when I convert the lead, the task is not closing. Can you provide some guidance please?

 

 

trigger SetTaskCompletedOnLeadClosed on Lead (after update) {
//Create a set of ideas for no duplicates
    Set<Id> leadListIds = new Set<Id>();
    for(Lead l : Trigger.new){
    // Access the "old" record by its ID in Trigger.oldMap     
        if(l.status == 'Closed - Converted' || l.status == 'Closed - Not Converted'){
            leadListIds.add(l.id);
            system.debug('LeadListIds = '+leadListIds);
            }
        }
    
    List<Task> taskList = [SELECT id, subject, status, whoid FROM Task WHERE whoid in :leadListIds];
    system.debug('taskList = '+taskList);
    
    List<Task> taskToUpdate = new List<Task>();
    for(Task t : taskList){
        if(t.status != 'Completed'){
            t.status = 'Completed';
        }
         taskToUpdate.add(t);
         system.debug('taskToUpdate = '+taskToUpdate);
    }
    if(taskToUpdate.size()>0){
    update taskToUpdate;
    }
}
List<String> newMultiSelectList = new List<String>();

newMultiSelectList.add('Pro-Life'); newMultiSelectList.add('Establishment'); newMultiSelectList.add('GOP');

string value = '('' + String.join(newMultiSelectList, '','')+'')';

// I need results that includes all the three values (AND Condition)

//I tried this, but it is taking as OR condition

String queryString = 'select id, Audience_Tags__c FROM Audience__c WHERE Audience_Tags__c INCLUDES'+value;
List<Audience__c> newlist = DataBase.query(queryString); system.debug('List of records: '+newlist);

Any help would be appreciated
I have a custom object for an "Application" and each application has an evaluator (Lookup to user table). I want all files uploaded to be owned by the evaluator since other users might upload files but it's annoying that the actual evaluator can't delete them unless they have "Modify All Data" permissions. They also don't automatically attach to AdobeSign agreements because they are not owned by the senter. I wrote this trigger and it seems to work but when you try to upload the file, it gives you an error message in Salesforce, despite the log having no indication of an error. If  I change the trigger to "after insert" instead of "before insert" the file uploads successfully but the owner doesn't change. 
 
trigger CDL_OwnershipUpdate2021 on ContentDocumentLink (before insert) {

    for(ContentDocumentLink CDL: trigger.New)
    { 
        string parentId = CDL.LinkedEntityId;
        string newOwner = null;
        string docId = CDL.ContentDocumentId;
        
        List<Application__c> Apps = new List<Application__c>();
        
        Apps = [select Id, Evaluator__c from Application__c where Id = :parentId];
        
        if(Apps != null && Apps.size() > 0){
            
            System.debug('Checkpoint 1');
            
            for(Application__c app: Apps)
            {
                newOwner = app.Evaluator__c;
            }
        }
        
        ContentDocument doc = [select Id, OwnerId from ContentDocument where Id = :docId];
        
        if(newOwner != null){
            
            System.debug('Checkpoint 2');
            
            doc.OwnerId = newOwner;
            
            update doc;
        }   
    }
}

 
I'm using the following code:


global class SendNotificationBatch implements Database.Batchable<sObject>, Schedulable, Database.Stateful { //Variable Section global FINAL String strQuery; global List<String> errorMessages = new List<String>(); global SendNotificationBatch() { this.strQuery = getBatchQuery(); } //Returns the Query String to Batch constructor to fetch right records. private String getBatchQuery() { String strQuery = 'SELECT Id, CloseDate, Owner.Email FROM Opportunity WHERE CloseDate < TODAY'; return strQuery; } //Batch Start method global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator(strQuery); } //Batch Execute method calls findCostForWoD method global void execute(Database.BatchableContext BC, List<sObject> scopeList) { System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size()); List<Opportunity> oppList = (List<Opportunity>) scopeList; if(!oppList.isEmpty()) { List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>(); for (Opportunity prod : oppList) { Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {prod.Owner.Email}; Message.setToAddresses(toAddresses); Message.SaveAsActivity = false; mailList.add(Message); } if(!mailList.isEmpty()) { try{ Messaging.sendEmail(mailList); } catch (Exception ex) { errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString()); } } } } //Batch Finish method for after execution of batch work global void finish(Database.BatchableContext BC) { AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()]; // Send an email to the Apex job's submitter notifying of job completion. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {aaj.CreatedBy.Email}; mail.setToAddresses(toAddresses); mail.setSubject('JOB Salesforce Send Notification Batch: ' + aaj.Status); String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n'; bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n'; bodyText += 'Error Message' + String.join(errorMessages, '\n'); mail.setPlainTextBody(bodyText); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } //Method which schedules the ProductDownloadBatch global void execute(SchedulableContext sc) { SendNotificationBatch snInstance = new SendNotificationBatch(); ID batchprocessid = Database.executeBatch(snInstance); } }

but I get this error when executing:

Error MessageUnable to send email to Tech: Class.SendNotificationBatch.execute: line 41, column 1

I'm assuming it has to do with opportunity products, when I just want to look at the CloseDate field on the Opportunity object. Any ideas on what to change?  Thanks!
Hello, I have a requirement where i would like to create a Table like structure in salesoforce  as below with fixed row attibute and coulmn attribute. I looked for lightning data table but it has only columns attributes. not row attribute. How to implement the same in lwc

for.e.g 

User-added image
Hello I am writing a trigger on contact object where if I select account lookup field than account s country also get populated in contact object.
code is working fine just need to optimised it .

 
public class UpdateContactRecordsFromAccount {

   
    public void beforeInsert(List<Contact > neWValues)
    {
       Set<ID> id_po = new Set<ID>();
      for(Contact po : newValues){
            id_po.add(po.AccountId);
        }
       
     List<Account> AccountList = [select id , Country__c  from Account where Id in : id_po];
     for(Contact con : neWValues){  
          for(Account  acc : AccountList)
          {
           con.Country__c = acc.Country__c;
            
          }
       }
    }
}

Please help 
Is there a way to set the ownerId = Content version> email> Case>Last Modified By?

I want to set the owner of the file to whoever has been working the case. These files are created via email-to-case. Please help with actual suggestions, not links. I have been reading blogs for days and nothing has worked. I'm at wits end on how to allow my users to delete Files on emails.

trigger ConDoc on ContentVersion (after insert) {

    List<ContentVersion> conver = [SELECT Id, Title, OwnerId FROM ContentVersion WHERE Id IN: Trigger.newMap.keySet()];

    for (ContentVersion CV: conver){
        CV.OwnerId= '3D00GF0000007fwJR';
        CV.Title = 'HannaTest';
    }

    update conver;

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