• Ajay K Dubedi
  • ALL STAR
  • 5937 Points
  • Member since 2015
  • Ajay Dubedi


  • Chatter
    Feed
  • 189
    Best Answers
  • 0
    Likes Received
  • 7
    Likes Given
  • 1
    Questions
  • 1533
    Replies
Hi All,

Following is the code for creating multiple child records.

This code is invoked using process builder and condition to satisfy for firing process builder and creating multiple records is choosing value called "Yes" under a picklist called "Approved" on Parent Object which is "Opportunity Contract".

In sandbox this Code is working fine with all custom profiles, when i give them modify all permission for both the custom objects.

In production this code is working for systems administrator alone and not working for other profiles even with modify all permission and i getting following error and not able to save the record for creating multiple child records.

Attempt to de-reference a null object

Here is the code, any suggestions are highly appriciated

public class OppConAMInvocableClass {
    @InvocableMethod(label='Insert Child Records for Opportunity Contracts' description='Inserts the child records based on number of contract years.')
  public static void insertChildRecords(List<Opportunity_Contract__c> parentList) {
      List<Annual_Maintenance__c> childrecords = new List<Annual_Maintenance__c>();        
      for(Opportunity_Contract__c parent : parentList) {
        Integer numberYears = Integer.valueOf(parent.Contract_Years__c);
        for(Integer i=1;i<numberYears;i++) {
        //Account acct = [SELECT Id FROM Account where Id = :e.WhatId];
        Integer j = i + 1;          
        Annual_Maintenance__c child = new Annual_Maintenance__c();
            
          
            Child.Anniversary_Date__c=Parent.Annual_Renewal_Date__c.addYears(i);  
            Child.Name=Parent.Name+'-'+Child.Anniversary_Date__c.year();
            Child.Number_of_sites__c=Parent.Number_of_Sites__c;
            Child.Opportunity_Department__c =Parent.Opportunity_Department__c;
            Child.Account__c=Parent.Account_Name__c;
            Child.Primary_Contact__c=Parent.Primary_Contact__c;
            Child.Annual_Maintenance_Start_Date__c=Parent.Contract_Start_Date__c;
            Child.Annual_Maintenance_End_Date__c=Parent.Contract_End_Date__c;
            Child.Opportunity_Name__c=Parent.Opportunity_Name__c;
            
            //rama
            Child.Anniversary_Date__c=Parent.Annual_Renewal_Date__c;
            Child.Sales_Territory__c=Parent.Sales_Territory__c;
            Child.Annual_Maintenance_Amount__c=Parent.SMS_Maintenance_Amount__c;
        child.Opportunity_Contract__c=parent.Id;
        childrecords.add(child);
        }
      }    
    Database.SaveResult[] results = Database.insert(childrecords);
    /*
    List<ID> itemIds = new List<ID>();
    for (Database.SaveResult result : results) {
      if (result.isSuccess()) {
        itemIds.add(result.getId());
      }
    }
    return itemIds;
    */
  }
}
Hi guy ,
this is my practice class and test class.I don't understand why my test class can not pass. Can someone help me? please...
public with sharing class ContactExtension {

    public Contact cont{get;set;}
    public String Phone{get;set;}
    
    public ContactExtension(ApexPages.StandardController controller){    
    
        Id ContactId = ApexPages.currentPage().getParameters().get('Id');
        this.cont = (Contact)controller.getrecord(); 
        Contact cont = new Contact();
    }   
    public PageReference save(){              
       
        PageReference pagereference;      
        if(cont.Phone != null){     
			Phone = cont.phone;            
            cont.Phone = '886'+cont.Phone;    
            cont.MobilePhone = '886'+ Phone;       
            insert cont; 
            pagereference = new PageReference('/'+cont.id);
        }      
        return pagereference;  
    }
	     
}
 
@isTest
public class testContactExtension {

     static testMethod void testm1(){
    
         test.startTest();         
         
         Contact  tcontact  = new Contact(LastName='TEST',Phone='0973768421',Email='Test@jzn.com.tw',JOB_STATUS__c ='在職');   
         insert tcontact; 
         
         PageReference pageRef=new PageReference ('/apex/PageTryInput');
         test.setCurrentPage(pageRef);
         pageRef.getParameters().put('Id',String.valueOf(tcontact.Id));
         ApexPages.StandardController thecontroller;
         ContactExtension cls = new ContactExtension(thecontroller);   
        
         cls.Phone ='00000';
         cls.cont = new Contact();
         cls.cont.Phone = '0000000';
         cls.cont.MobilePhone = cls.Phone + cls.cont.Phone;
         cls.save(); 

         
         test.stopTest();
     }
    
}

 
for example 
Price__c * Qyt__c = Total_Price__c (Total price is formula field)
Total_Price__c * Disscount_per__c = Disscount__c (Disscount Is also formula field)
Disscount__c + Total_Price__c = Amount (Amount is  also formula field)


how to cover this filed in test class
Apex Class-


public class CS_AcceptOldestCaseController {
    public String filterId {get; set;}
    public Boolean hasErrors {get; set;}
    public Case oldestCase {get; set;}
    
    // Constructor to accept oldest case
    public CS_AcceptOldestCaseController(ApexPages.StandardSetController cont){
        try {
            // get the 15 digit filter id for return information
            filterId = String.valueOf(cont.getFilterId()).substring(0, 15);
            
            // get all record ids in the list view
            List<Id> caseIds = new List<Id>();
            for(Case c : (List<Case>) cont.getRecords()){
                caseIds.add(c.Id);
            }
            while(cont.getHasNext()){
                for(Case c : (List<Case>) cont.getRecords()){
                    caseIds.add(c.Id);
                }
                cont.next();
            }
            
            // get all records in the list that have a owner of type Queue sorted by last modified date, then assign the first one to treat
            System.Debug('caseIds:' + caseIds);
            List<Case> cases = [select Id, OwnerId, CaseNumber from Case where Id=: caseIds and Owner.Type = 'Queue' order by CreatedDate ASC];
            if (cases.size() > 0){
                oldestCase = cases[0];
            } else {
                oldestCase = null;
            }
            
            hasErrors = false;
         } catch (Exception ex){
            hasErrors = true;
            ApexPages.addMessages(ex);
        }
        
    }
    
    // accept the case
    public PageReference acceptCase(){
        try {
            String successMsg = 'No queue cases found';
            if (oldestCase != null){
                oldestCase.OwnerId = UserInfo.getUserId();
                update oldestCase;
                
                successMsg = 'Case ' + oldestCase.CaseNumber + ' accepted';
            } else  {
                hasErrors = true;
            }
            
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.CONFIRM,successMsg);
            ApexPages.addMessage(myMsg);
            
        } catch (Exception ex){
            hasErrors = true;
            ApexPages.addMessages(ex);
        }
        
        return null;
    }

}


Test Class-

@isTest
public class CS_AcceptOldestCaseControllerTest {
    
     public testmethod static void testAcceptOldestCaseController()  {
         List<Case> cases=new  List<Case>();        
          Group g = new Group(Name='TestQueue',Type='Queue');
          System.runas(new User(Id=UserInfo.getUserId())) {
              insert g;
              insert new QueueSobject(QueueId=g.id, SObjectType='Case');
          }
         
         
           Case c = new Case(Subject='test', Client_ID__c = 'test', Contact_Email__c ='test@test.com');
          insert c;
        Case c1 = new Case(Subject='test', Client_ID__c = 'test', Contact_Email__c ='test@test.com');
          insert c1;
         case c3=new case();
         c3.Subject='test';
         c3.Client_ID__c='text';
         c3.Contact_Email__c='test@test.com';
         c3.OwnerId=g.Id;
        insert c3;
         cases.add(c3);
         cases.add(c);
         cases.add(c1);
        
         List<Id> caseIds = new List<Id>();
         caseIds.add(c.Id); 
          caseIds.add(c1.Id);
          caseIds.add(c3.Id);
         
        Test.startTest();
        Boolean hasErrors=true;
        PageReference pageRef = Page.CS_AcceptOldestCase;
        Test.setCurrentPage(pageRef);
        
        ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(cases);  
        ssc.getHasNext();
        ssc.getHasPrevious();
        ssc.getPageNumber();
        CS_AcceptOldestCaseController con = new CS_AcceptOldestCaseController(ssc);         
        con.AcceptCase();        
        Test.stopTest();
    }
    public testmethod static void testAcceptOldestCaseController1()  {
         List<Case> cases=new  List<Case>();        
           Case c = new Case(Subject='test', Client_ID__c = 'test', Contact_Email__c ='test@test.com');
          insert c;
        Case c1 = new Case(Subject='test', Client_ID__c = 'test', Contact_Email__c ='test@test.com');
          insert c1;         
         cases.add(c);         
         List<Id> caseIds = new List<Id>();
         caseIds.add(c.Id); 
         
        Test.startTest();
        Boolean hasErrors=true;
        PageReference pageRef = Page.CS_AcceptOldestCase;
        Test.setCurrentPage(pageRef);
        
        ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(cases);  
         ssc.getHasNext();
         ssc.next();
        CS_AcceptOldestCaseController con = new CS_AcceptOldestCaseController(ssc);         
        con.AcceptCase();        
        Test.stopTest();
    }   
}

