Add multiple fields to a custom block

Permalink 1 user found helpful

I would like to create a custom block in which you can dynamically add fields of the same type when adding/editing the block just like you can do in the standard blocks form, survey & slideshow. However, I have trouble finding how to do this.

I have understood that I have to override the save($args) function and instead save an array of the added fields.

Does any one know how to do this, of a tutorial or have a good example block to learn from?

Any input is appreciated!

View Replies:
jordanlev replied on at Permalink Reply
It is a fairly complex thing to do. Your best bet is to look at the slideshow block (although it's not for the faint of heart -- the code is not very straightforward).

I do wish that there were some kind of built-in library or widget that helped with this (it's on my extremely long todo list, so maybe in 5 years there will be ;)

The best I can do here is explain at a high level how you'd approach it:

FRONT END (add/edit.php files): Use some kind of jquery template library (I've had good luck with jquery-tmpl -- -- it is no longer in active development, but I am unaware of another solution that is as easy to use and well-documented as that one). You create a little mini-template for the field html, then have javascript functionality on the page that adds a new one of those or removes them as appropriate (check out the dashboard single_page of the Designer Content addon for a robust example of this technique).

BACK END (save method of controller.php): all of the form data is sent to the $data variable. In your javascript template on the front-end, you'd want to come up with a unique name for each new repeating field that's added to the form -- for example, adding an underscore and a unique sequential number to the end, or putting square brackets after the field name so PHP treats each one as an array element. You will need to loop through all of these to see what all of the data is that the user entered. Basically you must manually save everything here, and cannot rely on the usual built-in C5 functionality that automatically saves form fields to database fields.

The especially tricky part is going to be loading existing data (you'll need to manually load this in the controller's edit() function, and send it to the edit.php template) and displaying that (you'll want to run some kind of initialization javascript to create fields based on your mini-template -- probably having php output a javascript array, or the javascript code itself that does this.

If you're an experienced developer, this will take a little time but be very doable. If you're not that experienced with PHP or javascript, it's going to be a very challenging task (but a *great* learning experience if you're up for it -- it really touches on a lot of useful and common situations you'll encounter as a web developer and a C5 developer).

Good luck!