Support

Account

Home Forums Add-ons Repeater Field Associating Admin Defined Repeaters to user meta Reply To: Associating Admin Defined Repeaters to user meta

  • 1) To obtain a specific row by the value of its subfield, you have to iterate through all rows.

    function retrieve_row( $fieldNameOrArray, $subfieldName, $searchValue, $post_id = false ) {
    	
    	if ( is_array( $fieldNameOrArray ) )
    		$field =& $fieldNameOrArray;
    	else
    		$field = get_field( $fieldName, $post_id );
    	
    	if ( !$field || !is_array( $field ) || !isset( $field[0][ $subfieldName ] ) )
    		return false;
    	
    	foreach ( $field as $index => $row ) {
    		if ( $row[ $subfieldName ] == $searchValue )
    			return $row;
    	}
    	
    	return false;
    	
    }
    
    // Example
    $row = retrieve_row( 'repeaterFieldName', 'uniqueId', 'gold' );
    // Or if you already have the field loaded into a variable
    $row = retrieve_row( $repeaterFieldArray, 'uniqueId', 'gold' );

    To enforce unique values in a particular subfield, you need to place a script on the repeater field’s instructions:

    <script>
    jQuery( function() {
    	
    	// Definitions
    	
    	var repeaterFieldName = 'repeater',
    		uniqueFieldName = 'unique_id',
    		$repeaterFieldEl = jQuery( '.field.field_type-repeater[data-field_name="' + repeaterFieldName + '"]' );
    		
    	// Validation
    		
    	jQuery(document).on( 'acf/validate_field', function( event, $el ) {
    		
    		var fieldName = $el.data('field_name'),
    			fieldValue,
    			$uniqueFieldList,
    			$uniqueInputs;
    			
    		if ( fieldName != uniqueFieldName )
    			// Skip fields other than the unique one
    			return;
    		
    		fieldValue = $el.find('input[type=text], input[type=number]').val();
    		
    		if ( !fieldValue )
    			return;
    		
    		$uniqueFieldList = $repeaterFieldEl.find( '.row > .sub_field[data-field_name="' + uniqueFieldName + '"]' );
    		$uniqueInputs = $uniqueFieldList.find('input[type=text], input[type=number]');
    		
    		// Compare against other unique fields
    		$uniqueInputs.each( function( n, currentEl ) {
    			if ( $uniqueFieldList[n] === $el[0] ) {
    				// Skip comparing against self
    				return;
    			}
    			if ( currentEl.value == fieldValue ) {
    				// Not unique
    				$el
    					.data( 'validation', false )
    					.data( 'validation_message', 'This field must have a unique value.' );
    			}
    		});
    		
    	});
    	
    });
    </script>

    Just set the repeaterFieldName and uniqueFieldName at the beginning to something appropriate, and make sure that your unique field is required, or the validation will not run.

    2) Perhaps you should create another ACF group with those same fields and associate it to users. Now the fields will exist in the user meta. When you use update_field(), pass the field name, not the key, as the key is going to be different.