I have covered all part except
 while(cont.getHasNext()){
                for(Case c : (List<Case>) cont.getRecords()){
                    caseIds.add(c.Id);
                }
                cont.next();
            }
and cath part
Global class OldCaseDeleter implements Database.Batchable<SObject> {
    Public List<SObject> allRecords;
   Global Database.QueryLocator start(Database.BatchableContext BC) {
       String query = 'SELECT Id FROM Case WHERE CreatedDate = today and Exempt_From_Deletion__c = false';
       System.debug('query -> ' + query);
       return Database.getQueryLocator(query);
   }
   Global void execute(Database.BatchableContext BC, List<SObject> records) {
       List<Case> caseList = (List<Case>)records;
       Set<Id> caseID = new Set<Id>();
       for(Case c: caseList) {
           caseId.add(c.Id);
       }
       List<ContentDocumentLink> files = [SELECT ContentDocumentId, LinkedEntityId
                                          From ContentDocumentLink
                                          WHERE LinkedEntityId IN :caseId];
       Set<Id> conId = new Set<Id>();
       for(ContentDocumentLink cd : files) {
           conId.add(cd.ContentDocumentId);
       }
       List<ContentDocument> files1 = [SELECT Id, Title
                               FROM ContentDocument
                               WHERE Id IN : conId];
           allRecords = new List<SObject>();
        allrecords.addAll((List<SObject>)files1);
        allrecords.addAll((List<Case>)caseList);
        Delete allrecords;
   }
   Global void finish(Database.BatchableContext BC) {
   }
}

How can I get all Objects except the System Objects in SF?

Here's my code. But I need to revise it to get only the needed Objects.

@AuraEnabled
	public static List<SelectOption> fetchAllObjects(){
        Set<String> listObjs = new Set<String>();
        for(MyCustomSettings__c cs : [Select Id, Objects__c From MyCustomSettings__c]){
            listObjs.add(cs.Objects__c);
        }

		List<SelectOption> objList = new List<SelectOption>();
        Set<String> csObjNames = new Set<String>();
        Map<String, String> mapName = new Map<String, String>();
        Map<String, String> mapLabel = new Map<String, String>();
		for(Schema.SObjectType objTyp : Schema.getGlobalDescribe().Values()){
            System.debug(objTyp.getDescribe().getLabel());

            if ( objTyp.getDescribe().isCreateable()) {
                csObjNames.add(objTyp.getDescribe().getLabel());
                    mapName.put(objTyp.getDescribe().getLabel(), objTyp.getDescribe().getName());
                    mapLabel.put(objTyp.getDescribe().getName(), objTyp.getDescribe().getLabel());
            }
		}

        List<String> objNamesCast = new List<String>();
        objNamesCast.addAll(csObjNames);
        objNamesCast.sort();

        for(String s : objNamesCast){
            String objTypeName = mapName.get(s);
            String objTypeLabel = mapLabel.get(objTypeName);
            if(!listObjs.contains(objTypeName)) objList.add(new SelectOption(objTypeName,objTypeLabel));
            else objList.add(new SelectOption(objTypeName,objTypeLabel, true));
        }

		return objList;   
	}
How can we display thousands of records on the VF page without using the StandardSetController or Pagination?
Hi - I am hoping there is someone with a little time on their hands that can and is willing to help me. We only have one developer that sort of kind of knows SFDC. However, 110% of his time is tied up in a huge enterprise project. We have the below trigger that I need a test class for. 

Thank you in advance if you can help. I understand if no one can

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
trigger CheckboxIfFile on ContentDocumentLink (after insert) {
    
  Schema.DescribeSObjectResult  r = Case.sObjectType.getDescribe();
    String keyPrefix = r.getKeyPrefix();
    
    if(trigger.isInsert){
        for(ContentDocumentLink att : trigger.New){
            
            if(keyPrefix == String.valueOf(att.LinkedEntityId).left(3)){
                
                ContentDocument doc = [SELECT Id, Title from ContentDocument WHERE Id = :att.ContentDocumentId];
                
                if (doc.Title.containsIgnoreCase('screen')) {
                    
                    Case con =  [SELECT Id, Screen_Shots_Attached__c from Case WHERE Id = :att.LinkedEntityId LIMIT 1];
                    con.Screen_Shots_Attached__c  = True;
                    update con;
                }
            }
        }
    }
}
Hello Wonderful people.!
I am new to APEX development, currently facing problem in fetching the relevant data from the table. Any help in this regard is highly appreciated.

Below are my variables and objects:
Object : myDataTable__c
Fields : 
data1__c --> Lookup to DataTable1__c object
data2__c --> Lookup to DataTable2__c object

myDataTable__c contains different entries with relevant values containing  data1__c & data2__c.

I have called a method from the helper class, the apex method looks as below:
public static Boolean unAssignCandidate(ID pass1, ID pass2) {
List<myDataTable__c> mydt = [SELECT Id,data1__c,data2__c FROM myDataTable__c WHERE data1__c = : pass1 AND data2__c = : pass2 ];

if (mydt.size() > 0 ) {
           delete mydt;
           return True;            
        }else {
            throw new AuraHandledException('Unable to unassign the candidate.');
        }   
}

The query always returns an empty list whenever a WHERE clause is applied. 

I am sure, there is some simple mistake that I am doing, and any help towards this would be a great support..

Thanks in advance for your time!!
 
Hi All,
 i created the batch given below:-
 //Batch to create FBGFamily junction records for Account having same name
public class BatchFBGFamilies implements Database.Batchable<sObject> {
    //run method to execute batch on one record
    public static void run( Set<Id> AccIds ) {
        List<Account> accountRecords =  [Select id, Name  
                                         From Account
                                         Where Id IN:  AccIds ];
        executeHelper( accountRecords );                  
    }
    //Start method to get All Account which is exetuing batch
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select Id, Name ' +
            'FROM Account';
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext BC, List<Account> accounts){
        executeHelper( accounts );
    }
    
    public void finish(Database.BatchableContext BC){
    }
    
    //method to perform record creation of junction object for Account having same name
    public static void executeHelper( List<Account> accounts ) {
        //set to get Account having duplicate name
        Set<String> duplicateNames = new Set<String>();
        for (Account account : accounts)
        {
            duplicateNames.add(account.Name);
        }
        
        
        //map to get Account name and list of AccountIds having same name
        Map<String, List<Account>> mapDuplicateAccNameToIds = new Map<String, List<Account>>();
        for(Account acc : [SELECT id,name FROM Account  where Name IN: duplicateNames AND ID NOT IN : accounts]) {
            if(mapDuplicateAccNameToIds.containsKey(acc.Name)) {
                List<Account> ListDuplicates = mapDuplicateAccNameToIds.get(acc.Name);
                ListDuplicates.add(acc);
                //System.debug('ListDuplicates'+ListDuplicates);
                mapDuplicateAccNameToIds.put(acc.Name, ListDuplicates);
            } else {
                mapDuplicateAccNameToIds.put(acc.Name, new List<Account> { acc });
            }
        }
        System.debug('mapDuplicateAccNameToIds'+mapDuplicateAccNameToIds);
        Map<String,FBG_Family__c> mapAlreadyexistFamily = new Map<String,FBG_Family__c>();
        for(FBG_Family__c existFamily : [select id, Name, Sister_Company__c, Sister_Company2__c FROM FBG_Family__c ]){
            String key = String.valueOf(existFamily.Sister_Company__c) + String.valueOf(existFamily.Sister_Company2__c);
            mapAlreadyexistFamily.put(key,existFamily);

        }
        //System.debug('Already exit'+mapAlreadyexistFamily);
        
        //creating junction object records
        List<FBG_Family__c> ListFBGFamily = new List<FBG_Family__c>();
        if(mapDuplicateAccNameToIds.Size() > 0){
            for (Account acc : accounts)
            {
                if( mapDuplicateAccNameToIds.containsKey(acc.Name) ){
                    System.debug('account'+accounts);
                    List<Account> DuplicateAccount = mapDuplicateAccNameToIds.get(acc.Name);
                    //System.debug('DuplicateAccount'+DuplicateAccount);
                    If(DuplicateAccount.Size() > 0) {
                        for(Account Acc1 : DuplicateAccount ){
                            FBG_Family__c Family =  new FBG_Family__c();
                            Family.Sister_Company__c =  acc.id;
                            if( acc.Id != Acc1.Id){
                                Family.Sister_Company2__c = Acc1.id;
                                String key = String.valueOf(Family.Sister_Company__c) + String.valueOf(Family.Sister_Company2__c);
                                if(!mapAlreadyexistFamily.containsKey(key)){
                                    ListFBGFamily.add(Family); 

                                }
                            } 
                        }
                    }   
                }
                
                system.debug('ListFBGFamily'+ListFBGFamily);
                
            }
        }
        if( ListFBGFamily.Size() > 0 ){
            FBGFamilyTriggerHelper.runTrigger = FALSE;
            Insert ListFBGFamily;
        }
    }
}
i created the test class for it but its not giving me the coverage.
my test  class is given below:-
@istest
public class BatchFBGFamiliesTest {
    Static testmethod void creatingFamilyRecordTest(){
        
        Account acc = new Account();
        acc.Name = 'Test18';
        insert acc;
        Account acc1 = new Account();
        acc1.Name = 'Test18';
        insert acc1;
        Account acc2 = new Account();
        acc2.Name = 'Test18';
        insert acc2;
        test.startTest();
        BatchFBGFamilies obj = new BatchFBGFamilies();
        database.executeBatch(obj);
        test.stopTest();
        List<FBG_Family__c> ListFamily = [SELECT id, Name
                                          FROM FBG_Family__c
                                         ];
        List<FBG_Family__c> ListFamilyHavingFirstAccount = [SELECT id, Name
                                                            FROM FBG_Family__c
                                                            WHERE Sister_Company__c =: acc.id 
                                                            OR Sister_Company2__c =: acc.id
                                                           ];
        List<FBG_Family__c> ListFamilyHavingSecondAccount = [SELECT id, Name
                                                             FROM FBG_Family__c
                                                             WHERE Sister_Company__c =: acc1.id 
                                                             OR Sister_Company2__c =: acc1.id
                                                            ];
        List<FBG_Family__c> ListFamilyHavingThirdAccount = [SELECT id, Name
                                                            FROM FBG_Family__c
                                                            WHERE Sister_Company__c =: acc2.id 
                                                            OR Sister_Company2__c =: acc2.id
                                                           ];
        List<FBG_Family__c> ListFamilyFirstAccountAsCompany1 = [SELECT id, Name
                                                                FROM FBG_Family__c
                                                                WHERE Sister_Company__c =: acc.id 
                                                               ];
        System.assertEquals(6, ListFamily.Size());
        System.assertEquals(4, ListFamilyHavingFirstAccount.Size());
        System.assertEquals(4, ListFamilyHavingSecondAccount.Size());
        System.assertEquals(4, ListFamilyHavingThirdAccount.Size());
        System.assertEquals(2, ListFamilyFirstAccountAsCompany1.Size());
        
        
    }
    static testmethod void RunMethodTest(){
        Account acc = new Account();
        acc.Name = 'Test18';
        insert acc;
        BatchFBGFamilies.run( new Set<Id>{ acc.Id });
    }
} how to cover the remaining part?bold lines are not covering
Any suggestions?
Hi All,
     i have requirement in which i have a juction object called family__c. i have two lookup Sister_Company__c and Sister_Company2__c. i am creating a batch in which i want to create records of Accounts having duplicate names.and both duplicates will go in Sister_Company__c and Sister_Company2__c lookup fields.
     example like Account 'ABC' with record type 'A'. and have 2 more account with same name as 'ABC' having record type 'B',and record type 'C'. than junction object records should created and the fill the fields like:-    Sister_Company__c = 'ABC(A)' and  Sister_Company2__c = 'ABC(B)'. and  2nd record as:-Sister_Company__c = 'ABC(A)' and  Sister_Company2__c = 'ABC(c)' creating two junction records like this for ABC(A).
 i created a batch for it but its giving me null pointer exeption.
 how to solve it?
 my batch is given below:-
 //Batch to create FBGFamily junction records for Account having same name
public class BatchFBGFamilies implements Database.Batchable<sObject> {
    //run method to execute batch on one record
    public static void run( Set<Id> AccIds ) {
        List<Account> accountRecords =  [Select id, Name  
                                         From Account
                                         Where Id IN:  AccIds ];
        executeHelper( accountRecords );                  
    }
    //Start method to get All Account which is exetuing batch
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select Id, Name ' +
            'FROM Account';
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext BC, List<Account> accounts){
        executeHelper( accounts );
    }
    
    public void finish(Database.BatchableContext BC){
    }
    
    //method to perform record creation of junction object for Account having same name
    public static void executeHelper( List<Account> accounts ) {
        //set to get Account having duplicate name
        Set<String> duplicateNames = new Set<String>();
        for (Account account : accounts)
        {
            duplicateNames.add(account.Name);
        }
        
        //map to get Account name and list of AccountIds having same name
        Map<String, List<Account>> mapDuplicateAccNameToIds = new Map<String, List<Account>>();
        for(Account acc : [SELECT id,name FROM Account  where Name IN: duplicateNames AND Id NOT IN : accounts]) {
            if(mapDuplicateAccNameToIds.containsKey(acc.Name)) {
                List<Account> ListDuplicates = mapDuplicateAccNameToIds.get(acc.Name);
                ListDuplicates.add(acc);
                mapDuplicateAccNameToIds.put(acc.Name, ListDuplicates);
            } else {
                mapDuplicateAccNameToIds.put(acc.Name, new List<Account> { acc });
            }
        }
        Map<String,FBG_Family__c> mapAlreadyexistFamily = new Map<String,FBG_Family__c>();
        for(FBG_Family__c existFamily : [select id, Name, Sister_Company__c, Sister_Company2__c FROM FBG_Family__c ]){
            String key = String.valueOf(existFamily.Sister_Company__c) + String.valueOf(existFamily.Sister_Company2__c);
            mapAlreadyexistFamily.put(key,existFamily);
        }
        //System.debug('Already exit'+mapAlreadyexistFamily);
        
        //creating junction object records
        List<FBG_Family__c> ListFBGFamily = new List<FBG_Family__c>();
        for (Account acc : accounts)
        {
            List<Account> DuplicateAccount = mapDuplicateAccNameToIds.get(acc.Name);
            System.debug('DuplicateAccount'+DuplicateAccount);
            If(DuplicateAccount.Size()>0) {
                for(Account Acc1 : DuplicateAccount ){

                    FBG_Family__c Family =  new FBG_Family__c();
                    Family.Sister_Company__c =  acc.id;
                    if( acc.Id != Acc1.Id){
                        Family.Sister_Company2__c = Acc1.id;
                        String key = String.valueOf(Family.Sister_Company__c) + String.valueOf(Family.Sister_Company2__c);
                        if(!mapAlreadyexistFamily.containsKey(key)){
                            ListFBGFamily.add(Family); 
                        }
                     } 
                }
            }
        }
        if( ListFBGFamily.Size() > 0 ){
            FBGFamilyTriggerHelper.runTrigger = FALSE;
            Insert ListFBGFamily;
        }
    }
}
 what i am missing? Any suggestions?
 
public class EmailInvoiceA {
    
