orodruim
orodruim

Reputation: 23

Populate a select from another in Wordpress and CF7

I'm using Contact form 7 pugin in Wordpress. I need to populate a Select field with "crops" that are in a MySQL DB, and depending of the chosen one, a second Select has to be populated with this crop's "variety.

I know that using CF7 conditional fields it is possible, but there are 53 crops and more than 400 variety. So, it would be a lot of fields in DB and in the contact form.

I think it should be done using ajax, but I have no idea about this, and I can not find any example to learn using ajax + CF7 + Wordpress. What I would like to do is make a query to MySQL (Select variedad from cultivos where cultivo = 'id_cultivo') and populate the select with the result.

Does anyone know how I can do this?

Upvotes: 2

Views: 3448

Answers (2)

orodruim
orodruim

Reputation: 23

I have done the following lines in order to solve my trouble:

In js file:

    jQuery(document).ready(function($) {
     $("#idsubfamilia").change(function(e) {


                 e.preventDefault();
         jQuery.post(MyAjax.url, {action : 'buscar_posts' ,cadena : $('#idsubfamilia').val() }, function(response) {
//                $('#variedad_container').hide().html(response).fadeIn();
$('#variedad_container').hide().html(response).fadeIn();
            });
    });

});

In functions.php (thanks to http://masquewordpress.com/como-utilizar-ajax-correctamente-en-wordpress/):

/* AJAX */

// Primero incluimos nuestro archivo javascript definido anteriormente
wp_enqueue_script( 'mi-script-ajax',get_bloginfo('stylesheet_directory') . '/js/ajax-search.js', array( 'jquery' ) );

// ahora declaramos la variable MyAjax y le pasamos el valor url (wp-admin/admin-ajax.php) al script ajax-search.js
wp_localize_script( 'mi-script-ajax', 'MyAjax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );

//Para manejar admin-ajax tenemos que añadir estas dos acciones.
//IMPORTANTE!! Para que funcione reemplazar "buscar_posts" por vuestra action definida en ajax-search.js

add_action('wp_ajax_buscar_posts', 'buscar_posts_callback');
add_action('wp_ajax_nopriv_buscar_posts', 'buscar_posts_callback');

function buscar_posts_callback() {

        global $wpdb;
    $subfamilia=$_POST['cadena'];
    //$datos = $wpdb->get_results('SELECT id, subfamilia_' . $idioma . ' FROM wp_custom_subfamilias  ORDER BY subfamilia_' . $idioma);
    $datos = $wpdb->get_results("SELECT variedad FROM wp_custom_variedad where subfamilia_fk='".$subfamilia."' ORDER BY variedad");

     echo '<ul>';
echo '<select name="selectVariedad" id="idSelectVariedad">';
    foreach ($datos as $dato) {


       echo "<option value='".$dato->variedad."'>".$dato->variedad."</option>";


    }
echo '</select>';
     echo '</ul>';
    die(); // Siempre hay que terminar con die

}

Upvotes: 0

Aurovrata
Aurovrata

Reputation: 2279

I need to populate a Select field with "crops" that are in a MySQL DB

Use a dynamic dropdown field from the Smart Grid plugin extension for CF7.

It allows you to populate your dropdown using either a set of existing post or a taxonomy, else iit also has the ability to populate using a hook, so you can build a custom sql if your 'crops' are in a custom table.

and depending of the chosen one, a second Select has to be populated with this crop's "variety.

so this is trickier. The dynamic dropdown populated using a taxonomy allows you to build a jquery select2 dropdown which makes it much easier to search through long lists of options, furthermore, if your taxonomy is hierarchical (2 level deep), it will use the parent level terms as option groups in the dowdown and actual options will be the child terms. Hence you could organise your 'crops' and 'varieties' as a taxonomy of parent->child terms. Crops that have no variety would simply have itself as a variety, and your dropdown would allow users to select a variety within a specific category.

This would make it simpler to setup on your form, without the requirement of hidden dropdowns. It is also a lot more scalable & maintainable, as whenever you update your crop/variety terms, it is dynamically reflected in the form without having to change your form.

I hope all the above makes sense. If you wish to explore this further, you can post on the plugin support forum.

Upvotes: 1

Related Questions