+ Start a Discussion
Prashant Yadav 90Prashant Yadav 90 
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;
    */
  }
}
Best Answer chosen by Prashant Yadav 90
Ajay K DubediAjay K Dubedi
Hi Prashant,

I have gone through your problem and found out following point:

Try recompiling all your classes after moving all your code to production org. Setup-->Apex classes-->Compile all classes.
This has worked before hoping same for you. For more please refer: https://developer.salesforce.com/forums/?id=9060G0000005Vu1QAE

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi    
Gautam Kasukhela 15Gautam Kasukhela 15 
Hello All,
    Need help in resolving an issue. I am trying to display the Status picklist field on a lightning component. For this I have written a server side controller to fetch the values and set in the component. 
During the callback in the helper, I keep encountering an error where the reposne is ERROR and the message in the ERROR reads "Unable to read sObject". Below is the code: 

Component Code
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
                access="global"
                controller="FetchValuesFromDatabase">

<aura:handler name="init" value="this" action="{!c.doInit}"/>

<aura:attribute name="case" type="Case" default="{'sObjectType': 'case'}"/>
<aura:attribute name="listOfStatusPicklistValues" type="list" default="[]" description="List of Status Picklist values on Case object"/>

<aura:attribute name="statusFieldAPI" type="string" default="status" description="API name of the Status field whose picklist values we want to fetch"/>
<aura:attribute name="originFieldAPI" type="string" default="origin" description="API name of the Origin field whose picklist values we want to fetch"/>

    <!-- CREATE NEW CASE -->
    <div aria-labelledby="newCaseForm">
        <!-- BOXED AREA -->
        <fieldset class="slds-box slds-theme--default slds-container--small">
        <legend id="newCaseForm" class="slds-text-heading--small 
          slds-p-vertical--medium">
          Add Case
        </legend>
  
        <!-- Create New Case Form : START -->
        <form class="slds-form--stacked">          
            <lightning:select aura:id="newCaseForm" label="Status"
                              name="caseStatus"
                              value="{!v.case.Status}"
                              required="true">
                <aura:iteration items="{!v.listOfStatusPicklistValues}" var="status">
                    <option value="{!status}">{!status} </option>
                </aura:iteration>              
                              

            </lightning:select>                  
            <lightning:select aura:id="newCaseForm" label="Case Origin"
                              name="caseOrigin"
                              value="{!v.case.Origin}"
                              required="true"/>                   
            <lightning:textarea aura:id="newCaseForm" label="Description"
                             name="caseDescription"
                             value="{!v.case.Description}"/>
            
    
        </form>
        <!-- Create New Case Form : END -->
      </fieldset>
      <!-- / BOXED AREA -->
    </div>
    <!-- / CREATE NEW CASE -->
</aura:component>
Controller Code:-
({
    doInit : function(component, event, helper) {
        //get the details of the Object and its fields that we want to retrieve. These have been defined
        // as attributes in the component.
        var picklistFieldAPI = component.get("v.statusFieldAPI");
        var objDetails       = component.get("v.case");

        //call the helper to fetch the values of the picklist from database
        helper.fetchPickListValues(component,objDetails,picklistFieldAPI);
        

    }
})

Helper Code
({
    fetchPickListValues : function(component,objDetails,picklistFieldAPI) {
            //invoke the server-side controller to get the picklist values
            var action = component.get("c.getPicklistValues");
            action.setParams({
                'objDetails' : objDetails,
                'picklistFieldAPI' : picklistFieldAPI
            });
        //set callback action
        action.setCallback(this,function(response){
            debugger;
            if(response.getState() == "SUCCESS"){
                //set the response in the component field
               component.set("v.listOfStatusPicklistValues",response.getReturnValue());
            } else if(response.getState() == "ERROR"){
                var errors = response.getError();
                alert(errors);
            }
        });
			$A.enqueueAction(action);
    }
})

Client-Side Controller Code
public class FetchValuesFromDatabase {
   