    @auraEnabled
    public static void sendMailWithPDF(String recordId){
        for(Invoice__c cc : [select Id,Distributor__r.E_mail__c,Distributor__r.CC_to_if_any__c,Distributor__r.Name from Invoice__c WHERE Id =: recordId]){
            list<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();  
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.PdfEmailInvoice;
            pref.getParameters().put('Id',recordId);
            pref.setRedirect(true);
            Blob b;
            b = pref.getContent();
            attach.setFileName('Invoice.pdf');
            attach.setBody(b);
            semail.setSubject('Invoice details');
            semail.setReplyTo('noreply@gmail.com');
            semail.setSenderDisplayName('salesforce User');
           sendTo.add(cc.Distributor__r.E_mail__c);
            
            List<String> send = new List<String>();
            if(cc.Distributor__r.E_mail__c==null && cc.Distributor__r.CC_to_if_any__c != null)
            {  
                send.add(cc.Distributor__r.CC_to_if_any__c);
               semail.setToAddresses(send);
            }
            else if(cc.Distributor__r.E_mail__c !=null && cc.Distributor__r.CC_to_if_any__c != null)
            {
                sendTo.add(cc.Distributor__r.E_mail__c);
                send.add(cc.Distributor__r.CC_to_if_any__c);
              semail.setccAddresses(send);
              semail.setToAddresses(sendTo);
                
           }
           else if(cc.Distributor__r.E_mail__c !=null && cc.Distributor__r.CC_to_if_any__c == null)
            {  
              sendTo.add(cc.Distributor__r.E_mail__c);
                   semail.setToAddresses(sendTo);
         }
                mails.add(semail);
            String emailBody =' <html><body><p> Dear '+ cc.Distributor__r.Name+' ,<br><br> Please find the attached Invoice details. <br><br>    Regards, <br> IT Team <br>  Sayaji Groups.</p></body></html>';
            semail.setHtmlBody(emailBody);
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
        }
    }      
    @auraEnabled
     public static void sendMailWith(String recordId,String mMail){
        for(Invoice__c cc : [select Id,Distributor__r.E_mail__c,Distributor__r.CC_to_if_any__c,Distributor__r.Name from Invoice__c WHERE Id =: recordId]){
            list<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();  
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();
            sendTo.add(mMail);
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.PdfEmailInvoice;
            pref.getParameters().put('Id',recordId);
            pref.setRedirect(true);
            Blob b;
            b = pref.getContent();
            attach.setFileName('Invoice.pdf');
            attach.setBody(b);
            semail.setSubject('Invoice details');
            semail.setReplyTo('noreply@gmail.com');
            semail.setSenderDisplayName('salesforce User');
           
           
              List<String> send = new List<String>();
            if(cc.Distributor__r.CC_to_if_any__c != null)
            {
                 send.add(cc.Distributor__r.CC_to_if_any__c);
                 
            }
            mails.add(semail);
			semail.setCcAddresses(send);
            semail.setToAddresses(sendTo);
            String emailBody =' <html><body><p> Dear '+ cc.Distributor__r.Name+' ,<br><br> Please find the attached Invoice details. <br><br>    Regards, <br> IT Team <br>  Sayaji Groups.</p></body></html>';
            semail.setHtmlBody(emailBody);
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
        }
    }    
     @auraEnabled
   public static void Mail(String recordId,String mMail,boolean checkCmp){
        for(Invoice__c cc : [select Id,Distributor__r.E_mail__c,Distributor__r.CC_to_if_any__c,Distributor__r.Name from Invoice__c WHERE Id =: recordId]){
            list<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();  
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>();        
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.PdfEmailInvoice;
            pref.getParameters().put('Id',recordId);
            pref.setRedirect(true);
            Blob b;
            b = pref.getContent();
            attach.setFileName('Invoice.pdf');
            attach.setBody(b);
            semail.setSubject('Invoice details');
            semail.setReplyTo('noreply@gmail.com');
            semail.setSenderDisplayName('salesforce User');
  
           if(checkCmp==true)
               {
                  sendTo.add(mMail);
                   semail.setToAddresses(sendTo);
               }
           else  if(checkCmp==false)
            {
              if(mMail != null)
            {
                sendTo.add(mMail);
            	semail.setToAddresses(sendTo);
            }   
             if(cc.Distributor__r.E_mail__c != null)
            {
               sendTo.add(cc.Distributor__r.E_mail__c);  
                semail.setToAddresses(sendTo);
            } 
                
             if(cc.Distributor__r.CC_to_if_any__c != null)
            { 
                List<String> send = new List<String>();//cc string
				send.add(cc.Distributor__r.CC_to_if_any__c);  
               semail.setCcAddresses(send);
           }   
            }
            mails.add(semail);

            String emailBody =' <html><body><p> Dear '+ cc.Distributor__r.Name+' ,<br><br> Please find the attached Invoice details. <br><br>    Regards, <br> IT Team <br>  Sayaji Groups.</p></body></html>';
            semail.setHtmlBody(emailBody);
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
        }
    }       
}

 
Hi Experts 

Can we create a salesforce bell notification for approval process using Apex Trigger,Apex class , Lightning Component  I searched on google also its says By Using Process builder we create a salesforce custom notification but i want to send notification when user clicked on the submit for approval button i am and in approval process My Users in queues so salesforce not sent bell notification to Queue Users so how to send bell notificatio Queue Users If any one doing this type of scenario so please share with me Any Example 


Thanks in Advance
Neeraj Sharma
Hi. I created a component which when dropped onto the opportunity screen, it is supposed to show a summary of the total value of all the added products. I checked the logs and the relevant data is sent back from the server but for some reason it is not showing on my table. If you can please take a look at my code and advise me on what is wrong, I'd highly appreciate it.Here it is:

COMPONENT

<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="OppProductsTotalValueController">
    <aura:attribute name="oppProducts" type="OpportunityLineItem[]"/>
    <aura:attribute name="displayText" type="String" default="" description="for displaying a message when the opportunity has no products added"/>
    <aura:attribute name="tableColumns" type="List"/>
    <aura:attribute name="headerTitle" type="Aura.Component[]">
        <b>Total Value of Added Products</b>
    </aura:attribute>
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <lightning:card>
        <aura:set attribute="title">{!v.headerTitle}</aura:set>
        <p class="slds-card__body_inner">
            <aura:text value="{! v.displayText }"/>
        </p>
        <lightning:datatable data="{!v.oppProducts}" columns="{!v.tableColumns}" keyField="id" hideCheckboxColumn="true"/>
    </lightning:card>    
    
</aura:component>

CONTROLLER

({
    doInit: function(component, event, helper) {  
         
        //Get opportunity products
        var action = component.get("c.getOppProducts");
        action.setParams({"oppId": component.get("v.recordId")});
        
        // Pass the data to my attribute and create table
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){                                
                if(response.getReturnValue().length == 0)
                {
                    component.set("v.displayText","This opportunity has no products added to it.");                        
                }
                else
                {   
                    helper.createTable(component); 
                    component.set("v.oppProducts", response.getReturnValue());
                        //For checking the data passed back from the server
                        console.log(JSON.parse(JSON.stringify(component.get("v.oppProducts"))));                                       
                }                
            }
            else{
                console.log('Problem getting Opportunity Products, response state: ' + state);
            }
        });
        $A.enqueueAction(action);
    }
})

HELPER

({
    createTable : function(component) {
        component.set('v.tableColumns', [
    {label:'Product Code', fieldName:'prodCode', type:'text'},
    {label:'Total Value', fieldName:'totalVal', type:'currency'}    
        ]);
    }
})

APEX CLASS

public class OppProductsTotalValueController {
    
    @AuraEnabled
    public static OpportunityLineItem[] getOppProducts(Id oppId)
    {
        // Check to make sure relevant fields are accessible to this user
        String[] fieldsToCheck = new String[] {
            'ProductCode', 'TotalPrice'
        };
        
        Map<String,Schema.SObjectField> fieldDescribeTokens = 
            Schema.SObjectType.OpportunityLineItem.fields.getMap();
        
        for(String field : fieldsToCheck) {
            if( ! fieldDescribeTokens.get(field).getDescribe().isAccessible()) {
                throw new System.NoAccessException();
            }
        }
        
        //Check for any products which have been added    
        OpportunityLineItem[] returnedOppProds;
        
        returnedOppProds = [SELECT ProductCode, TotalPrice FROM OpportunityLineItem WHERE (OpportunityId = :oppId AND TotalPrice > 0)];
                        
        return returnedOppProds;
    }    
}

Thanks in advance!

I am trying to achieve this by using SOQL.

Apex Class

public class soql_example_6 {
  //accountName 
    public String accName  {set;get;}
    // account rating 
    public String accRating  {set;get;}
    // query String 
    public String query    {set;get;}
    public String query2   {set;get;}
    // Result fetched
    public List<Account> accounts   {set;get;}
    public List<Opportunity> opps	{set;get;}
    
    public SOQL_Example_6(){
        accounts = new List<Account>();
        opps 	 = new List<Opportunity>();
    }
    // This search is for Accounts
    public void search(){
        // Default query 
        query='select id ,name,phone,rating,industry from Account';
        // if accName and accRating values are entered 
        // where name='TCS' and Rating ='Hot'
        if(accName!=''&&accRating!=''){
            query =query+' where name=\''+accName+'\' and rating=\''+accRating+'\'';      
        }else{
            // if only name is entered 
            // where name='TCS'
            if(accName!=''){
                query=query+' where name=\''+accName+'\'';
            } else if(accRating!=''){
                // if only rating is entered
                // where rating='Hot'
                query=query+' where rating=\''+accRating+'\'';
            }
        }
        accounts =Database.query(query);
    }

    // This search is for related Opportunities
    public void search2(){
        // Default Opportunity query
        query2='select id,name,Account, Amount, CloseDate, StageName from Opportunity';
        // If Account Name is selected
        // Fetch that Account Name ID to this query
        if(accName!=''){
// --------------
// Getting an error here in the below line.
            query2 = query2+'where ID=:\''+accId+'\' ';
        }
    }

}
VisualForce Page
<apex:page controller="SOQL_Example_6">
    <apex:form >
        <br/><br/>
    	<apex:outputPanel style="width:1000px; height:40px;padding:10px;border:1px solid grey;margin-top:50px;">
            Name : <apex:inputText value="{!accName}" /> 
            &nbsp;&nbsp;&nbsp;
            Rating : <apex:inputText value="{!accRating}" />
            &nbsp;&nbsp;&nbsp;
            <apex:commandButton value="Search" action="{!search}" reRender="fm"/>
        </apex:outputPanel>
        <br/><br/><br/>
        <apex:outputPanel id="fm">
            <apex:pageBlock>
            <apex:pageBlockSection columns="2" rendered="true">
                <apex:outputPanel title="Account Details">
                    <apex:dataTable value="{!accounts}" var="a" rules="rows" width="600" frame="border" cellpadding="10" rendered="{!accounts.size>0}">
                        <apex:column value="{!a.name}" headerValue="Name" />
                        <apex:column value="{!a.Phone}" headerValue="Phone" />
                        <apex:column value="{!a.Industry}" headerValue="Industry" />
                        <apex:column value="{!a.Rating}" headerValue="Rating" />
                    </apex:dataTable>
                </apex:outputPanel>
                
                 <apex:outputPanel title="Opportunity Details">
                    <apex:dataTable value="{!opps}" var="o" rules="rows" width="600" frame="border" cellpadding="10" rendered="{!opps.size>0}">
                        <apex:column value="{!o.name}" headerValue="Name" />
                        <apex:column value="{!o.Amount}" headerValue="Amount" />
                        <apex:column value="{!o.CloseDate}" headerValue="CloseDate" />
                        <apex:column value="{!o.stageName}" headerValue="StageName" />
                    </apex:dataTable>
                </apex:outputPanel>
        	</apex:pageBlockSection>
            </apex:pageBlock>    
		</apex:outputPanel>
    </apex:form>
</apex:page>



Now When I select Name only then its related Opportunities has to pop up in the right output panel window.

Eg:
-- if Name = Company_1 is written then
in the below-left output panel that Account column have to be displayed.
in the right output panel that Account related opportunities have to be displayed.

-- if Name is empty then
in the below-left page block all Accounts have to be displayed.
in the right page block, this output panel must not be displayed.
 
I am getting Error:System.QueryException: List has no rows for assignment to SObject
public String save(String ids){
            Case caseObject = [SELECT Subject, Description, ContactId, Origin, Priority, Status, OwnerId, RecordTypeId, ParentId,  Product_Code__c,Product_Description__c, Lot_Number__c, GMP_Quality__c, Trademark__c, Business_Unit__c,  ProdCert_Topic__c,Rega_Responsibility__c,ProdCert_Request__c,Business_Line_Description__c,Additional_Request_Info__c,Applied_ProdCert_Rule__c,RAAnswer__c FROM Case where Id =: ids];
 
Hi...

I need to navigate from one component (component "A") to another (component "B"), send parameters and request data from apex class.

Everything works except sending parameter to the apex class... here is my code:

Navigating to other component and send parameters:

Component A. controller
...
handleRowAction: function (component, event, helper) {

            
        var evt = $A.get("e.force:navigateToComponent");
        evt.setParams({
            componentDef : "c:CASCSVFile",
            componentAttributes: {
                selectedRow : JSON.stringify(event.getParam('row'))
            }
        });
        evt.fire();
 
       
    }
...

Component B XML
<aura:component controller="CASExportFile" >
 


        <!-- attributes -->
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="selectedRowsCount" type="Integer" default="0"/>
 
	<aura:attribute name="selectedRow" type="String" access="global"/>

...more code
Component B controller
init: function (component, event, helper) {

    var selectedItem = JSON.parse(component.get("v.selectedRow"));

    var action = component.get("c.csvtojson");
    
    	
        action.setParams({
            "selectedItem":  selectedItem
        });

    console.log('3.4>>>'+component.get("v.selectedRow"));
    console.log('3.5>>>'+selectedItem.Id);
    
        	action.setCallback(this, function(response) {
			var state = response.getState();
            

			if (state === "SUCCESS") {
                 
				var storeResponse = response.getReturnValue();


                console.log('3.6>>>'+Object.getOwnPropertyNames(storeResponse[0]));
                
                var headerlist = Object.getOwnPropertyNames(storeResponse[0]);
                
                var headerArray = [];
               
                for (var i in headerlist ) { 
                    
                    headerArray.push({ label: headerlist[i], fieldName: headerlist[i], type: 'text'})
                }
                
                headerArray.push({label: 'View', type: 'button', initialWidth: 135, typeAttributes: { label: 'View Details', name: 'view_details', title: 'Click to View Details'}});
                console.log('3.7>>>'+JSON.stringify(headerArray));

                 
                component.set('v.columns',headerArray);
             	component.set("v.data", storeResponse);
                component.set("v.filteredData", storeResponse);
                
                
                if(storeResponse != null && storeResponse.length > 0){

                    component.set("v.hasRecords", "true");
                }
                
                component.set('v.maxRowSelection', storeResponse.length);

			}
			else if (state === "RUNNING") {
                //@todo start the timer
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("3.>>Error message: " + 
                                 errors[0].message);
                        alert(errors[0].message);
                    }
                } else {
                    console.log("3.>>Unknown error");
                }
            }
         }); 
    
 
		$A.enqueueAction(action);
    },

Lightning Action console
User-added imageBrowser Log Console

User-added image

 
I need a trigger where I have 3 objects account, contact, and city and the city has no relationship with any object. The account has a field called City--c. If city--c and city object name is matched, then the only contact should be created
 
Hello,

I am simply trying to access a few Case fields of a Case that has been created after an Apex trigger. However, I keep getting this error: "Invalid loop variable type expected SObject was Case". I am not sure what the problem is, as other sources online that I have looked at seem to be using the same syntax/declarations that I am using. As a sidenote, I am fairly new to Apex and am still learning as I go. Please bear with me.

Here is my code:

trigger Ticket_Trigger on Case (after insert) {

    List<Id> listId = new List<Id>();
    for(Case c : Trigger.new){
        listId.add(c.Id);
    }
    
    List<Case> caseList = [SELECT Case.Id, Case.Origin, Case.ContactId, Case.AccountId, Case.Status,
                           Case.Priority, Case.Subject, Case.LastModifiedById, Case.OwnerId,
                           Case.CreatedById, Case.CreatedDate, Case.Description 
                           FROM Case 
                           WHERE Case.id IN :setId];
    
    System.debug(caseList);
}
Hi.
I'm stuck on creating a trigger which fires when a status changes on a record on the 'Placement' object (very new to development). Basically I want the trigger to fire and call a HTTP request class when the 'Status' on the Placement object changes from '8 - Offer Accepted' to '9 - Induction Booked'.

How do I start??

Any help is much appreciated! 
Many Thanks,
Natasha 
We need to create a storage location for a userguide(in any format pdf,excel etc) in salesforce and for that we have to give read only permissions to all users and Editable access to admin and selected users.

We have tried these two ways but couldn't find exact solution:

1- We have tried it using by creating a Folder in documents and giving readable access to all users and to give editable access to admin or some selected users we have created a permission set in which under System Permissions we just ticked the Manage public Documents checkbox.So by this all the users which are assigned in the permission set are able to manage all the folders but we want to manage only a particular folder.

2- We have also tried using content libraries.In that we created a library and added the content file in it.Gave permissions of viewing,editing to particular users but in this we are not able to add Chatter Only users so this solutions got breaked,adding to it some more profiles are asked to generate a case to salesforce support to get Salesforce CRM Content User License by this license only they can view or edit content.

Solutions for this is highly appreciable.And if any one can suggest how to modify any of above two ways to get required solution this will be a great help. I have also posted this question on salesforce community and Stack Exchage.

