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
niharnihar 

error message:

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Last Name]: [Last Name]
Error is in expression '{!save}' in component <apex:commandButton> in page formexample: Class.EnrollmentFormClass.save: line 30, column 1
An unexpected error has occurred. Your development organization has been notified.
visualforcepage :

<apex:page controller="EnrollmentFormClass">
    <apex:form >
    <apex:pageBlock title="Opportunitiy Zone Enrollment Form">
              <apex:pageBlockSection columns="3">
              <apex:inputField value="{!con.Student_Name__c}"/>
              <apex:inputField value="{!con.School__c}"/> 
              <apex:inputField value="{!con.Date__c}"/> 
            </apex:pageBlockSection>
            <br/> 
            <br/>
                    SPARC programs are funded by United Way of Greater Atlanta. As such, we are required to report demographic, income, educational and health access information on every individual/family we serve. With the United Way belief that serving one family member serves them all, we collect general information on each member of your household. We appreciate your willingness to complete this form in its entirety so that we can continue providing free programs to the community. Thank you!
            <br/>  
            <br/> 
            <apex:pageBlockSection title="Head of Household Information:">
                <apex:inputField value="{!con.FirstName}"/>
                <apex:inputField value="{!con.LastName}"/>
                <apex:inputField value="{!con.Date_of_Birth__c}"/>
                <apex:inputField value="{!con.Gender__c}"/> 
                <apex:inputField value="{!con.Do_you_have_a_primary_medical_provider__c}"/>
                <apex:inputField value="{!con.Do_you_have_a_primary_medical_provider__c}"/>
                <apex:inputField value="{!con.Address__c}"/>
                <apex:inputField value="{!con.City__c}"/>
                <apex:inputField value="{!con.State__c}"/>
                <apex:inputField value="{!con.County__c}"/>
                <apex:inputField value="{!con.Phone__c}"/>
                <apex:inputField value="{!con.Email_Address__c}"/>
                <apex:inputField value="{!con.Preferred_Method_of_Contact_Circle_One__c}"/>
            </apex:pageBlockSection>
            <apex:pageBlocksection title="Demographic Data: (All information is confidential and is used in applying for grants to fund this program.)" columns="3">
                 <apex:inputField value="{!con.Spanish_translation_Services_Needed__c}"/>
                 <apex:inputField value="{!con.Race_Check_One__c}"/>
                 <apex:inputField value="{!con.Marital_Status_check_one__c}"/>
                 <apex:inputField value="{!con.HIGHEST_LEVEL_OF_EDUCATION_Check_one__c}"/>
                 <apex:inputField value="{!con.Employment_check_one__c}"/>
            </apex:pageBlocksection>
            <apex:pageBlocksection title="Income:" columns="3">
                <apex:inputField value="{!con.Annual_Income__c}"/> 
                <apex:inputField value="{!con.Source_of_Income__c}"/> 
                <apex:inputField value="{!con.Primary_Method_of_Transportation__c}"/>
            </apex:pageBlocksection>
            <apex:pageBlocksection title="HOUSEHOLD Information:" columns="3">
                <apex:inputField value="{!conc.Other_Adult_First_Name__c}"/>
                <apex:inputField value="{!conc.LastName}"/>
                <apex:inputField value="{!conc.Date_of_Birth__c}"/>
                <apex:inputField value="{!conc.Gender__c}"/> 
                <apex:inputField value="{!conc.Relationship_Primary_Care_Provider__c}"/>
                <apex:inputField value="{!conc.Medical_Insurance__c    }"/> 
            </apex:pageBlocksection>
                <apex:pageBlockButtons location="bottom" >
                <apex:commandButton action="{!save}" value="save"/>
            </apex:pageBlockButtons> 
            <apex:pageBlocksection title="Children (all children currently in your household, INCLUDING those participating in this program):" columns="1">
             <apex:pageBlockTable value="{!concAddList}" var="c">
             <apex:column headerValue="Name">
             <apex:commandButton action="{!AddRow}" value="AddRow"/>
             </apex:column>
           
             <apex:column headerValue="Name">
             <apex:inputfield value="{!c.LastName}"/>
             </apex:column>
             <apex:column headerValue="Date of Birth">
             <apex:inputfield value="{!c.Date_of_Birth__c}"/>
             </apex:column>
             <apex:column headerValue="Gender">
             <apex:inputfield value="{!c.Gender__c}"/>
             </apex:column>
             <apex:column headerValue="Relationship Primary Care Provider">
             <apex:inputfield value="{!c.Relationship_Primary_Care_Provider__c}"/>
             </apex:column>
             <apex:column headerValue="Medical Insurance}">
             <apex:inputfield value="{!c.Medical_Insurance__c}"/>
             </apex:column>             
       </apex:pageBlockTable> 
       </apex:pageBlocksection>
       </apex:pageBlock>
    </apex:form>
</apex:page>


Apex class :

public with sharing class EnrollmentFormClass {
public Contact con {get;set;}
public Contact conc {get;set;}
public Contact conct {get;set;}
public List<Contact> concAddList{get;set;}
public Account acc {get;set;}
    
public EnrollmentFormClass() {
     con  = new Contact();
     conc = new Contact();
     conct = new Contact();
     acc  = new Account();
     concAddList  = new List<Contact>();  
     concAddList.add(con);
     }
    public void AddRow(){
        
        concAddList.add(new Contact());
        concAddList.add(con);
    }
public void save(){
    insert con;    
    acc.name = con.lastName;
    insert acc;
    con.AccountId = acc.Id;
    conc.AccountId = acc.Id;
    conct.AccountId = acc.Id;
    
    insert conc;
    insert conct;
    insert concAddList;
    update con;
   
    }
     
}
Best Answer chosen by nihar
RKSalesforceRKSalesforce
Hi Nihar,

In your Save method please assign some value to Contact.LastName field. Your Insert is failing because LastName field is required on COntact.

Please mark as best answer if helped.

Regards,
Ramakant

All Answers

RKSalesforceRKSalesforce
Hi Nihar,

In your Save method please assign some value to Contact.LastName field. Your Insert is failing because LastName field is required on COntact.

Please mark as best answer if helped.

Regards,
Ramakant
This was selected as the best answer
niharnihar
hi ramakanth,
  how to assign some value to Contact.LastName field?
RKSalesforceRKSalesforce
In your VF page Contact.LastName field is referenced 3 times. This field is required so put some value there.at all 3 places

Regards,
Ramakant
niharnihar
hi ramakanth,
   My task is to create page block table in application form by using visualforce and apex classes and insert data into it after inserting when click on addrow button it must open a new row
RKSalesforceRKSalesforce
Hi Nihar,

