Automatically fill Contact Form 7 dropdown options using data from an ACF field

After using the same old Wordpress contact form plugin, FastSecureContactForm, and custom JavaScript code for years to populate a dropdown list in a contact form with file titles from an ACF field, I decided to rebuild my website. Now, I am using Contact Form 7 and would like to replicate this functionality.

The previous JavaScript code referred to the ACF field containing track names as track_name and the form field in FastSecureContactForm where the list of file names was generated dynamically as si_contact_ex_field2_3. The numbers indicated the specific form (2) and extra field (3). Here is a snippet of the JavaScript used:


<script type="text/javascript">

var field_to_update = document.getElementById('si_contact_ex_field2_3');
field_to_update.innerHTML = '';

var elOptNew = document.createElement('option');
elOptNew.text = 'Select'
elOptNew.value = 'Select';

field_to_update.add(elOptNew);

field_to_update.options[0].selected = true;

var track_names = document.getElementsByName('audioFileName');  

for (i=0; i<track_names.length; i++) {

    var track_name = track_names[i].innerHTML;

    var elOptNew = document.createElement('option');
    elOptNew.text = track_name.replace("&amp;", "&");
    elOptNew.value = track_name;

    field_to_update.add(elOptNew);
}

I have two questions:

A) How can I adapt the above JavaScript to reference and populate the dropdown field in the new Contact Form 7 form with data from the ACF field? Currently, I have created a "Form Tag" like this

[select* menu-470 "Select" "Track A" "Track B" "Track C"]
, but I need the "Track A" "Track B" "Track C" part to be dynamically substituted with multiple track_names retrieved from the ACF field.

B) If there is a simpler or better way to achieve dynamic population of the dropdown field in Contact Form 7, I would appreciate any suggestions or guidance.

Thank you in advance for your assistance!

Phil

Answer №1

Try this method that eliminates the need for extra plugins.

Construct your form in the following manner:

[checkbox my-options data:my_possible_values]
[submit]

Next, insert the following code snippet into your theme's functions.php file:

add_filter('wpcf7_form_tag_data_option', function($n, $options, $args) {
  if (in_array('my_possible_values', $options)){
    
    // Assuming 'my_acf_field' is an ACF multi-select field
    $my_possible_values = get_field('my_acf_field');

    // Transform $my_possible_values to an array
    // resembling this format: ['val 1', 'val 2', 'val 3']
    return array_map(function($el) {
        return $el['value'];
    }, $my_possible_values);
  }
  return $n;
}, 10, 3);

Note: the data attribute can also be utilized with [radio] and [select] fields.

View a demonstration of this technique here:

Answer №2

If you're looking to enhance your cf7 form with a Smart Grid-layout Design, the extension plugin offers a solution with its dynamic dropdown field tag.

By converting your select tag into a dynamic one, you can take advantage of this feature,

[dynamic_select dynamic_select-353 "source:filter"]

The dynamic dropdown provides 3 potential sources of data - an existing taxonomy, a post type, or a custom filter. To populate your dropdown field using an ACF field and this filter,

add_filter( 'cf7sg_dynamic_dropdown_custom_options','dynamic_select_353_dynamic_options',10,3);
/**
* Filter dropdown options for dynamic drodpwn list of taxonomy terms.
* @param mixed $options the opttion to filter.
* @param string $name the field name being populated.
* @param string $cf7_key  the form unique key.
* @return mixed $options return either an array of <option value>=><option label> pairs or a html string of option elements which can be grouped if required.
*/
function dynamic_select_353_dynamic_options($options, $name, $cf7_key){
  $data = ... //fetch your data from your ACF field.
foreach($data as $label=>$value){
    $options += '<option value="'.$value.'">'.$label.'</option>';
  }
return $options;
}

Answer №3

If you find yourself in a situation where you need to populate a dropdown dynamically and want the value field to be different from the displayed text, such as using an ID instead of the name.

You can achieve this by incorporating the following code snippet:

