Support

Account

Home Forums Backend Issues (wp-admin) How can I send an additional field during ajax requests? Reply To: How can I send an additional field during ajax requests?

  • @radgh (or anyone else) could you help me with my situation please, which is even simpler than yours but still I haven’t been able to fully figure it out…

    So, in my case I only use one Post Object (cousin of Relationship), that pulls data from a hierarchical (parent-child) CPT. Very simple and stock up to here. Ah, the Post Object is within a Repeater, so that the admin will be able to add rows of Post Objects, but that doesn’t affect the case anyway.

    The problem is I want to prevent the admin who will use the system from choosing top categories (where parent=0), but rather choose only child categories, by disabling the top categories within the select2.

    At this point let me tell you, in case you don’t already know, that it’s a select2 stock functionality to disable specific options by adding a property disabled:true for that option.

    So, I did a lot of research and found that the only JS filter that is being triggered every time the select2 gets populated is acf.add_filter(‘select2_ajax_results’, function( json, params, instance ) (https://www.advancedcustomfields.com/resources/javascript-api/#filters-select2_ajax_results), where json param holds only the id and text properties of the results.

    For testing purposes I added a third param disabled:true to each option, and indeed all options where greyed out…

    add_action('acf/input/admin_footer', 'my_acf_input_admin_footer');
    function my_acf_input_admin_footer() {
        ?>
        <script type = "text/javascript">
        (function($) {
            // JS here
            acf.add_filter('select2_ajax_results', function(json, params, instance) {
                $.each($(json.results), function() {
                    $(this).prop("disabled", true);
                });
                return json;
            });
        })(jQuery);
        </script>
        <?php
    }

    The problem is I don’t know at the time select2_ajax_results filter gets triggered which options are top categories and which are children. So, I need somehow to add a third param, like top:true, to json at an earlier stage. But what filter would that be? Probably it should be server side, but what exactly filter?

    The following screenshot was taken with the test code above in place, which disabled ALL options…

    Screenshot

    Any insight would be greatly appreciated.