I had worked on similar requirement in the past to add new row for attachment. Please find below code for the same:
public with sharing class MultiAttachmentController 
{
    // the parent object it
    public String sobjId {get; set;}
    
    //Variable for Exception message
    private static final string EXEPTION_MSG = '\r\n';
    
    private static final string EXEPTION_MSG1 = '--------------'; 
    
    //Set of Site_Visit_Photo__c Names
    public Set<String> descriptionSet;
    
    // list of new attachmentsto add
    public List<Attachment> newAttachments {get; set;}
	public List<Attachment> attachmentsToAdd;
    
    // the number of new attachments to add to the list when the user clicks 'Add More'
    public static final Integer NUM_ATTACHMENTS_TO_ADD=5;
    
    //Get ParentId(BuildinId) and anitializing newAttachments 
    public MultiAttachmentController(ApexPages.StandardController controller)
    {       
        String strId = System.currentPagereference().getParameters().get('retURL');
        if(String.isNotBlank(strId)){
            strId = strId.remove('/');
            sobjId = strId;
        }
        newAttachments = new List<Attachment>{new Attachment(),new Attachment(),new Attachment(),new Attachment(),new Attachment()};
    }   

    // Add more attachments action method
    public void addMore()
    {
        // append NUM_ATTACHMENTS_TO_ADD to the new attachments list
        for (Integer idx=0; idx<NUM_ATTACHMENTS_TO_ADD; idx++)
        {
            newAttachments.add(new Attachment());
        }
    }    
    
    // Save action method
    public PageReference save()
    {
        try{
            //List variables to hold records of type Attachments and Site_Visit_Photo__c
            List<Attachment> toInsert = new List<Attachment>();
            List<Site_Visit_Photo__c> sitePhotoList = New List<Site_Visit_Photo__c>();
            List<Site_Visit_Photo__c> insertedSitePhotoList = New List<Site_Visit_Photo__c>();
			List<Site_Visit_Photo__c> sitePhotoListToInsert = New List<Site_Visit_Photo__c>();
            
            //Map to hold Name and id of Site_Visit_Photo__c record
            Map<String, Id> SVPhotoNameAndIdMap = New Map<String, Id>();    
            Site_Visit_Photo__c  localRecord;
            descriptionSet = New Set<String>();     
            Id parentRecordId;
            attachmentsToAdd = New List<Attachment>();
			
			for(Attachment attachRecord: newAttachments){
				if(attachRecord != null && attachRecord.Body != null && attachRecord.Description != null ){
					attachmentsToAdd.add(attachRecord);
					system.debug('@@@attachRecord.Description'+attachRecord.Description);
				}
				
			}
			system.debug('@@@attmentsToAdd '+attachmentsToAdd);
        
            //To iterate over list of attachments and add Site_Visit_Photo__c to the listto Insert 
            for(Attachment attach: attachmentsToAdd){
                localRecord = New Site_Visit_Photo__c();
                localRecord.Building__c = sobjId;
				localRecord.Name = attach.Description;
                descriptionSet.add(attach.Description);//add Name to descriptionSet
                sitePhotoList.add(localRecord);
            }		

			for(Site_Visit_Photo__c photo:sitePhotoList){
				if(photo.Name != null){
					sitePhotoListToInsert.add(photo);
				}
			}
            if(!sitePhotoListToInsert.isEmpty()){
                insert sitePhotoListToInsert;
                insertedSitePhotoList = [select id, Name from Site_Visit_Photo__c where Name in :descriptionSet];
            }
			
            
            //To Put data into Map which would be used later in the code
            if(!insertedSitePhotoList.isEmpty()){
                for(Site_Visit_Photo__c SVPhoto: insertedSitePhotoList){
                    SVPhotoNameAndIdMap.put(SVPhoto.Name, SVPhoto.Id);          
                }
            }
            //To set parent of Attachment record
            for (Attachment newAtt : attachmentsToAdd)
            {           
                if (newAtt.Body != null && newAtt.Description != null)
                {
                    parentRecordId = SVPhotoNameAndIdMap.get(newAtt.Description);
                    newAtt.parentId = parentRecordId;
					newAtt.ContentType = 'image/jpeg';							
                    toInsert.add(newAtt);
                }
            }
            insert toInsert;
            newAttachments.clear();
            newAttachments.add(new Attachment());
            return new PageReference('/'+sobjId);
            
        }catch(Exception classException){//To catch exceptions incase of failure
            
            system.debug(classException.getMessage() + EXEPTION_MSG + classException.getStackTraceString() + EXEPTION_MSG + classException.getTypeName() + EXEPTION_MSG + System.now() + EXEPTION_MSG + EXEPTION_MSG1);
            return new PageReference('/'+sobjId);
        }
        
    }
    
    // Action method when the user is done
    public PageReference done()
    {
        // send the user to the detail page for the sobject
        return new PageReference('/' + sobjId);
    }   
}

addMore method in above controller would do the trick for you.

PLease let me know if helped by marking best answer.

Regards,
Ramakant