[SalesForce] Inserting a record with Lookup value

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

Currently the error message is System.QueryException: List has no rows for assignment to SObject.

This will most likely be coming from the line: (please indicate in your responses which line is throwing the exception)

carts.Code__c = [SELECT Name, code__c FROM Code__c WHERE code__c =:code].Id;

There are a couple of problems with this line:

  1. You are using a short hand syntax that assumes exactly one Code__c record will always be returned by this query. If no records match then you will get the QueryException for no rows.
  2. You are querying the Name and Code__c fields and then using the Id field, which isn't part of the SOQL query.

Instead, try something like:

List<Code__c> codes = [Select Id from Code__c where code__c = :code limit 1];
if(codes.size() > 0) {
    carts.Code__c = codes[0].Id;
} else {
    carts.Code__c = null;
}