function updateDropdownValues( array $tag ) {

    if ( $tag['name'] !== 'custom-dropdown' ) {
        return $tag;
    }

    $items = [] // Add your array of items retrieval code here

    foreach ( $items as $key => $item ) {
        $tag['raw_values'][] = $item['name'];
        $tag['values'][]     = $item['id'];
        $tag['labels'][]     = $item['name'];
    }

    $tag['raw_values'][] = 'Other';
    $tag['values'][]     = 0;
    $tag['labels'][]     = 'Other';

    return $tag;
}
add_filter( 'custom_form_tag', 'updateDropdownValues', 10 );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Protractor issue: Out of bounds error encountered when attempting to use a function for the second time

I encountered an issue with a function that selects a category from a list of available categories. The function worked perfectly in my initial test, but when I used it with a different valid category name for another test, it failed and displayed the foll ...

Tips for obtaining immediate model updates within Agility.js

I am currently facing an issue with Agility.js regarding the 'change' event. This event is triggered every time a model within the object is modified. However, in my case, the model only gets updated when losing focus or pressing enter. I would l ...

Does the inclusion of a d.ts file in a JavaScript npm package constitute a breaking change according to SemVer guidelines?

Is adding a d.ts type declaration file and a new "types" property in the package.json of a JavaScript npm package considered a breaking change? Would it require a major version bump according to SemVer? This situation could go either way. It doesn't ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

Switching the color scheme between mobile and desktop devices to make the background look

As a newcomer to threejs, I have just begun learning and developing with this technology. I am aware that certain features may be different on mobile browsers compared to desktop ones due to limitations. However, I have encountered an issue that I cannot s ...

What is the process for passing an error to the next function within a catch block using catch

It's not uncommon for me to come across code snippets like this app.get('/', function (req, res, next) { Promise.resolve().then(function () { throw new Error('BROKEN') }).catch(next) }) I've been trying to wrap my hea ...

What is the best way to display the JSON array received from Postman on my HTML page using jQuery's Ajax success function?

I need help in iterating through the JSON array that is fetched from my API [{"a":1},{"b":2},{"c":3},{"d":4}]. How can I extract and display only the key-value pairs on my HTML output div? <body> <div id = "result" style = "color:green" > ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

Obtain Data for Visualizing Graph with JSON within a Database-connected Graph (highchart.js)

In the process of creating a database-driven graph, I am utilizing libraries from Codepen. These libraries include: THIS and Highchart.js The HTML file on display simply showcases the chart, while the main data processing is handled in an index.js file t ...

One of the challenges faced with using AngularJS is that it can often

I have a piece of code that is functioning correctly: angular.module('foo', []).config( function($locationProvider) { $locationProvider.html5Mode(true); } ); However, when the code is minified, it gets compressed and looks like this: a ...

Ensure that your JQuery code only runs after Angular has completed its rendering

As a newcomer to Angular JS, I may have a question that seems silly. Despite seeing it discussed in several SO questions, I still couldn't figure it out. My goal seems simple, yet I've had a tough time achieving it. I'm attempting to execut ...

Utilize PHP within an HTML form for action without causing a redirection

I am working on an HTML form that looks like this: <form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php"> On the form, there is a submit button that triggers the verify() function: <a href="#" class="button1" onClick="v ...

The issue with Ajax success not functioning properly within nested .ajax calls

I encountered an issue with my nested ajax functions. The success code is triggered in the first ajax request (url: "get_hours.php"), but not in the second case (url: "send.php"). The code within "send.php" is executed correct ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

What is the best way to retrieve information from a JSON response obtained through JQuery?

Is there a way to access the JSON data returned in the complete function of a JQuery AJAX request? Here's an example to illustrate my question: $.ajax({ url: 'buildings.php', data: "building=" + building, complete: function (res ...

Remove JSON data in JavaScript

"[ "{\"StudentID\":5042,\"Status\":\"Joshua picked up from school [0] at 12:41PM and reached home [0] at 12:43PM\",\"Date\":\"2013-11-20\"}", "{\"StudentID\":5042,\"Status\":\" ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

Top method for transitioning FontAwsome stars class from regular to solid

How can I dynamically change the class of 5 stars of FontAwesome Icons from regular to solid based on a numeric variable level that ranges from 0 to 5? <template> <div id="five-stars"> <font-awesome-icon v-for="(inde ...

Shall we Combine JavaScript Files with Import and Require Statements?

Apologies for the vague description, I am trying to be concise while acknowledging my limited understanding and potential incorrect assumptions. I currently have a website that consists of one large HTML file with scripts defined in-line within <script ...