Forms are everywhere on the web. From a simple sign up form to complicated application forms you’ve seen various forms with varying validation and fields. A very popular way to ask users to input multiple values for similar data is to use the “Add More” type field where the user can add any number of entries. Examples are Educational Qualification, Previous Employment History etc.

Joomla too supported the add more fields natively, by use of the repeatable element. However it had a few limitations

We’d tried to overcome these in a recent project by improving the repeatable field, but while we were doing that we realised that Joomla 3.6 has solved this in a much better way! Welcome “sub forms”. This provides a way to use JForm XML inside existing forms, by way of including another XML in lieu of a field in the parent XML. With sub-forms you can -

Let’s move on to an example -

Step 1 - Create a xml file which you want to nest into the subform field. The subform can contain any of the available Joomla field types. Let’s say you want to create a repeatable field for Past Employers. So create the file in components/com_yourcomponent/models/forms/pastemployers.xml with below code in it. 

<?xml version="1.0" encoding="UTF-8"?>
<form>
  <field name="start_date" 
         type="text" 
         label="Started working" />
  <field name="end_date" 
         type="text" 
         label="Left Job" />
  <field name="employer_name"
         type="text"
         label="Employer Name" />
  <field name="employer_name"
         type="text"
         label="Employer Name" />
</form>

Step 2 - Create the parent form that needs to load the sub form. For simplicity, I’m leaving out any other fields in the parent form and showing only 1 field which will display the sub form.

<?xml version="1.0" encoding="utf-8"?>
<form>
 <fieldset>
  <field name= "experience"
         description= "Past work history"
         type= "subform"
         label= "Employment History"
         min= "1"
         max= "1000"
         required= "true"            
         formsource= "components/com_pip/models/forms/pastemployers.xml"
         multiple= "true"
         buttons= "add,remove"
  layout="joomla.form.field.subform.repeatable-table"
         groupByFieldset="false"/>
    </fieldset>
</form>

 The sub form field supports a lot of configuration using atrributes, so let’s see those one by one -

Step 3 - Load this field as usual in your view’s layout file.

echo $form->getInput(‘experience’);

That’s it ! However watch out for these gotchas that I faced when implementing the sub-form

Hope you implement sub-forms the next time you need add more instead of writing your own code ! Do let me know if you have more tips and tricks around sub-forms in the comments below. Thanks !