Thanks
Hi, 

Is there any way you can guarantee that a user uploads a file thru a Flow? 

We currently have a screen component which provides the users with a dropdown option to verifiy the response of the customer. With that we also want to upload the signed off document by the customer. 

With the current File Upload component I don't see a direct option to also validate that a file is really uploaded. Working around with Text Collection variables to store the file names and compare it with "null" doesn't seem to work.

Many thanks in advance!
Is there an option to hide the standard Save & New Button for a custom object? I am only looking to hide it for a specific profile for one custom object.
Hi,

I am looking to hide Save & New button from standard salesforce edit page for a custom object. Is there an option to do this for specific object?

Thanks.
Hi All,

Following is the code for creating multiple child records.

This code is invoked using process builder and condition to satisfy for firing process builder and creating multiple records is choosing value called "Yes" under a picklist called "Approved" on Parent Object which is "Opportunity Contract".

In sandbox this Code is working fine with all custom profiles, when i give them modify all permission for both the custom objects.

In production this code is working for systems administrator alone and not working for other profiles even with modify all permission and i getting following error and not able to save the record for creating multiple child records.

Attempt to de-reference a null object

Here is the code, any suggestions are highly appriciated

public class OppConAMInvocableClass {
    @InvocableMethod(label='Insert Child Records for Opportunity Contracts' description='Inserts the child records based on number of contract years.')
  public static void insertChildRecords(List<Opportunity_Contract__c> parentList) {
      List<Annual_Maintenance__c> childrecords = new List<Annual_Maintenance__c>();        
      for(Opportunity_Contract__c parent : parentList) {
        Integer numberYears = Integer.valueOf(parent.Contract_Years__c);
        for(Integer i=1;i<numberYears;i++) {
        //Account acct = [SELECT Id FROM Account where Id = :e.WhatId];
        Integer j = i + 1;          
        Annual_Maintenance__c child = new Annual_Maintenance__c();
            
          
            Child.Anniversary_Date__c=Parent.Annual_Renewal_Date__c.addYears(i);  
            Child.Name=Parent.Name+'-'+Child.Anniversary_Date__c.year();
            Child.Number_of_sites__c=Parent.Number_of_Sites__c;
            Child.Opportunity_Department__c =Parent.Opportunity_Department__c;
            Child.Account__c=Parent.Account_Name__c;
            Child.Primary_Contact__c=Parent.Primary_Contact__c;
            Child.Annual_Maintenance_Start_Date__c=Parent.Contract_Start_Date__c;
            Child.Annual_Maintenance_End_Date__c=Parent.Contract_End_Date__c;
            Child.Opportunity_Name__c=Parent.Opportunity_Name__c;
            
            //rama
            Child.Anniversary_Date__c=Parent.Annual_Renewal_Date__c;
            Child.Sales_Territory__c=Parent.Sales_Territory__c;
            Child.Annual_Maintenance_Amount__c=Parent.SMS_Maintenance_Amount__c;
        child.Opportunity_Contract__c=parent.Id;
        childrecords.add(child);
        }
      }    
    Database.SaveResult[] results = Database.insert(childrecords);
    /*
    List<ID> itemIds = new List<ID>();
    for (Database.SaveResult result : results) {
      if (result.isSuccess()) {
        itemIds.add(result.getId());
      }
    }
    return itemIds;
    */
  }
}
Hi,
I have a schedule class which inserts a chatter post on user birthyday.
There is test class for same which give 100% coverage in sandbox,but while deploying it gives code coverage error with 73% coverage.
Kindly help me with this,
Thanks in advance.
Schedule class:

global class AnniversayBirthydayChatter implements Schedulable{
 

global void execute(SchedulableContext sc) {

 List<user> lstbirthday=[Select id,name,UserRole.name,User_State__c from user where IS_birthday_today__c=true and isactive=true];// query on birthday of users
 
 List<user> lstanniversary=[Select id,name,UserRole.name,User_State__c from user where IS_Anniversary_today__c=true and isactive=true];//query of anniversary of users
     
     list<FeedItem> postlist1= new list<FeedItem>();
     list<FeedItem> postlist2= new list<FeedItem>();
     
       for(User u:lstbirthday){
        FeedItem post = new FeedItem(); // chatter instance creation
        
        post.ParentId = u.id;
        
         post.Body = 'Join together in wishing a very Happy Birthday to '+'-'+u.name +'-'+u.UserRole.name+'-'+u.User_State__c ;
         postlist1.add(post);
           
       }
       if(postlist1.size()>0 && postlist1!=null){
          insert postlist1;
       }
         for(User u:lstanniversary){
            FeedItem post = new FeedItem();// chatter instance creation
            
            post.ParentId = u.id;
            
             post.Body = 'Ashirvad Family wishes you both a very happy anniversary. Wish you both lot of happiness & good health'+'-'+'Mr & Mrs.'+'-'+u.name+'-' +u.UserRole.name+'-'+u.User_State__c ;
             postlist2.add(post);
           
       }
           if(postlist2.size()>0 && postlist2!=null){ //check for list size
              insert postlist2;
           }

}
}

Test class:
 @isTest
   public class Test_AnniversayBirthydayChatter  {
        @isTest static void Chattertestmethod(){
        Test.startTest();
 AnniversayBirthydayChatter abc=new AnniversayBirthydayChatter();
String sch = '0 00 8 * * ?'; //schedule interval time
        system.schedule('AnniversayBirthydayChatter',sch , abc); //system method to schedule apex class
         Test.stopTest();
        }
    }
Requirement: I have 2 objects "Contact" and a custom object "OrderApi__Subscription__c". When the custom object record is inserted/updated, I want to update the certain information present on custom object record on Contact object when a lookup field on custom object = 'ABC'

Below is the trigger I wrote which is not giving me any error, but it is not updating the fields on contact

trigger updateContact on OrderApi__Subscription__c (after insert, after update) {

    Set<String> contactIds = new Set<String>();
    List<Contact> conupdateList = new List<Contact>();
    Integer count = 0;
    
    for(OrderApi__Subscription__c sub: Trigger.new) {
    contactIds.add(sub.OrderApi__Contact__c);
    }
    
    List<Contact> contactList = [Select id, Chapter_Member_Status__c, Chapter_Member_Activated_Date__c, Member_Paid_Through_Date__c, Member_Term_End_Date__c, Member_Term_Start_Date__c from Contact where id IN : contactIds];
    
    List<OrderApi__Subscription__c> subList = [Select id, OrderApi__Status__c , OrderApi__Item__c , OrderApi__Item__r.Name, OrderApi__Activated_Date__c, OrderApi__Paid_Through_Date__c, OrderApi__Current_Term_Start_Date__c, OrderApi__Current_Term_End_Date__c from OrderApi__Subscription__c where id IN: contactIds];
    
    List<Contact> contactList2 = new List<Contact>();
    for(OrderApi__Subscription__c sub: subList) {
    if(sub.OrderApi__Item__r.Name == 'ABC') {
    count++;
    }
    }
    
    for(Contact con:contactList) {
    OrderApi__Subscription__c membership = new OrderApi__Subscription__c();
    con.Chapter_Member_Status__c = membership.OrderApi__Status__c;
    String activatedDate = string.valueof(membership.OrderApi__Activated_Date__c);
    con.Chapter_Member_Activated_Date__c = activatedDate;
    String paidThroughDate = string.valueof(membership.OrderApi__Paid_Through_Date__c);
    con.Member_Paid_Through_Date__c = paidThroughDate;
    String termEndDate = string.valueof(membership.OrderApi__Current_Term_End_Date__c);
    con.Member_Term_End_Date__c = termEndDate;
    String termStartDate = string.valueof(membership.OrderApi__Current_Term_Start_Date__c);
    con.Member_Term_Start_Date__c = termStartDate;
    contactList2.add(con);
    }
    
    if(count > 0) {
    update contactList2;
    }   
}

 
Can you tell me how I would then make Tab 1-4 SubField1 - SubField 12 and SubField2-1 - 2-2 bold in the following code?

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
 <lightning:tabset selectedTabId="{!v.selTabId}" >
        
        <lightning:tab label="Tab 1" id="1">
            <div class="c-container">
        <lightning:layout >
            <lightning:layoutItem padding="around-small">
                <div class="header-column">
                    <div class="slds-text-heading_medium">
                        <p class="field-title" title="SubField1">SubField1</p>
                    </div>    
                        <p>Data</p>
                </div>
                <br/>
            </lightning:layoutItem>
            <lightning:layoutItem padding="around-small">
                <div class="header-column">
                    <p class="field-title" title="SubField2">SubField2</p>
                    <p>*Other</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField3">SubField3</p>
                    <p>N/A</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField4">SubField4</p>
                    <p>No</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField5">SubField5</p>
                    <p>N/A</p>
                </div>
                
            </lightning:layoutItem>
            <lightning:layoutItem padding="around-small">
                <div class="header-column">
                    <p class="field-title" title="SubField6">SubField6</p>
                    <p>No</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="Gluten-Free">Gluten-Free</p>
                    <p>No</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField7">SubField7</p>
                    <p>Yes</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField8">SubField8</p>
                    <p>No</p>
                </div>
                <br/>
            </lightning:layoutItem>
            <lightning:layoutItem padding="around-small">
                <div class="header-column">
                    <p class="field-title" title="SubField9">SubField9</p>
                    <p>No</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField10">SubField10</p>
                    <p>Aisle 0</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField11">SubField11</p>
                    <p>Yes</p>
                </div>
                <br/>
                <div class="header-column">
                    <p class="field-title" title="SubField12">SubField12</p>
                    <p>No</p>
                </div>
                <br/>
            </lightning:layoutItem>
            <lightning:layoutItem padding="around-small">
                <div class="header-column">
                    <p class="field-title" title="SubField13">SubField13</p>
                    <p>No</p>
                </div>
            </lightning:layoutItem>
        </lightning:layout>
    </div>      
    
        </lightning:tab>
        
        <lightning:tab label="Tab2" id="2">
            <lightning:layout >
            <lightning:layoutItem padding="around-small">
                <div class="slds-panel slds-size_medium slds-panel_docked slds-is-open slds-size--7-of-8" aria-hidden="false">
                    <table class="slds-table slds-table_cell-buffer slds-no-row-hover slds-table_bordered">
                       <thead>
                      <tr class="slds-line-height_reset">
                          <th class="" scope="col">
                            <div class="slds-truncate" title="SubField2-1">SubField2-1</div>
                          </th>
                          <th class="" scope="col">
                            <div class="slds-truncate" title="SubField2-2">SubField2-2</div>
                          </th>
                      </tr>
                       </thead>
                <br/><br/>            
            </table>
            </div>
            </lightning:layoutItem>
            </lightning:layout> 
        </lightning:tab>
        
        <lightning:tab label="Tab3" id="3">
           
        </lightning:tab>
        
        <lightning:tab label="Tab4" id="4">
           
        </lightning:tab>
   
    </lightning:tabset>    
