Group fields together in JForm to create html input as array

This blog post is a reply to this topic on Joomla's forum: http://forum.joomla.org/viewtopic.php?f=642&t=815225 but when I tried to post it there I got a 403 error, that is why I thought that I'll share this information here.

For the last couple of weeks I've been working on the multiple upload functionality that is going to come with the next Hotspots version. I'm about to finish this off, but as usual there are some things that pop up and need rewriting. I've decided that instead of hardcoding the generated thumbnails, I'll add an option for the user where he can define his own thumbnail dimentions.

The problem is - when we save the images we need to get all available dimentions and generate the thumbs. Hotspots uses Joomla's configuration manager and it's using JForm to create the options. The configuration is stored as json array in the database. So I thought - It would be great if I had a nested structure like this for the thumbs property:

thumbs => small
thumbs => medium
thumbs => large

This is basically an array with small, medium and large keys. Now how do you create input fields that would be stored as array??? You would normally need this html syntax:

<input type="text" name="jform[thumbs][small] ...
<input type="text" name="jform[thumbs][medium] ...
<input type="text" name="jform[thumbs][large] ...

But how do you force JForm to do this for you?

Creating a field like this:

<field name="thumbs[small] ... />

actually outputs

<input type="text" name="jform[thumbs[small]]"

and this is not what we want. Fortunatly after looking at the getName function of JFormField I realised that I have to group my field definitions together in a fields node. The code then looks like this:

<fields name="thumbs">
    <field
        name="small"
        type="text"
        size="20"
        default="50x50"
        label="LIB_COMPOJOOM_FIELD_SMALL_THUMB_LABEL"
        description="LIB_COMPOJOOM_FIELD_SMALL_THUMB_DESC" />

    <field
        name="medium"
        type="text"
        size="20"
        default="320x240"
        label="LIB_COMPOJOOM_FIELD_MEDIUM_THUMB_LABEL"
        description="LIB_COMPOJOOM_FIELD_MEDIUM_THUMB_DESC" />

    <field
        name="large"
        type="text"
        size="20"
        default="900x600"
        label="LIB_COMPOJOOM_FIELD_LARGE_THUMB_LABEL"
        description="LIB_COMPOJOOM_FIELD_LARGE_THUMB_DESC" />
</fields>

now this generates the correct html input field:

<input type="text" name="jform[thumbs][small]"
<input type="text" name="jform[thumbs][medium]"
<input type="text" name="jform[thumbs][large]"

This way the values for those fields are saved as an array in the database.

Rate this blog entry:
2
Hotspots 5.1 now available for download
Custom filtering for JForm fields