acf-dynamic-ajax-select-example icon indicating copy to clipboard operation
acf-dynamic-ajax-select-example copied to clipboard

ACF JS Api

Open crtl opened this issue 7 years ago • 1 comments

Hello, your examples helped me a lot but I found the new ACF JS API which makes things just easy. Given the following example, all fields (supporting up to one repeater) will be just appended to the fields-key in the request:

    acf.addFilter("select2_ajax_data", function(data, args, $input, field, instance) {
        console.log("select2_ajax_data", arguments);

        var fields = acf.getFields();
        var fieldValues = {};

        for (var fieldKey in fields) {
            if (!fields.hasOwnProperty(fieldKey)) continue;

            var field = fields[fieldKey];

            if (fieldValues.hasOwnProperty(field.data.name)) {
                if (!Array.isArray(fieldValues[field.data.name])) {
                    fieldValues[field.data.name] = [fieldValues[field.data.name]];
                }

                fieldValues[field.data.name].push(field.val());
            } else {
                fieldValues[field.data.name] = field.val();
            }
        }

        data.fields = fieldValues;

        return data;
    });

crtl avatar Nov 06 '18 15:11 crtl

Yes, I have been playing with the new ACF JS API lately myself and the .val() method of the field helps with getting and setting values. If I have time to do new examples or update old examples I will probably incorporate it rather than work directly with field elements.

Hube2 avatar Nov 07 '18 12:11 Hube2