Skip to content

Instantly share code, notes, and snippets.

@AndreKelling
Last active May 2, 2023 06:51
Show Gist options
  • Select an option

  • Save AndreKelling/8968ff5195f7b7ad78356d2fa820045d to your computer and use it in GitHub Desktop.

Select an option

Save AndreKelling/8968ff5195f7b7ad78356d2fa820045d to your computer and use it in GitHub Desktop.
ACF Repeater validator for relay prices
<?php
/**
* based on https://gist.github.com/sudarshann/66c55e48f1e36fb5412261d869976dc7
*
* sorry for german wordings inside!
*/
class AndrekellingthemeAcfValidateStaffelpreis {
public function __construct() {
add_filter('acf/validate_value/name=prices', [$this, 'acf_validate_staffelpreis'], 10, 4);
}
function acf_validate_staffelpreis($valid, $value, $field, $input_name) {
// Bail early if value is already invalid.
if ($valid !== true) {
return $valid;
}
$result = self::validate_staffelpreis($value, $field['key']);
if( !empty($result) ){
return $result;
}
return true;
}
function validate_staffelpreis($current_rows, $fieldKey) {
$lowDayCount = 0;
$tagespreis = (float) get_field('tagesmiete', $_POST['post_id']);
$highPrice = $tagespreis;
$index = 0;
// acf_reset_validation_errors is not correctly removing error messages in any case. especially when editing another field, then the error message is on.
acf_reset_validation_errors();
foreach ($current_rows as $current_row) {
$current = array_values($current_row);
$currentKeys = array_keys($current_row);
$currentDayCount = (float) $current[0];
$currentPrice = (float) $current[1];
$fieldSelectorDay = "acf[$fieldKey][row-$index][$currentKeys[0]]";
$fieldSelectorPrice = "acf[$fieldKey][row-$index][$currentKeys[1]]";
$index++;
if(1 >= $currentDayCount){
acf_add_validation_error($fieldSelectorDay , 'Dieser Tag-wert ist nicht korrekt.' );
return 'Tage-wert muss größer 1 sein.';
}
if($lowDayCount >= $currentDayCount){
acf_add_validation_error($fieldSelectorDay , 'Dieser Tag-wert scheint nicht korrekt.' );
return 'Tage-wert muss ansteigend verlaufen, also größer werden.';
}
$lowDayCount = $currentDayCount;
if($tagespreis <= $currentPrice){
acf_add_validation_error($fieldSelectorPrice , 'Dieser Preis ist nicht korrekt.' );
return 'Preis-wert muss kleiner als der Tagespreis sein.';
}
if($highPrice <= $currentPrice){
acf_add_validation_error($fieldSelectorPrice , 'Dieser Preis scheint nicht korrekt.' );
return 'Preis-wert muss absteigend verlaufen, also kleiner werden.';
}
$highPrice = $currentPrice;
}
return false;
}
}
@AndreKelling
Copy link
Copy Markdown
Author

To make this repeater fields values valid under each other in that post.

It's about relay prices.

prices is the repeater field.
In there we have 2 subfields per row. Which are day and price

  • days shall increase per row
    • and be higher than 1
  • price shall decrease per row
    • and be higher than the one day price "tagesmiete"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment