Hube2 / acf-dynamic-ajax-select-example

Examples of dynamically loading values with AJAX based on other fields
181 stars 56 forks source link

ACF JS Api #10

Open crtl opened 5 years ago

crtl commented 5 years ago

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;
    });
Hube2 commented 5 years ago

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.