Support

Account

Home Forums ACF PRO acf/validate_save_post on clone fields

Solving

acf/validate_save_post on clone fields

  • Is there a trick to get acf/validate_save_post to work on clone fields?

    My code works when the fields are in the primary field group, Exhibition Fields, but when I pull those fields out and create a separate Dates field group which is then cloned into the Exhibition Fields group it doesn’t create an error on validation and won’t save any new value:

    add_action('acf/validate_save_post', 'msfa_acf_validate_save_post', 10, 0);
    
    function msfa_acf_validate_save_post() {
    
    	$start = $_POST['acf']['field_5d49b2ff396b6'];
    	$start = new DateTime($start);
    
    	$end = $_POST['acf']['field_5d49b34a396b7'];
    	$end = new DateTime($end);
    
    	// check custom $_POST data
    		if ($start > $end) {
    			acf_add_validation_error('acf[field_5d49b34a396b7]', 'End Date should be later than Start Date');
    		}
    }
  • This is because when a field is cloned its field key is altered. The new key will likely be the a concatenation of the clone field’s key and the original field key. The $_POST indexes to the field may further be altered if this also is a sub field of a repeater, group or flex field.

  • Here is how I would work around this issue with the star field as an example. This will work for both cloned and non-cloned versions of the same field.

    
    $field_key = 'field_5d49b2ff396b6';
    foreach ($_POST['acf'] as $key => $value) {
      if (substr($key, -strlen($field_key)) === $field_key) {
        $start = new DateTime($value);
        break;
      }
    }
    

    If I was going to do this a lot then I’d probably build a function that searches the input to find the right value.

  • Not quite working. The original validates or throws the error but not the clone; tried to with the acf_add_validation_error function using acf[field_5d5b156507abc][field_5d5b156507abc_field_5d49b34a396b7] which is how it seems to be indexing but no luck.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘acf/validate_save_post on clone fields’ is closed to new replies.