I'm trying to create a VF page for users to input data and then view their data. I've a few issues. Let's start with the input side. I hope someone can provide guidance. Here is my example.

I've 2 custom objects A (One) and B (Many) which I'm asking for users to provide inputs and then allow the capability to view their data. Their relationships are lookups.

When asking for users for input, I'm restricting the duplicate entries in object A by creating a formula field called combine (Username (picklist) with Month (picklist)). A user can not create two records in one month.

When a user create a record in object A they will create many records in Object B. How do I create this relationship when the record is created?

Thanks in advance.

1 Answer 1


This question seems a bit vague, but assuming you're using a standard controller for the page you're going to need to write a controller extension, and I think others might find themselves in similar scenarios so I'm going to attempt to provide a useful answer.

Essentially you save the new Object A record manually in the extension controller and then create the Object B records (as many as required) and set their lookup fields using the new ID found on the A record.

The rough skeleton for the controller would like the one below, and instead of calling {!Save} in your page you need an action button to use the customised saved method. This doesn't include any error checking so you'll want to add some try {} catch {} blocks in for safety!

Controller Extension

public with sharing ObjBExtension
    private ApexPages.StandardController sc;

    public ObjBExtension(ApexPages.StandardController sc)
        /* Store a reference to the standard controller so we can use
            it's save method later on */
        this.sc = sc;

    public PageReference SaveAndCreateBRecords()
        ApexPages.PageReference pr = sc.save();

        // Cast the SObject returned to the real type
        ObjectA__c objA = (ObjectA__c)sc.getRecord();

        List<ObjectB__c> bRecords = new List<ObjectB__c>();

        // Assuming you want 7 B records, one for each day of the week
        for(Integer i = 0; i < 7; i++)
            bRecords.add(new ObjectB__c(Name = 'Day ' + i), ObjALookup__c = objA.Id);

        insert bRecords;

        /* Returning the page reference from the save method will take
            the user to the detail page for the new A record */
        return pr;

Page Snippet

<apex:page controller="{!ObjectA__c}" extensions="ObjBExtension">
        <apex:inputField value="{!ObjectA__c.Name}"/>
        <apex:commandButton action="{!SaveAndCreateBRecords}" value="Save"/>
        <!-- snip! -->
  • Thanks LaceySnr. Let try to implement this into my exist codes.
    – Caky
    Oct 4, 2013 at 17:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .