function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tyler HarrisTyler Harris 

DML Statments with Related Object Records

I'm trying to insert two object records, but I'm getting an error because the 2nd object list doesn't see the 1st object id yet and I'm getting a "Missing Required Field validation error". Is there a way I can time, or chain these so they are both inserted with the correct relationship.
 
public StoreFront2(){
        ct=new Purchase_Line_Items__c();
        ct2=new Contact();
        flag = false;
        flip = false;
        flag2 = true; 
      
    }
      
    public PageReference buy(){
        
        List<Merchandise__c> toMerch = new List<Merchandise__c>();
        
        List<id> updateMerch = new List<id>();
                
        PageReference send = new PageReference('/apex/StoreCart2');
        
        if(ct != null && cart !=null ){
            List<DisplayMerchandise> counter = new List<DisplayMerchandise>();
    		List<Merchandise_Line_Item__c> merchi = new List<Merchandise_Line_Item__c>();
            Decimal total = 0;
            counter = cart.values();
            
            for(Integer i = 0; i < counter.size();i++){
                Decimal totalPrice = counter.get(i).count;
                total +=totalPrice;
                ct.Item_Quantity__c=total;
                system.debug(ct);
          		merchi.add(new Merchandise_Line_Item__c(Name ='Pencils',Purchases__c=ct.id, Merchandise_Item_Stable__c='a02F000000AuhTh'));
              
            }	
         	insert ct;
            insert merchi;

 
Tyler HarrisTyler Harris
I get the error on line 33 here because it's not seeing ct.id from line 29.
CyberJusCyberJus
Hi Tyler, 

You have to insert your CT object first because it is does not have an Id value until it is inserted. Try moving your insert ct line above your for loop, then update your ct object after your loop with your updated Item Quantity value. 
Tyler HarrisTyler Harris
Hi Cyber,

I moved it up, but it's still not working.

Apex
public virtual class StoreFront2 {    
    
    public String message { get; set; }
    List<DisplayMerchandise> products;
    Map<Id, DisplayMerchandise> cart;
    public Boolean incart{get;set;}
    public Id rowz;
    public id rowDel{ get;set; }
    public Boolean flip{ get;set; }
    public Boolean flag{ get;set; }
    public Boolean flag2 { get; set; }
    public Purchase_Line_Items__c ct{ get;set; }
    public Contact ct2{get;set;}
    
    public StoreFront2(){
        ct=new Purchase_Line_Items__c();
        ct2=new Contact();
        flag = false;
        flip = false;
        flag2 = true; 
      
    }
      
    public PageReference buy(){
        
        List<Merchandise__c> toMerch = new List<Merchandise__c>();
        
        List<id> updateMerch = new List<id>();
                
        PageReference send = new PageReference('/apex/StoreCart2');
        
        if(ct != null && cart !=null ){
            List<DisplayMerchandise> counter = new List<DisplayMerchandise>();
    		List<Merchandise_Line_Item__c> merchi = new List<Merchandise_Line_Item__c>();
            Decimal total = 0;
            counter = cart.values();
            insert ct;
            
            for(Integer i = 0; i < counter.size(); i++){
                
                Decimal totalPrice = counter.get(i).count;
                total +=totalPrice;
                ct.Item_Quantity__c=total;
                system.debug(ct);
          		merchi.add(new Merchandise_Line_Item__c(Name ='Pencils',Purchases__c=ct.id, Merchandise_Item_Stable__c='a02F000000AuhTh'));
              
            }	
         	
            insert merchi;

      		
            
	
			
        }
        
        return send;     
    }
    
    
    public void doShow(){
        if(flip){
            flag = true;  
            flag2=false;
        }
        else{
            flag = false;
            flag2 = true;
        }
          
    }
 
    public PageReference shop(){
        handleTheBasket();
        message = 'You bought: ';
        for (DisplayMerchandise p:products){
            if(p.tempCount > 0){
               message += p.merchandise.name + ' (' + p.tempCount + ') ' ;
               }
            }
        return null;
    }
   
    
    public void remove(){
     rowz = (Id) ApexPages.currentPage().getParameters().get('rowDel');
        if(cart.containsKey(rowz)){
            cart.remove(rowz);
            if(cart.isEmpty()){
                incart = false;
            }      
        }  
       
    }
        public pageReference back(){
        PageReference doit = new PageReference('/apex/StoreCart');
        doit.setRedirect(false);
            return doit;
        }
    
    
    public Pagereference checkout(){
        if(cart.isEmpty()){
            ApexPages.Message myError = new ApexPages.Message(ApexPages.Severity.ERROR, 'Shopping Cart is Empty');
            ApexPages.addMessage(myError);
            return null;
        } 
        
        else{
        PageReference send = new PageReference('/apex/ConfirmBuy');
        return send;
        }
    } 
    
    
    public void handleTheBasket(){
        for(DisplayMerchandise c : products){
            if(c.tempCount > 0){
            if(cart.containsKey(c.merchandise.Id)){        
                cart.get(c.merchandise.Id).count += c.tempCount;
                
            }
            else{
                cart.put(c.merchandise.Id, c);
                cart.get(c.merchandise.Id).count = c.tempCount;
                incart = true;
      
            } 
        
        }
        }
        
    }
    
    public Map<Id, DisplayMerchandise> getCart() {
        if(cart == null){
            cart = new Map<Id, DisplayMerchandise>();
            incart = false;
                }
      
        return cart;
    }
    
    public class DisplayMerchandise {
        public Merchandise__c merchandise{get; set;}
        public Decimal count{get; set;}
        public Decimal tempCount{get;set;}
        public DisplayMerchandise(Merchandise__c item){
            this.merchandise = item;
            
        }
    }

    public List<DisplayMerchandise> getProducts() {
        if (products == null){
            products = new List<DisplayMerchandise>();
    
            for (Merchandise__c item :
            [SELECT id, name, description__c, price__c
            FROM Merchandise__c
            WHERE Total_Inventory__c > 0]) {
           
            products.add(new DisplayMerchandise(item));
            }
        }
        return products;
    }

}