</aura:component>

I tried this for my CSS:

.THIS.slds-text-heading--large 
    {
        font-weight:bold;
    }
.THIS.header-column
    {
        font-weight:bold;
    }
.THIS.slds-truncate
    {
        font-weight:bold;
    }
Hello everbody,

i have to write a trigger that insert a case.  if the email in this case is not in a contact object the trigger create a contact. I tried this:

trigger CaseTrigger on Case (after insert) {        
    for(Case ca:trigger.new){      
            
        Contact[] caseWithEmail = [SELECT Id,Email FROM Contact WHERE Email = :ca.SuppliedEmail];
            
        if(caseWithEmail.isEmpty()){
            
        Contact newContact = new Contact(FirstName = ca.First_Name__c, LastName = ca.Last_Name__c, Phone = ca.SuppliedPhone, Email = ca.SuppliedEmail,
                                        MailingStreet = ca.MailingStreet__c, MailingCity = ca.MailingCity__c, MailingPostalCode = ca.MailingPostalCode__c,
                                        MailingState = ca.MailingState__c);
     insert newContact;
  }
    } 
}

I think a piece is absence but I don't know what it is.
Can somebody help me to find it?

Thank you!

I have PDF File and i want that PDF file to be shown on every record and must be able to edit.

for example: Assume i have custom button related to evrey custom object record when rep clicks on that button it should open that pdf page and user must be able to save and edit the pdf file related to that record how can achieve this in salesforce Lightning.

I am new to custom developing. any help is greatly appreciated.

Thank you!

I have a tab where i save my values in Unsorted column. And when I check checkbox I want to copy value from Unsorted column then sort it and save in Sorted column
User-added image
Hello all

I want to  send an automatic email when lead status is converted to "Qualified" , i tried it in workflow and process, it worked fine, now i want to try it in apex , i have ready made email template named "XXX" which shows as 

Hello {!Lead.LastName} 

Thank you for the registering with us 
Soon we will get back to you 

Team EduProserra

my apex class is

public class emailSending {

    public String Lead { get; set; }
    public string toMail { get; set;}
    public string ccMail { get; set;}
    public string repMail { get; set;}
    
    public void sendMail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        string[] to = new string[] {toMail};
        string[] cc = new string[] {ccMail};
        
        email.setToAddresses(to);
        if(ccMail!=null && ccMail != '')
            email.setCcAddresses(cc);
        if(repmail!=null && repmail!= '')
            email.setInReplyTo(repMail);
        
        email.setSubject('Thank you for the Registration');
        
        email.setHtmlBody('Hello, {!Lead.LastName} <br/><br/>Thank you for Registration. <br/>We will get back to you for more details<br/><br/>Regards<br/> EduPro Team');
        try{
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        }catch(exception e){
            apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
        }
        
        toMail = '';
        ccMail = '';
        repMail = '';
    }
}

how do i design a trigger for this??
Hi guy ,
this is my practice class and test class.I don't understand why my test class can not pass. Can someone help me? please...
public with sharing class ContactExtension {

    public Contact cont{get;set;}
    public String Phone{get;set;}
    
    public ContactExtension(ApexPages.StandardController controller){    
    
        Id ContactId = ApexPages.currentPage().getParameters().get('Id');
        this.cont = (Contact)controller.getrecord(); 
        Contact cont = new Contact();
    }   
    public PageReference save(){              
       
        PageReference pagereference;      
        if(cont.Phone != null){     
			Phone = cont.phone;            
            cont.Phone = '886'+cont.Phone;    
            cont.MobilePhone = '886'+ Phone;       
            insert cont; 
            pagereference = new PageReference('/'+cont.id);
        }      
        return pagereference;  
    }
	     
}
 
@isTest
public class testContactExtension {

     static testMethod void testm1(){
    
         test.startTest();         
         
         Contact  tcontact  = new Contact(LastName='TEST',Phone='0973768421',Email='Test@jzn.com.tw',JOB_STATUS__c ='在職');   
         insert tcontact; 
         
         PageReference pageRef=new PageReference ('/apex/PageTryInput');
         test.setCurrentPage(pageRef);
         pageRef.getParameters().put('Id',String.valueOf(tcontact.Id));
         ApexPages.StandardController thecontroller;
         ContactExtension cls = new ContactExtension(thecontroller);   
        
         cls.Phone ='00000';
         cls.cont = new Contact();
         cls.cont.Phone = '0000000';
         cls.cont.MobilePhone = cls.Phone + cls.cont.Phone;
         cls.save(); 

         
         test.stopTest();
     }
    
}

 
Hi all,

I wrote a fairly simple trigger based on a requirement we have within our company. I am not a code developer, but found a simple example on these forums to modify and it does exactly what I want it to do. However, to bring it to production, I need to create a test class for it and was wondering if you can help me create it. 

This is the trigger I would need a test class for. I would be very grateful if you can help me get the test class created, as we want to move this into production as soon as possible. 
 
