• Resolved Arnoud Klaren

    (@aklaren)


    We would like to fill a multiple select2 field with values from a database query instead of fixed values. A bit like the “Select (CPT)” field type, but then multiple select2 and more flexible. Is this possible?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Georgian Cocora

    (@raster02)

    Hello @aklaren,

    This can be done through custom code only. Here’s an example:

    add_filter('wppb_select2_labels_array', 'wppbc_custom_select_values', 10, 5); 
    add_filter('wppb_select2_options_array', 'wppbc_custom_select_values', 10, 5); 
    function wppbc_custom_select_values($values, $field, $form_location, $user_id, $request_data) {   
    
       if ($field['meta-name'] == 'my_custom_code_select') {      
          $values = array('one', 'two', 'three');     
       }      
    
       return $values;
    
    }

    Replace my_custom_code_select with the meta name of the field you want to target. Then you just need to grab the values you want to display and return them in an array.
    To have different labels and values, you need to hook a separate function on each filter.

    Regards.

    Thread Starter Arnoud Klaren

    (@aklaren)

    Thanks for the example. I finally got it working. Unfortunately, there were 2 problems with the example:

    1. It seems that the webhooks wppb_select2_labels/options_array only take 1 argument (only the $value array) instead of 5 arguments in the sample (the webhooks for the normal select field wppb_select_labels/options_array do take 5), so I cannot check on the $field[‘meta-name’]. I managed to work-around this by setting the (static) option value (in the form field) to the meta-name, checking this in the webhook and overwriting it with the values from the database;
    2. It seems that the multiple select2 field uses another webhook (named wppb_select2_multiple_labels/options_array), so initially the dropdown was still not populated with the database values. These webhook also take only 1 argument.

    And one tip for others: if the labels are the same as the option values, then you only need the wppb_select*_options_array webhook version.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Select2 field from database table’ is closed to new replies.