I have a form that I am filling with default values in hook_form_alter
. Some of the fields are in a in a field group and I need to trigger the “add more” button using code.
I figured out how to send a value to the jQuery code via $form['#attached']['js']
. I thought I could use that value to run a loop in the jQuery to trigger the “add more” as often as necessary but I only see the field group values twice.
For example if there should be four sets of field group values, I will see the first and second one but not the third or fourth. If I click on the add more button two more times I’ll see them in the form.
Here is the code in the js file:
(function ($, Drupal) { // Custom functions and variables can go here Drupal.behaviors.example = { attach: function (context, settings) { // Put your document's onload code here //alert(Drupal.settings.example.clicks); for (var i = 0; i < Drupal.settings.example.clicks; i++) { //alert(i); $("#edit-fgm-node-example-form-group-stuff-add-more").trigger("mousedown"); } } }; }(jQuery, Drupal));
This where I attach the js file
function example_after_build($form, &$form_state) { // TODO: Stuff! $settings['clicks'] = $_SESSION['count_of_items']; //the initial count of times to trigger jquery drupal_add_js(['example' => $settings], 'setting'); // Add our JavaScript file, named after_ajax.js. This file // lives in the /js folder inside our module: $form['#attached']['js'] = [ [ 'type' => 'file', 'data' => drupal_get_path('module', 'example') . '/js/after_ajax.js', ], ]; return $form; }
Any advice on how I could trigger the “add more” multiple times? Or is what I want to do not possible?