    @AuraEnabled
    public static List<String> getPicklistValues(SObject objDetails, string picklistFieldAPI){
        List<String> pickListValues = new List<String>();

        //Check if the object type passed from the component is not null. I yes, return empty list
        Schema.sObjectType objType = objDetails.getSObjectType();
        if(objType == null){
               return pickListValues; 
        }

        //Check if the field API names passed from the component are present on the object.
        //If not, return an empty list
        //Get the fields corresponding to the object in a MAP
        Map<String,Schema.SObjectField> objFieldsMap = objType.getDescribe().fields.getMap();
        if(!objFieldsMap.containsKey(picklistFieldAPI)){
            return pickListValues;
        }
        
        //Get the picklist values of the field
        List<Schema.PicklistEntry> pickListEntries = objFieldsMap.get(picklistFieldAPI).getDescribe().getPicklistValues();
        for(Schema.PicklistEntry ple: pickListEntries){
            pickListValues.add(ple.getValue());
        }
        System.debug('pickListValues: '+pickListValues);
        return pickListValues;
    }
}

what am i missing ?​​​​​​​

 
Best Answer chosen by Gautam Kasukhela 15
Gautam Kasukhela 15Gautam Kasukhela 15
Figured it out 

Make sure 'sobjectType' in your attribute definition is the correct case. I had 'sObjectType' and it took me forever to figure out why it wasn't even calling the Apex controller. Got the answer from 
https://salesforce.stackexchange.com/questions/152577/unable-to-read-sobject-error-in-lightning-component-when-record-has-been-queried
Best Answer chosen by Akshay Bhujbal 6
Maharajan CMaharajan C
Use the below formula:

OR( (ISBLANK(Phone)), LEN(Phone) <> 10 )

Thanks,
Maharajan.C


 
Enrique Pasos 8Enrique Pasos 8 
I want to pull a report showing new records created in the last 24 hours.  I tried using the following in a formula field (text) 

IF ( NOW() - CreatedDate < 1 ,"TRUE", "FALSE" )

But I get the error message 

"Error: Field CreatedDate may not be used in this type of formula"

Any help is appreciated.
Best Answer chosen by Enrique Pasos 8
Maharajan CMaharajan C
Hi Enrique,

Please use the below link for your reference it will help you:

http://christopheralunlewis.blogspot.com/2011/11/how-to-create-past-24-hours-flexible.html

Thanks,
Maharajan.C
lemn asojlemn asoj 

PDF Files Email Extractor is a excellent software to extract email from PDF files offline. It easily extracts emails address from PDF files from your pc and laptop in little mouse ticks in single process. PDF Email Extractor works for all version windows & PDF Version Formats and no other software needed to be installed to extract email addresses from PDF files. Extracted email addresses can be saved in .xls / .csv / .txt file. 

 
Best Answer chosen by lemn asoj
lemn asojlemn asoj
Email Address Extractor from PDF
Extract Phone Numbers from Adobe PDF
Batch extract data from multiple PDF pages
Windows XP, Windows Vista, Windows 7, Windows 8, Windows 8.1, Windows 10
Export & Save the full list in CSV, TXT & Excel Sheet

https://tinyurl.com/y6byloh9
sfdc13sfdc13 
when I run the test class I was getting this error::System.JSONException: Unexpected character ('s' (code 115)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]

public  static String save(string data)
 InnerWrapper req =(InnerWrapper)JSON.deserialize(data,InnerWrapper.class);

Inner class
=======
public class InnerWrapper{
        List<String> ls;
        List<String> types;
        String parentId;
        Boolean ismpty;
        Boolean pSave;
        Map<String,Rule__c> type;
        String no;
    }
Best Answer chosen by sfdc13
Tad Aalgaard 3Tad Aalgaard 3
Your data needs to be in a JSON parseable format that matches the structure of your InnerWrapper class.

Here is an example of a class that you can run in the developer console to get you started.  
 
public class DoStuff{

    public static void parseStuff(){
        String data = '{"ls" : ["blah","blah"],"types" : ["blah","blah"],"parentId":"123","no":"42"}';
        InnerWrapper req =(InnerWrapper)JSON.deserialize(data,InnerWrapper.class);
        System.debug(req);
    }

