Home › Forums › Add-ons › Repeater Field › Question about deleting a row from repeater with acf javascript api
Hello,
I have the following question and have already worked out some code but it doesn’t seem to work completely.
I have a repeater called labels and have a repeater called data_rows in this repeater there is another repeater called data.
I would like that when I add or remove a row in the repeater labels that it also does that in every repeater data for every row in the repeater data_rows
Now I have the adding working but when I remove one my javascript crashed.
Does anyone have an idea how I can do this?
Below you can find the javscript.
Thanks in advance.
(function($) {
function syncDataRepeaters( type = '' ) {
// Get the labels field using ACF's API
const labelsField = acf.getField('field_683346e30acc7');
if (!labelsField) {
console.warn('Labels field not found');
return;
}
const labelCount = labelsField.$rows().length;
// Get the main repeater: data_rows
const dataRowsField = acf.getField('field_68584dfaa3ed5');
if (!dataRowsField) {
console.warn('data_rows field not found');
return;
}
// For each row in data_rows
dataRowsField.$rows().each(function(index, rowEl) {
const $row = $(rowEl);
// console.log( 'data data_rows found', $row );
const dataRepeaters = acf.findFields({
key: 'field_68584e03a3ed6', // inner repeater field name
parent: $row
});
dataRepeaters.each(function(index, dataItem) {
const $el = $(dataItem);
const dataField = acf.getField($el);
if (!dataField) return;
if( type === 'add' ) {
dataField.add();
}
if( type === 'remove' ) {
acf.removeAction('remove', onRemove);
dataField.remove();
setTimeout(() => {
acf.addAction('remove', dataField);
}, 50);
}
});
});
}
// Run when new fields are added
acf.addAction('append', function($el) {
// Check if the appended element is your labels field (field_683346e30acc7)
const isLabelsField = $el.closest('.acf-field[data-key="field_683346e30acc7"]').length > 0;
if (isLabelsField) {
syncDataRepeaters('add');
}
});
function onRemove($el) {
console.log('remove');
console.log($el);
const isLabelsField = $el.closest('.acf-field[data-key="field_683346e30acc7"]').length > 0;
console.log( isLabelsField );
if (isLabelsField) {
setTimeout(() => {
syncDataRepeaters('remove');
}, 10);
}
}
acf.addAction('remove', onRemove);
})(jQuery);
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.