Support

Account

Home Forums Backend Issues (wp-admin) Relationship field – filter choices with AJAX Reply To: Relationship field – filter choices with AJAX

  • I managed to change the arguments for the relationship field, and get the result based on them. Task: I have Users, And I also have CPT Teams – when creating a user, I assign him a role, for example: Reporter and I, in the relation field, should pull up Teams whose selection field is equal to Reporter.

    JS:

    acf.addFilter('relationship_ajax_data', function (ajaxData, field){
    
                if(ajaxData.field_key == "field_63599162ef1ea"){
    
                    if($('body div[data-key="field_6315dc672e038"]').length > 0){
    
                        let roles = [];
    
                        $('body div[data-key="field_6315dc672e038"] .acf-checkbox-list li input').each(function (i,e){
                            if($(this).is(':checked')){
                                roles.push($(this).val());
                            }
                        });
    
                        ajaxData.meta_key = 'team_role';
                        ajaxData.meta_value = roles;
    
                    }
    
                    console.log(ajaxData);
    
                }
    
                return ajaxData;
            });

    PHP
    add_filter('acf/fields/relationship/query/name=user_teams', [$this, 'lh_acf_fields_relationship_query'], 10, 3);

    public function lh_acf_fields_relationship_query($args, $field, $post_id)
    	{
    
    		if(isset($_POST) && !empty($_POST)){
    
    			if(isset($_POST['field_key']) && $_POST['field_key'] == 'field_63599162ef1ea'){
    
    				if(isset($_POST['meta_key']) && !empty($_POST['meta_key']) &&
    					isset($_POST['meta_value']) && !empty($_POST['meta_value'])){
    
    					$args['meta_query'] = [
    						'relation' => 'AND',
    						[
    							'key' => sanitize_text_field($_POST['meta_key']),
    							'value' => $_POST['meta_value'],
    							'compare' => 'IN'
    						]
    					];
    
    				}
    
    			}
    
    		}
    
    		return $args;
    	}