acf-dynamic-ajax-select-example
acf-dynamic-ajax-select-example copied to clipboard
ACF JS Api
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;
});
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.