I’m using Flexible Content (FC) as part of a page template; each “section” of the page is built using a FC field; within the FC is a “section ID” field, which needs to be unique within the page itself.
I’ve found different solutions for validating fields against each other on the same page (via $_POST[‘acf’]), but I’ve not come across a situation where there has been done when using Flexible Content. I have it partially working; it finds duplicates of the field and alerts the user that the field needs to be unique, but the problem I’m having is that it’s marking all of the fields of the field type that needs to be unique, whether or not it’s the field with the duplicate ID.
For example, I have a repeater field (key = field_1234) and within that repeater I have a text field for a unique section ID input (key = field_5678). When I use the following code…
function validate_unique_id( $valid, $value, $field, $input_name ) {
foreach ($_POST['acf']['field_1234'] as $row) {
if (in_array($row['field_5678'], $list)) {
$valid = 'There are duplicate '.$field['name'].' values';
break;
}
$list[] = $row['field_5678'];
}
return $valid;
}
add_filter('acf/validate_value/key=field_5678', 'validate_unique_id', 10, 4);
…and a user creates three sections, with two of those sections using the same section ID in the text field (key = field_5678)…in this case, because there are duplicates, it halts the save and alerts the user to the validation error, but instead of just highlighting the fields that contain the duplicate values, it highlights all of the section ID fields, even if they’re unique. Is there any way to modify the above code so that it only highlights the fields that contain duplicate IDs?
Any advice would be appreciated.