Jump to content
BitPoet

FormBuilderMultiplier - repeatable Fieldgroups in FormBuilder forms

Recommended Posts

I'm really in love with FormBuilder, but the one thing missing to match all my end users' expectations were repeatable field groups. Think repeaters, in ProcessWire terms. Our primary application of PW is our corporate intranet, so "lines" of fields are quite common in the forms I build. We have all kinds of request forms where the information for a varying number of colleagues needs to be entered (from meal order to flight booking request) and where it is simply impractical to send a form for each, and I don't want to clutter my forms with multiple instances of fields that may only get used ten percent of the time.

That's why I started to build FormBuilderMultiplier (link to GitHub).

What it does:

  • Adds an option to make a regular Fieldgroup repeatable
  • Lets you limit the number of instances of a Fieldgroup on the form
  • Adds an "Add row" button the form that adds another instance of the Fieldgroup's fields
  • Adds a counter suffix at the end of every affected field's label
  • Stores the entered values just like regular fields
  • Makes the entered values available in preview and email notifications
  • Supports most text based fields, textareas and selects (really, I haven't had enough time to test all the available choices yet)

What it doesn't do (yet):

  • Support saving to ProcessWire pages (i.e. real Repeaters)

I haven't tested all the validation stuff, Date/Time inputs etc. yet, but since I'm utterly swamped with other stuff at work, I didn't want to wait until I have it polished. Any feedback is welcome. There might also be some issues with different output frameworks that I haven't encountered yet. The forms I work with mostly use UIKit.

Status:

Still alpha, so test well before using it in the field.

Known issues:

When rows are added, the form's iframe needs to be resized, which isn't completely clean yet.

How it works:

The Fieldgroup settings are added through regular hooks, as is the logic that adds the necessary field copies for processing the form and displaying previews.

"Multiplied" field instances are suffixed with _NUM, where NUM is an incremental integer starting from 1. So if you have add two fields named "surname" and "givenname" to a fieldgroup and check the "multiply" checkbox, the form will initially have "surname_1" and "givenname_1" field (I'm still considering changing that to make the risk to shoot oneself into the foot by having a regular "surname_1" field somewhere else in the form less likely).

When a "row" is added, the first row is cloned through JS and the counter in the fields' IDs, names and "for" attributes as well as the counter in the label are incremented before appending the copies to the Fieldset container in the form.

To keep backend and frontend in sync, a hidden field named [name of the fieldset]__multiplier_rows is added to the form. Both the backend and the frontend script use this to store and retrieve the number of "rows".

ToDo:

  • Naturally, add the option to store the data in real repeaters when saving to pages.
  • Do a lot of testing (and likely fixing).
  • Make a few things (like the "Add row" button label etc.) configurable in field(set) context.
  • Add a smooth API to retrieve the multiplied values as WireArrays.

The mandatory moving screenshot:

FBMulitplier.gif

  • Like 13

Share this post


Link to post
Share on other sites

Hey! Sounds great!
I was looking for something like this for a client migration to PW for a long time.

I will check it out.

Share this post


Link to post
Share on other sites
20 hours ago, Peter Knight said:

Are there plans to also allow multipliers on the front end?

Thanks. I'm not completely sure if I read your question right. The screencap above shows the front end form (it's just included in the backend interface on the preview tab, but it's the same as if you embed your form anywhere on the frontend).

  • Like 1

Share this post


Link to post
Share on other sites

Hi @BitPoet,

I have tried your module and ran into a few error:

1. The "multiplied" rows are not getting the _NUM suffic for name and ID. Only on the label its adding #2

2. And Fatal error is thrown when checking the entries. This is within the ToPopulate function. If I Escape this row the error is gone. (I'm on the latest dev PW version)  

//$hid->label = _("Number of rows");

3. When I can view the data in entries -> the multiplier doestn have a value and the orginal has the filled in value of the original. Probably caused by 1. 
 

Share this post


Link to post
Share on other sites
1 hour ago, DL7 said:

I have tried your module and ran into a few error

Hi @DL7,

thanks for the feedback. I'll try to find the time tomorrow to give it a spin on the latest PW version so I can hopefully reproduce the behavior.

Share this post


Link to post
Share on other sites

Hi @BitPoet,

Thanks! Some additonal pointer: on an older version (3.0.36) I dont see this fatal error, but the increment still isnt working. 

The below mentioned isnt working for me either on this older version. See the form initially starts with their "normal" ID/Name as been set in the settings

On 11/12/2018 at 7:54 PM, BitPoet said:

the form will initially have "surname_1" and "givenname_1" field

This works only if I add 

if($child->name) $child->name .= "_1";

If I do this, then the increment is working perfectly. Problem I face then is that none of the entries fields are filled with values 🙂 I'm also looking into that. Fixed that by adding this same line to the populate hook:

if($child->name) $child->name .= "_1";

 

Share this post


Link to post
Share on other sites

@BitPoet One additional error I see: when using embed methode c, the JS is not triggered, this posting the form when clicking on add row. I'm checking it currently but havent found the problem yet. 

Added this the init

		$this->addHookAfter('Page::render', $this, 'addScripts');

This as a function


    public function addScripts($event) {
		$page = $event->object; 
		if($page->template == 'admin') return;
        $additionalHeadScripts = '<script type="text/javascript" src="'.wire('config')->urls->siteModules.'FormBuilderMultiplier/FormBuilderMultiplier.js"></script>';
		$event->return = str_replace("</head>", $additionalHeadScripts.'</head>', $event->return); 
	}
	

And commented/removed the current JS append to get this fixed. 

Share this post


Link to post
Share on other sites

Hi @BitPoet ,

I tried your module but have a few concerns about it. The field type Fieldset created for the forms works fine while trying out in the Preview section but on the frontend the Add Row button submits the form, I couldn't find event listeners on submit of the Add Row button to add the created Fieldset.

I'm currently using the module on ProcessWire 3.0.123.

Share this post


Link to post
Share on other sites
3 hours ago, Rajesh Khanna said:

I tried your module but have a few concerns about it. The field type Fieldset created for the forms works fine while trying out in the Preview section but on the frontend the Add Row button submits the form, I couldn't find event listeners on submit of the Add Row button to add the created Fieldset.

I'm currently using the module on ProcessWire 3.0.123.

Sounds like the FormBuilderMultiplier.js script isn't loaded. Which embed method do you use for your form?

Share this post


Link to post
Share on other sites
20 minutes ago, Rajesh Khanna said:

I have used the Template embed method.

Thanks for the quick feedback,the  template embed method should work. Is your module, by any chance, installed in a directory named differently than FormBuilderMultiplier inside site/modules? If yes, updating to the latest dev version should solve the issue.

Share this post


Link to post
Share on other sites
12 minutes ago, BitPoet said:

Thanks for the quick feedback,the  template embed method should work. Is your module, by any chance, installed in a directory named differently than FormBuilderMultiplier inside site/modules? If yes, updating to the latest dev version should solve the issue.

No the module is named properly as you stated.

Share this post


Link to post
Share on other sites
Just now, Rajesh Khanna said:

No the module is named properly as you stated. 

What FormBuilder version do you use?

I'll try to set up a test environment to see if I can replicate the issue.

Meanwhile, do you see any errors in the browser's developer console?

Share this post


Link to post
Share on other sites
3 minutes ago, BitPoet said:

What FormBuilder version do you use?

I'll try to set up a test environment to see if I can replicate the issue.

Meanwhile, do you see any errors in the browser's developer console?

Thank you for your help!!

FormBuilder version is 0.3.2 and FormBuilder Fieldset Multiplier version is 0.0.6 .

I even tried the Custom embed method, but still can't see any event listener on the Add button.

In the console, I found this line "ReferenceError: $ is not defined FormBuilderMultiplier.js:5:1 " don't know what this is.

Share this post


Link to post
Share on other sites
4 minutes ago, Rajesh Khanna said:

In the console, I found this line "ReferenceError: $ is not defined FormBuilderMultiplier.js:5:1 " don't know what this is. 

Ah, now I see. The script is missing the JQuery library (which is present in the backend).  For a short term solution, it should be sufficient to add the following lines within the <head> section of your template:

<?php $jq = $modules->get('JqueryCore'); ?>
<script src='<?php echo $config->urls->JqueryCore . "JqueryCore.js" ?>'></script>

I'll see about either making sure that jquery gets loaded by my module or rewriting the module script so it works without jquery in the long run.

  • Like 1

Share this post


Link to post
Share on other sites
18 hours ago, BitPoet said:

Ah, now I see. The script is missing the JQuery library (which is present in the backend).  For a short term solution, it should be sufficient to add the following lines within the <head> section of your template:


<?php $jq = $modules->get('JqueryCore'); ?>
<script src='<?php echo $config->urls->JqueryCore . "JqueryCore.js" ?>'></script>

I'll see about either making sure that jquery gets loaded by my module or rewriting the module script so it works without jquery in the long run.

Hi @BitPoet ,

I added the script within the <head> section and it worked. It'll be better if the jQuery gets loaded directly by the module.

Thanks a lot for your help, Cheers!!

  • Like 1

Share this post


Link to post
Share on other sites

Hi @BitPoet ,

I had another question to ask, how can I add the "multiplyLimit" function in the frontend. I have an input field where the user can add the number of input fields he/she wants to populate. Do check the attachment for reference.

multiplyLimit.png

Share this post


Link to post
Share on other sites
6 hours ago, Rajesh Khanna said:

I had another question to ask, how can I add the "multiplyLimit" function in the frontend. I have an input field where the user can add the number of input fields he/she wants to populate.

You can do that in an onchange handler for your number input. The limit is stored in the data-multiplier-limit of a hidden input with an ID of "Inputfield_" plus the name of the fieldset and "__multiplier_rows". If, for example, your "No Of Users" field is named "usercount", adding this snipped at the bottom of your template should do the trick:

<script>
$('#Inputfield_usercount').on('change', function(evt) {
  var newlimit = $(this).val();
  $('Inputfield_myinputs__multiplier_rows').data('multiplier-limit', newlimit);
});
</script>

This is untested, though. I'm heading out in a minute, but I'll take a closer look tomorrow. Did you add the "myinputs__multiplier_rows" label yourself? If not, then I missed to include the code to properly hide InputfieldHiddens in the module and need to fix that.

  • Like 1

Share this post


Link to post
Share on other sites

Hi BitPoet, thank you for that module, I'm quite happy cause I just recognized that it's not possible to use a multiplierfield in formbuilder forms – so your solution looks promising. I tried it with a single textfield and it works as expected. Except if the form validation forces the form to load again. Than the multiplier fields get messed up (cloned again) – and after a second submit error the fields are empty. 
Is this maybe related to a version conflict or is the repopulation after submit-errors just not implemented?

  • ProcessWire: 3.0.123
  • FormBuilder 40/ states 39(?), 
  • FormBuilder Fieldset Multiplier 0.0.6
  • Form embed used: template embed (option B)

Thanks for any help or hint…

fb_mpfs_1.png

fb_mpfs_2_submiterror.png

fb_mpfs_3_submiterror.png

Share this post


Link to post
Share on other sites

Great addition to FB, thanks @BitPoet

Small problem when using FB40a with PW3.0.145 to remember form entries in a cookie. On revisiting the form displays the number of rows I've added but they're empty of data.

Share this post


Link to post
Share on other sites
On 11/7/2019 at 4:28 PM, sz-ligatur said:

Except if the form validation forces the form to load again. Than the multiplier fields get messed up (cloned again) – and after a second submit error the fields are empty. 
Is this maybe related to a version conflict or is the repopulation after submit-errors just not implemented?

I need to take a look at that, but unfortunately, I'm not hopeful that I'll find enough time this week. Next week should be a bit less crazy though.

10 hours ago, psy said:

Small problem when using FB40a with PW3.0.145 to remember form entries in a cookie. On revisiting the form displays the number of rows I've added but they're empty of data.

I haven't found the time to update to the latest FB release, but it looks like soon will be a good time to do so 🙂 Stay tuned.

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Gadgetto
      SnipWire - Snipcart integration for ProcessWire
      Snipcart is a powerful 3rd party, developer-first HTML/JavaScript shopping cart platform. SnipWire is the missing link between Snipcart and the content management framework ProcessWire.
      With SnipWire, you can quickly turn any ProcessWire site into a Snipcart online shop. The SnipWire plugin helps you to get your store up and running in no time. Detailed knowledge of the Snipcart system is not required.
      SnipWire is free and open source licensed under Mozilla Public License 2.0! A lot of work and effort has gone into development. It would be nice if you could donate an amount to support further development:

      Status update links (inside this thread) for SnipWire development
      2020-07-03 -- SnipWire 0.8.7 (beta) released! Fixes some small bugs and adds an indicator for TEST mode 2020-04-06 -- SnipWire 0.8.6 (beta) released! Adds support for Snipcart subscriptions and also fixes some problems 2020-03-21 -- SnipWire 0.8.5 (beta) released! Improves SnipWires webhooks interface and provides some other fixes and additions 2020-03-03 -- SnipWire 0.8.4 (beta) released! Improves compatibility for Windows based Systems. 2020-03-01 -- SnipWire 0.8.3 (beta) released! The installation and uninstallation process has been heavily revised. 2020-02-08 -- SnipWire 0.8.2 (beta) released! Added a feature to change the cart and catalogue currency by GET, POST or SESSION param 2020-02-03 -- SnipWire 0.8.1 (beta) released! All custom classes moved into their own namespaces. 2020-02-01 -- SnipWire is now available via ProcessWire's module directory! 2020-01-30 -- SnipWire 0.8.0 (beta) first public release! (module just submitted to the PW modules directory) 2020-01-28 -- added Custom Order Fields feature (first SnipWire release version is near!) 2020-01-21 -- Snipcart v3 - when will the new cart system be implemented? 2020-01-19 -- integrated taxes provider finished (+ very flexible shipping taxes handling) 2020-01-14 -- new date range picker, discount editor, order notifiactions, order statuses, and more ... 2019-11-15 -- orders filter, order details, download + resend invoices, refunds 2019-10-18 -- list filters, REST API improvements, new docs platform, and more ... 2019-08-08 -- dashboard interface, currency selector, managing Orders, Customers and Products, Added a WireTabs, refinded caching behavior 2019-06-15 -- taxes provider, shop templates update, multiCURL implementation, and more ... 2019-06-02 -- FieldtypeSnipWireTaxSelector 2019-05-25 -- SnipWire will be free and open source Plugin Key Features
      Fast and simple store setup Full integration of the Snipcart dashboard into the ProcessWire backend (no need to leave the ProcessWire admin area) Browse and manage orders, customers, discounts, abandoned carts, and more Multi currency support Custom order and cart fields Process refunds and send customer notifications from within the ProcessWire backend Process Abandoned Carts + sending messages to customers from within the ProcessWire backend Complete Snipcart webhooks integration (all events are hookable via ProcessWire hooks) Integrated taxes provider (which is more flexible then Snipcart own provider) Useful Links
      SnipWire in PW modules directory SnipWire Docs (please note that the documentation is a work in progress) SnipWire @GitHub (feature requests and suggestions for improvement are welcome - I also accept pull requests) Snipcart Website  

       
      ---- INITIAL POST FROM 2019-05-25 ----
       
    • By Sten
      Hello
      Till now I hacked something with the twig template but it works no more with new PW versions so I look forward to create a module. I am working on a site in multiple languages : French, English, Italian, German, Spanish, Portuguese, Hebrew, Russian. The new posts are entered in any language with a field for language. Till now, I got twig files to get the translations with constants defined for each part of the pages.
      So I'd like to create a module to include theses files added according to the url /fr/en/...
      Have you some observations to do before I begin about the direction to take ?
      Thank you
    • By ukyo
      Mystique Module for ProcessWire CMS/CMF
      Github repo : https://github.com/trk/Mystique
      Mystique module allow you to create dynamic fields and store dynamic fields data on database by using a config file.
      Requirements
      ProcessWire 3.0 or newer PHP 7.0 or newer FieldtypeMystique InputfieldMystique Installation
      Install the module from the modules directory:
      Via Composer:
      composer require trk/mystique Via git clone:
      cd your-processwire-project-folder/ cd site/modules/ git clone https://github.com/trk/Mystique.git Module in live reaction with your Mystique config file
      This mean if you remove a field from your config file, field will be removed from edit screen. As you see on youtube video.
      Using Mystique with your module or use different configs path, autoload need to be true for modules
      Default configs path is site/templates/configs/, and your config file name need to start with Mystique. and need to end with .php extension.
      Adding custom path not supporting anymore !
      // Add your custom path inside your module class`init` function, didn't tested outside public function init() { $path = __DIR__ . DIRECTORY_SEPARATOR . 'configs' . DIRECTORY_SEPARATOR; Mystique::add($path); } Mystique module will search site/modules/**/configs/Mystique.*.php and site/templates/Mystique.*.php paths for Mystique config files.
      All config files need to return a PHP ARRAY like examples.
      Usage almost same with ProcessWire Inputfield Api, only difference is set and showIf usage like on example.
      <?php namespace ProcessWire; /** * Resource : testing-mystique */ return [ 'title' => __('Testing Mystique'), 'fields' => [ 'text_field' => [ 'label' => __('You can use short named types'), 'description' => __('In file showIf working like example'), 'notes' => __('Also you can use $input->set() method'), 'type' => 'text', 'showIf' => [ 'another_text' => "=''" ], 'set' => [ 'showCount' => InputfieldText::showCountChars, 'maxlength' => 255 ], 'attr' => [ 'attr-foo' => 'bar', 'attr-bar' => 'foo' ] ], 'another_text' => [ 'label' => __('Another text field (default type is text)') ] ] ]; Example:
      site/templates/configs/Mystique.seo-fields.php <?php namespace ProcessWire; /** * Resource : seo-fields */ return [ 'title' => __('Seo fields'), 'fields' => [ 'window_title' => [ 'label' => __('Window title'), 'type' => Mystique::TEXT, // or InputfieldText 'useLanguages' => true, 'attr' => [ 'placeholder' => __('Enter a window title') ] ], 'navigation_title' => [ 'label' => __('Navigation title'), 'type' => Mystique::TEXT, // or InputfieldText 'useLanguages' => true, 'showIf' => [ 'window_title' => "!=''" ], 'attr' => [ 'placeholder' => __('Enter a navigation title') ] ], 'description' => [ 'label' => __('Description for search engines'), 'type' => Mystique::TEXTAREA, 'useLanguages' => true ], 'page_tpye' => [ 'label' => __('Type'), 'type' => Mystique::SELECT, 'options' => [ 'basic' => __('Basic page'), 'gallery' => __('Gallery'), 'blog' => __('Blog') ] ], 'show_on_nav' => [ 'label' => __('Display this page on navigation'), 'type' => Mystique::CHECKBOX ] ] ]; Searching data on Mystique field is limited. Because, Mystique saving data to database in json format. When you make search for Mystique field, operator not important. Operator will be changed with %= operator.
      Search example
      $navigationPages = pages()->find('my_mystique_field.show_on_nav=1'); $navigationPages = pages()->find('my_mystique_field.page_tpye=gallery');
    • By Robin S
      This is a module I made as an experiment a while ago and never got around to releasing publicly. At the time it was prompted by discussions around using Repeater fields for "page builder" purposes, where the depth feature could possibly be used for elements that would be nested inside other elements. I thought it would be useful to enforce some depth rules and translate the depth data into a multi-dimensional array structure.
      I'm not using this module anywhere myself but maybe it's useful to somebody.
      Repeater Depth Helper
      This module does two things relating to Repeater fields that have the "Item depth" option enabled:
      It enforces some depth rules for Repeater fields on save. Those rules are:
      The first item must have a depth of zero. Each item depth must not be more than one greater than previous item depth. It provides a RepeaterPageArray::getDepthStructure helper method that returns a nested depth structure for a Repeater field value.
      Helper method
      The module adds a RepeaterPageArray::getDepthStructure method that returns a multi-dimensional array where the key is the page ID and the value is an array of nested "child" items, or null if there are no nested children.
      Example

      The module doesn't make any assumptions about how you might want to use the depth structure array, but here is a way you might use it to output a nested unordered list.
      // Output a nested unordered list from a depth structure array function outputNestedList($depth_structure, $repeater_items) { $out = "<ul>"; foreach($depth_structure as $page_id => $nested_children) { $out .= "<li>" . $repeater_items->get("id=$page_id")->title; // Go recursive if there are nested children if(is_array($nested_children)) $out .= outputNestedList($nested_children, $repeater_items); $out .= "</li>"; } $out .= "</ul>"; return $out; } $repeater_items = $page->my_repeater; $depth_structure = $repeater_items->getDepthStructure(); echo outputNestedList($depth_structure, $repeater_items);
       
      https://github.com/Toutouwai/RepeaterDepthHelper
      https://modules.processwire.com/modules/repeater-depth-helper/
    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
×
×
  • Create New...