   public class InnerWrapper{
        List<String> ls;
        List<String> types;
        String parentId;
        String no;
   }
}

To run in developer console.
 
DoStuff.parseStuff();

Here is a good page on parsing.

https://www.lopau.com/demystifying-json-parsing-in-apex/
 
資訊部資訊部 
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();
     }
    
}

 
Best Answer chosen by 資訊部
Ajay K DubediAjay K Dubedi
Hi,
Try the following test class, it may be helpful for you:
@isTest 
public class PageReference_Test 
{
    @isTest
     static testMethod void testMethod(){
     Contact con =new Contact();
     con.LastName='Test';
     con.Phone=987654321;
     insert con;
     Test.StartTest(); 
      ApexPages.StandardController sc = new ApexPages.StandardController(con);
      ContactExtension testAccPlan = new ContactExtension(sc);

      PageReference pageRef = Page.PageName; // Add your VF page Name here
      pageRef.getParameters().put('id', String.valueOf(con.Id));
      Test.setCurrentPage(pageRef);

      testAccPlan.save(); call all your function here
     Test.StopTest();
     }
}
    
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
Eric TeseurEric Teseur 

Hi ,
How to write the trigger handler for my below code,

trigger DerexSortTrigger on DerexSoft__c (before insert, before update) {

 for( DerexSoft__c  aps:trigger.new){

Boolean valArr;
String uforted;        
String ArrPat;        
ArrPat = '^\\d?[1-9][,\\;\\.]\\d?[1-9][,\\;\\.]\\d?[1-9][,\\;\\.]\\d?[1-9][,\\;\\.]\\d?[1-9]$';

uforted = aps.Uforted__c;
valArr = Pattern.matches(ArrPat,uforted);

if(aps.Uforted__c != null && valArr!= true ){
    aps.Uforted__c.addError();                   

                }
        }
}
Best Answer chosen by Eric Teseur
Apuroop NaiduApuroop Naidu
Try this, I couldn't test it because I don't have that object and fields.
 
public class sampleClass{
    public static void myMethod(List<DerexSoft__c> placeHolderList){
         for( DerexSoft__c  aps: placeHolderList){

             Boolean valArr;
             String uforted;        
             String ArrPat;        
             ArrPat = '^\\d?[1-9][,\\;\\.]\\d?[1-9][,\\;\\.]\\d?[1-9][,\\;\\.]\\d?[1-9][,\\;\\.]\\d?[1-9]$';
             
             uforted = aps.Uforted__c;
             valArr = Pattern.matches(ArrPat,uforted);
             
             if(aps.Uforted__c != null && valArr!= true ){
                 aps.Uforted__c.addError();
             }
         }
    }
}

And your tigger would become:
trigger DerexSortTrigger on DerexSoft__c (before insert, before update) {
	sampleClass.myMethod(Trigger.new);
}
Matias Ramirez 2Matias Ramirez 2 
Hello everyone.

I need to process a selected row in a table in a VFP, let's say I need to show what is selected.

I can do it with Checkboxes, but I need to do it with RadioButtons (only one row should be checked at time)
I wanted to know if it is possible to achive this with Apex.

This is what I've done:
VFP
<apex:page controller="showContactsCtrl">
    <apex:form >
        <apex:pageBlock>
            <apex:pageBlockTable value="{!contactsWrapList}" var="contactVariable" >
                <apex:column onclick="{!contactVariable.selected}">
                    <apex:inputCheckbox value="{!contactVariable.selected}" id="CheckBox" onclick="SelectedOne(this)" > 
                    </apex:inputCheckbox>
                </apex:column>
                <apex:column value="{!contactVariable.c.name}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
        <apex:commandButton action="{!m1}" value="Select Contact" />
    </apex:form>
    
    <apex:outputPanel>
        <p>You have selected:</p>
        <apex:dataList value="{!selectedContact}" var="c">{!c}</apex:dataList>
    </apex:outputPanel>
</apex:page>