trigger DLL_Automation_Task_Trigger on BMCServiceDesk__Task__c (Before update, Before insert) {


     List< BMCServiceDesk__Change_Request__c> lstChangeRequestToUpdate = new List<BMCServiceDesk__Change_Request__c>();
     Map<Id,BMCServiceDesk__Change_Request__c>changeMP;
     for(BMCServiceDesk__Task__c tskobj:trigger.new)
     {
        if((tskobj.BMCServiceDesk__taskType__c=='Automation') && (tskobj.BMCServiceDesk__FKStatus__c=='a2924000000RkGyAAK'))
        {
            lstChangeRequestToUpdate.add(new BMCServiceDesk__Change_Request__c(Id = tskobj.BMCServiceDesk__FKChange__c,
                                                    Automation_Stop__c=true));
        }
     }
     update lstChangeRequestToUpdate;

 
Hi guys,

    I have this trigger on the account and it is not updating at all on contacts. there are no errors either. I tried updating fields on the account and it did not update them on contacts.
 
trigger contactAccountTrigger on Account (after update) {
   Set<Id> accountIds = new Set<Id>();
   List<Contact> contactList1 = new List<Contact>();
    for(Account acc: Trigger.new){
        Account oldAccount = Trigger.oldMap.get(acc.ID);
           If(acc.Contacts.size()>0){
          
                    accountIds.add(acc.id);  

            }
    }//End of Loop

    If(accountIds.size()>0){
         Map<Id,Account> mapAccount = new Map<Id,Account> ([select id,Tier__c,Type, (select id,Account_Tier__c,Account_Type__c from contacts ) from account where id in :accountIds ]);
         List<Contact> contactList = new List<Contact>();
        for(account acc :Trigger.new)
        {
            //Account oldAccount = Trigger.oldMap.get(acc.ID);
      
                 
                If(mapAccount.containsKey(acc.id))
                {
                    Account accObj = mapAccount.get(acc.id);
                    List<Contact> lstCont = accObj.contacts;
                  	for(contact c:lstCont)
                   		  {
                           c.Account_Tier__c=acc.Tier__c;
                           c.Account_Type__c = acc.Type;
                           contactList.add(c);     
                    	  }//end of for loop  
                        System.debug('2nd Loop- Inside');
               		 }         
           
        } //end of Acc1 for loop 
        
          if(contactList.size()>0)
        {
           update contactList1;
        }
            
    }// End of accountIds.size()
      
  }//End of trigger

Thanks in advance!!
I created a trigger that  display an error message if the owner of a opportunity tries to enter the same number in a field that is already on another record. My trigger below is working mostly. The message shows at the field level when there is another opportunity with the same number, but if i create an  opportunity and do not enter a number ( so the field is null/blank). Then go back into the record
and try to add a number it gives me the error message no matter what number I enter into the field. I'm not sure how to get the trigger to allow a user to enter a number in the field after it's been created without getting the error. Any help would be greatly appreciated.
 
trigger TR_RejectDupPriority on Opportunity (before insert, before update) {
    
    //Display error message if another opportunity has the same number in Quting_Priority__c field

 Set<decimal> oppSet = new Set<decimal>();

 for(Opportunity o : trigger.new){

     oppSet.add(o.Quting_Priority__c);
       
}

 //query all existing record for quoteprioritynum__c
 List<Opportunity> oppsList = [SELECT id,Owner.Profile.Name, Owner.Id,
 Quting_Priority__c, LastModifiedBy.Id, quoteprioritynum__c 
      FROM Opportunity 
      WHERE Quting_Priority__c in :oppSet AND 
 Owner.Id = :userinfo.getuserid()];
   
    //ignore system admins
    Profile pr = [select id from Profile where name='System Administrator'];
  
  if(UserInfo.getProfileId()!=pr.id)
for(Opportunity o:trigger.new) 
    
{
    //Check Update for dupe numbers
    if(Trigger.isUpdate && 
    Trigger.oldmap.get(o.id).Quting_Priority__c!=o.Quting_Priority__c
     && o.LastModifiedBy.Id == o.Owner.Id)
       
    {
       o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');
    }

    //Only check for priority size
    if(Trigger.isInsert && o.Quting_Priority__c==o.Quting_Priority__c
         && oppsList.size()>0 && o.LastModifiedBy.Id == o.Owner.Id)
       
    {
       o.Quting_Priority__c.adderror('Another quote has the same priority number, please enter a new number!');

    }
} 

}



 
I want to know where a user is being referenced in salesforce(groups,approval prcoesses,email alerts) how can this be achieved???
Please help me
Hi Experts,

I have below question with me, can you please help me understand the right answer?
 
  1. Universal containers sales team would like to track product shipments for each of its customers. The shipment tracking information is currently available in a back end system, which the company plans to integrate with Salesforce. Which objects are relevant for this integration?
 
a.          Opportunity, Opportunity product, Contract, Custom object Shipment Status.
b.           Lead, Account, Opportunity Product, Custom object –Shipment Status.
c.           Opportunity, Opportunity product, Custom object –Shipment Status.
d.           Lead, Opportunity, Product, Custom object –Shipment Status.

I think C is the right answer, butat someplaces the option A is marked as correct. DO we need Contract?

Hi,

 

I have a task assigned to get the last clicked and how many times it's clicked and clicked by whome for a custom button (Javascript) for any object.

I'm looking to automate different processes in our org. Is there an appexchange  app?  Or can provide some strategies  on how we can automate  repeatable tasks  and/or processes if we know what needs to prefilled in? 
I create a custom object then i  create action link visualforce page for pdf and now i want to create save and email button in visualforce page 
I'd like to describe this case in detail: First , we have created an custom sObject which OWD is Private Second, we have an approval process on this sObject and user created an record and submit for approval Third, his manager reassigned user's request to another person who has no right to view user's record because OWD is private and also has no role hierarchy with this user My question is : Can we add custom logic when manager reassign this approval to another person? So that we can apex sharing this record to person.

Appreciate for any help
HI, anyone take Platform developer certification in 2019?. can you please provide reference links and simple quiz if its available online
Hi Expert,

I am new to the programming world. I have a custom controller which insert a contact created on VF page. Now I am not able to write test class for this. I could only cover 56% code.
 
public class TestPopup {
    
    public list<Account> acc{get;set;} 
    public Account acc1 {get;set;} 
    public Contact contact {get;set;}
    public List<Contact> conlist;
    public Boolean displayPopup {get;set;}
    public String accid {get;set;}
       

    public TestPopup(){
        acc = [select ID, Name, AccountNumber,Type from Account];
	    acc1 = new Account();
        conlist = new List<Contact>();
        contact = new Contact();
        	
    }
   
    public list<Account> getacc(){
        return acc;
    }
    
    public void showPopup()
    { 
    	displayPopup = true;
        acc1 = [SELECT Id, Name, Phone, (SELECT lastName FROM Contacts) FROM Account WHERE Id = :accid];
    }
       
    public void closePopup() {
        displayPopup = false;
        
    }

    public PageReference save(){
        contact.AccountId= acc1.Id;
        insert contact;
        ID contactId = contact.Id;
        PageReference pr = new PageReference('/' + contactId);
   		return pr;
    }  
        
}
 
@isTest
public class TestCustomController {
     static testMethod void testMethod1() 
     {
         Account testAccount = new Account();
         testAccount.Name='Test Account';
         insert testAccount;
         
         Contact cont = new Contact();
         cont.LastName = 'Test';
         cont.FirstName = 'Contact';
         cont.AccountId = testAccount.Id;
          // insert cont;
         
         Account testAccount1 = new Account();
         testAccount1 = [SELECT Id, Name, Phone, (SELECT lastName FROM Contacts) FROM Account WHERE Id = :testAccount.Id];
       
         
         
         Test.StartTest(); 
         PageReference pageRef = Page.All_Account; // Add your VF page Name here
         pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
         Test.setCurrentPage(pageRef);
         
         TestPopup testAccPlan = new TestPopup();  
         testAccPlan.getacc();
        // testAccPlan.showPopup(); 
         testAccPlan.closePopup();
         
         Test.StopTest();
         
     } 
}

 
Hi,

Cannot save the Controller, please help.

https://trailhead.salesforce.com/projects/quickstart-lightning-components/steps/quickstart-lightning-components4
Ok, been directed here by support so hoping someone can help.

Basically noticed that our case milestones were violating outside our set business hours.  After a lot of head scratching the only conclusion was that our timezone on the business hours in use by the entitlement processes were set to GMT.  I have changed this to BST (British Summer Time) to prevent more out of hours violations.

I have asked support if having it set to BST would mean that come Autumn salesforce will automatically revert back an hour in line with daylight savings.  They have said this does not occur and you have to manually change the timezone each time daylight savings occurs.

Can anyone confirm if this is true?  Seems like something so basic that I can't believe its not in the system. 
  • April 21, 2016
  • Like
  • 3

Hi, 

This Monday I tried to do the exam but I had technical issues with camera. Kryterion support tried to help me but we couldn't solve the problem. They rescheduled my exam multiple times but they can not do it to a different day.

Please, I have opened cases and called to certification support phone without getting any answer. Could you help me?

Best regards
I want to send emails in user's language dynamically. Two approaches:
1. Use visualforce email template, create labels and use them in the template. Set language attribute in the template and provide translations for the labels using translation workbench.
2. Create multiple versions of each template, each in a separate language and choose the template dynamically.

Advantage of first approach is that no additional efforts are required if a new language is to be supported but creating so many custom labels is cumbersome. 2nd approach is good in that respect but a template needs to be added everytime a new language is supported. 
Is there any other approach? If not, which one of the above should be chosen?