Support

Account

Home Forums Backend Issues (wp-admin) Use Select2 instead of browser dropdown

Solving

Use Select2 instead of browser dropdown

  • We’re using a custom select field for our data. How can we make ACF use Select2 for the UI?

    
    public function render_field($field)
    {
        $field['type'] = 'select';
        $field['ui'] = 0;
        $field['ajax'] = 0;
        $field['multiple'] = 0;
        $field['allow_null'] = 0;
        $field['choices'] = '...redacted...';
    
        acf_render_field($field);
    }
    
  • Is this a custom field type that you are creating?

    I’m not sure that you can use it where you want to use it as this may require adding custom AJAX calls to return the information, however, I don’t know this at all since I’ve never tried to use a select2 field for a custom field type, you’d have to test it to find out.

    At any rate

    
    $field['ui'] = 1;
    
  • I think this needs some kind of JavaScript code to work and not just setting ui to 1 the select doesn’t render.

  • Like I said, it looks like your building a custom field type. I would look at existing field types in ACF to see how the developer does whatever it is that you’re trying to do.

  • I came across this same issue and while it can certainly be solved with custom javascript, I found another way that requires no extra js.

    I noticed that acf_render_field($field) for a custom field type, doesn’t initialize it into a select2 field with just 'ui' => 1 in the args.

    However acf_render_field_wrap($field) DOES automatically initialize select2 when the ui is set to true. The downside here is you have unnecessary nested field wrappers. So I kept digging and all it really boiled down to was needing a simple div with the necessary classes & data attributes. Then ACF is already looking for those and is the ui is also set to a true value… BOOM, select2 is initialized and works great!

    Here’s a stripped down code example of it working with a new custom field type:

    function render_field( $field ) {
    
    $field['type']     = 'select';
    $field['ui']       = 1;
    $field['choices']  = [
      'red'    => 'Red',
      'green'  => 'Green',
      'blue'   => 'Blue',
      'yellow' => 'Yellow',
    ];
    
    // Div with necessary classes/attributes to init Select2
    echo "<div class='acf-field acf-field-select' 
               data-name='{$field['label']}' 
               data-type='select' 
               data-key='{$field['key']}'>";
    
    acf_render_field($field);
    
    echo "</div>";
    
    }

    Hope that helps, good luck!

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Use Select2 instead of browser dropdown’ is closed to new replies.