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 MoritzLost
      This module allows you to integrate hCaptcha bot / spam protection into ProcessWire forms. hCaptcha is a great alternative to Google ReCaptcha, especially if you are in the EU and need to comply with privacy regulations.

      The development of this module is sponsored by schwarzdesign.
      The module is built as an Inputfield, allowing you to integrate it into any ProcessWire form you want. It's primarily intended for frontend forms and can be added to Form Builder forms for automatic spam protection. There's a step-by-step guide for adding the hCaptcha widget to Form Builder forms in the README, as well as instructions for API usage.
      Features
      Inputfield that displays an hCaptcha widget in ProcessWire forms. The inputfield verifies the hCaptcha response upon submission, and adds a field error if it is invalid. All hCaptcha configuration options for the widget (theme, display size etc) can be changed through the inputfield configuration, as well as programmatically. hCaptcha script options can be changed through a hook. Error messages can be translated through ProcessWire's site translations. hCaptcha secret keys and site-keys can be set for each individual inputfield or globally in your config.php. Error codes and failures are logged to help you find configuration errors. Please check the README for setup instructions.
      Links
      Github Repository and documentation InputfieldHCaptcha in the module directory (pending approval) Screenshots (configuration)

      Screenshots (hCaptcha widget)

       
       

       
    • By joshua
      This module is (yet another) way for implementing a cookie management solution.
      Of course there are several other possibilities:
      - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/
      - https://github.com/webmanufaktur/CookieManagementBanner
      - https://github.com/johannesdachsel/cookiemonster
      - https://www.oiljs.org/
      - ... and so on ...
      In this module you can configure which kind of cookie categories you want to manage:

      You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience.
      Currently there are four possible cookie groups:
      - Necessary (always enabled)
      - Statistics
      - Marketing
      - External Media
      All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ...
      When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax:
      <script type="text/plain" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The type has to be "optin" to get recognized by PrivacyWire, the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision.
      If you want to give the users the possibility to change their consent, you can use the following Textformatter:
      [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie.
      You can also add a custom link to output the banner again with a link / button with following class:
      <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> This module is still in development, but we already use it on several production websites.
      You find it here: PrivacyWire Git Repo
      Download as .zip
      I would love to hear your feedback 🙂
      CHANGELOG
      0.1.1 Debugging: fixed error during uninstall 0.1.0 Added new detection of async scripts for W3C Validation 0.0.6 CSS-Debugging for hiding unused buttons, added ProCache support for the JavaScript tag 0.0.5 Multi-language support included completely (also in TextFormatter). Added possibility to async load other assets (e.g. <img type="optin" data-category="marketing" data-src="https://via.placeholder.com/300x300">) 0.0.4 Added possibility to add an imprint link to the banner 0.0.3 Multi-language support for module config (still in development) 0.0.2 First release 0.0.1 Early development
    • By bernhard
      --- Please use RockFinder3 ---
    • 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 (pending approval) If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By Craig
      I've been using Fathom Analytics for a while now and on a growing number of sites, so thought it was about time there was a PW module for it.
      WayFathomAnalytics
      WayFathomAnalytics is a group of modules which will allow you to view your Fathom Analytics dashboard in the PW admin panel and (optionally) automatically add and configure the tracking code on front-end pages.
      Links
      GitHub Readme & documentation Download Zip Modules directory Module settings screenshot What is Fathom Analytics?
      Fathom Analytics is a simple, privacy-focused website analytics tool for bloggers and businesses.

      Stop scrolling through pages of reports and collecting gobs of personal data about your visitors, both of which you probably don't need. Fathom is a simple and private website analytics platform that lets you focus on what's important: your business.
      Privacy focused Fast-loading dashboards, all data is on a single screen Easy to get what you need, no training required Unlimited email reports Private or public dashboard sharing Cookie notices not required (it doesn't use cookies or collect personal data) Displays: top content, top referrers, top goals and more
×
×
  • Create New...