I'm trying to insert a custom object record which contains various custom fields and also a lookup field. Is it possible to insert the record without specifying the lookup field value? I've tried inserting an empty value or null on the lookup field but it throws an System.NullPointerException: exception error.
carts.Code__c –> The Lookup field
if(carts == null) carts = new Cart__c();
carts.rStatus__c = 'Saved';
carts.Price__c = 125;
if (code != null || code.length() != 0){
carts.Code__c = [SELECT Name, code__c FROM Code__c WHERE code__c =:code].Id;
} else{
carts.Code__c = '';
}
insert carts;
pageRef = new PageReference('/apex/out');
pageRef.setRedirect(true);
}catch(DmlException e) {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Error' + e);
ApexPages.addMessage(myMsg);
} catch(Exception e) {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please be patience, Your request will be......' + e);
ApexPages.addMessage(myMsg);
}
return pageRef;
Best Answer
This will most likely be coming from the line: (please indicate in your responses which line is throwing the exception)
There are a couple of problems with this line:
Instead, try something like: