[SalesForce] Issues saving apex:inputfield values to object in controller. Only last field on form saves value

Here's my issue:

As per code below, I am trying to display a number of fields dynamically and then allow the user to enter values and save the record (or update it if they are viewing an existing record, but that's besides the point).

Rendering the fields works fine, but when saving I get an error because only the last field on the form actually sends any data back to the controller. As you can see in the Apex block below, I am dumping some info to the debug log right before the insert. Those values show up as:

11:38:23.047 (47854968)|USER_DEBUG|[133]|DEBUG|4
11:38:23.047 (47899970)|USER_DEBUG|[134]|DEBUG|null
11:38:23.047 (47940313)|USER_DEBUG|[135]|DEBUG|null

(Here I had entered "4" for "Company")

If I move the order of fields around (for context, this is done via a page layout in the Salesforce UI), I can confirm that it is always the last one that is being set.

Does anyone have any idea why this would be occurring? Am I overlooking something obvious?

Please let me know if this question isn't formatted properly or if I should provide any more contextual info.

Thanks in advance!

Error:

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Last Name]: [Last Name]
Error is in expression '{!SaveLead}' in component <apex:commandButton> in page asdflead: Class.asdfLeadCont.SaveLead: line 136, column 1

VisualForce:

<apex:form>

<apex:commandButton styleClass="btn btn-primary" value="Save" action="{!SaveLead}" immediate="false"> </apex:commandButton>

<apex:repeat value="{!i['layoutComponents']}" var="c">
    <apex:outputPanel rendered="{!c['type'] == 'Field'}" layout="none">

        <div class="field-label"><b>{!c['details']['label']}</b>:</div> 
            <div class="field-value">
                    <apex:variable var="fieldName" value="{!IF(c['value'] == '', 'Email', c['value'])}" />
                    <apex:inputField styleClass="{!fieldName}" value="{!lead[fieldName]}" >
             </div>
        </div>
    </apex:outputPanel>
</apex:repeat>

</apex:form>

APEX:

 public PageReference SaveLead() {

    PageReference pageRef =  new PageReference('/apex/DetailPage?id=' + lead.id);

    System.debug('**************************************************************************');

        System.debug(this.lead.Company);
        System.debug(this.lead.Email);
        System.debug(this.lead.FirstName);
        insert this.lead;                       
        pageRef =  new PageReference('www.google.com');     //for testing       



    return pageRef;


}

Best Answer

I am not 100% certain but I think that the variable tag just takes the last possible value since it's in a loop. Try to debug all the parameters in the controller method and try to rewrite the page to drop the variable tag. Please let me know if it worked for you.