I have two objects that are needed to be inserted at the same time. These objects are Parent__c
(parent object) and Detail__c
(detail object). But each time I hit the save button, there's this error showing up:
Attempt to de-reference a null object
Error pertains to this line: newDetailList.add(d);
I tried inserting the parent record first without the line items, and it is successfully saved. However, problem occurs when I try to add the detail object part.
Meanwhile, here's what I've worked on so far:
Apex Class:
public class InsertParentAndDetail {
public Parent__c newParent{get;set;}
public List<LineItemWrapper> wrapperList{get;set;}
public List<Account> selectedAccount {get;set;}
public List<Detail__c> newDetailList {get;set;}
public InsertParentAndDetail(ApexPages.StandardController controller) {
newParent = (Parent__c)controller.getRecord();
if(wrapperList == null) {
wrapperList = new List<LineItemWrapper>();
}
for(Account a : [SELECT Id, Name, Industry FROM Account LIMIT 10]) {
wrapperList.add(new LineItemWrapper(a));
}
}
public PageReference save() {
List<Account> selectedAccount = new List<Account>();
for(LineItemWrapper wrapItem : wrapperList) {
if(wrapItem.selected == true) {
selectedAccount.add(wrapItem.acc);
}
}
insert newParent;
if(newParent.Id != null) {
for(LineItemWrapper liWrap : wrapperList) {
Detail__c d = new Detail__c();
d.Parent__c = newParent.Id;
d.Account__c = liWrap.acc.Id;
newDetailList.add(d);
}
insert newDetailList;
}
PageReference pageRef = new PageReference('/' + newParent.Id);
pageRef.setRedirect(true);
return pageRef;
}
public class LineItemWrapper {
public Boolean selected {get;set;}
public Account acc {get;set;}
public LineItemWrapper(Account acc2) {
acc = acc2;
selected = false;
}
}
}
Visualforce Page:
<apex:page standardController="Parent__c" extensions="InsertParentAndDetail">
<script type="text/javascript">
function selectAllCheckboxes(obj,receivedInputID){
var inputCheckBox = document.getElementsByTagName("input");
for(var i=0; i<inputCheckBox.length; i++){
if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
inputCheckBox[i].checked = obj.checked;
}
}
}
</script>
<apex:form >
<apex:pageblock>
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Parent Information">
<apex:inputField value="{!newParent.Field1__c}" label="Field 1"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="All Accounts">
<apex:pageBlockTable value="{!wrapperList}" var="accWrap">
<apex:column >
<apex:facet name="header">
<apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
</apex:facet>
<apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
</apex:column>
<apex:column value="{!accWrap.acc.Name}"/>
<apex:column value="{!accWrap.ac.Industry}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>
liWrap.acc.Id
value and initialize the list as well because your list is null.