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.
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.
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.
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 !
When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.