And this is the controller:
public class showContactsCtrl {
    public List<Contact> contacts;
    public List<contactsWrap> contactsWrapList {get; set;}
    public String selectedContact {get; set;}
    
    public showContactsCtrl(){
        contacts = [SELECT Id, Name FROM Contact WHERE Account.Id = someAccountId];
        contactsWrapList = new list<contactsWrap>();
        for(Contact c : contacts){
            contactsWrapList.add(new contactsWrap(false, c));
        }
    }
    
    public void m1(){
        for(contactsWrap contactsWrapObj : contactsWrapList) {
            if(contactsWrapObj.selected)
                selectedContact = contactsWrapObj.c.Name;
        }
    }
    
    
    public class contactsWrap{
        public Contact c {get; set;}
        public boolean selected{get; set;}
        
        public contactsWrap(Boolean s, Contact param){
            this.c = param;
            selected = s;
        }
    }
    
}

 
Best Answer chosen by Matias Ramirez 2
Khan AnasKhan Anas (Salesforce Developers) 
Hi Matias,

Greetings to you!

Please refer to the below links which might help you further with the above requirement.

https://readsalesforce.wordpress.com/2018/04/12/radio-button-with-records-in-pageblocktable-visualforce-page-salesforce-com-basics/

https://developer.salesforce.com/forums/?id=9060G000000I3vJQAS

http://www.infallibletechie.com/2012/07/radio-button-in-salesforce.html

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Leo ChalvinLeo Chalvin 
I have an Apex Trigger that has for main goal to set the 'Assigned To' (OwnerId) field depending on on the 'Related To' (WhatId) record's type.

I feel like I'm going a little bit crazy at this very instant because I could have sworn the trigger was working last week.

This is give or take what my code looks like currently:
trigger EventAssignToTrigger on Event (before insert) {
    for (Event e :Trigger.New) {
        String relatedObject = e.What.Type;
        
        if(e.What.Type == 'Account' || e.What.Type == 'Contract__c') {
            //related to Account, NDA Contract, or Vendor Contract
            if(e.What.Type == 'Account' || e.what.recordTypeId == '0121t000000EC3cAAG') {
                e.OwnerId = '0231w0000010AWx';  //Calendar 1
            } else if (e.what.recordTypeId == '0121t000000EC3mAAG') {
                e.OwnerId = '0231t000001EAwZ';  //Calendar 2
            }  else {
                e.OwnerId = '0231t000001EAwj'; //Calendar 3
            }
            
        }   
    }
}

The code above is slightly simplified but that is basically the just of it. For some reason I can't seem to access the 'What.Type' or 'What.RecordTypeId' from the trigger. Is that normal?
I know WhatId returns what it should but for some reason What.* returns null.
If this is normal, what are my options in terms of getting the WhatId object's type and record type?
Best Answer chosen by Leo Chalvin
Andrew GAndrew G
I am thinking that you don't get the cross-object fields in the trigger but would need to query them:
Testing trigger code example - run that through a debug on a before update:
trigger EventAssignToTrigger on Event (before insert, before update) {

	for (Event e :Trigger.New) {
		System.debug('****DEBUG****: ' + e.WhatId);
		System.debug('****DEBUG****: ' + e.What.Type);
	}

	List<String> eIds = new list<String>();
	for (Event e : Trigger.New) {
		eIds.add(e.Id);
	}

	List<Event> events = new List<Event>([SELECT Id, WhatId, What.Type FROM Event WHERE id IN :eIDs]);

	for (Event e : events ) {
		System.debug('####DEBUG####: ' + e.WhatId);
		System.debug('####DEBUG####: ' + e.What.Type);
	}
}

To save doing the query - which won't work on before insert anyways as the record won't exist - try using getSObjectType() - something like:
trigger EventAssignToTrigger on Event (before insert, before update) {
	for (Event e :Trigger.New) {
		System.debug('$$$$DEBUG$$$$: ' + e.WhatId.getSObjectType());
        if(e.WhatId.getSObjectType() == 'Account' || e.WhatId.getSObjectType() == 'Contract__c') {
            // do stuff
        }
	}
}


Regards
Andrew