Support

Account

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

Solving

Relationship field – filter choices with AJAX

  • Hi all,

    Please help me to finish this, I think I am close, but I need some help.
    I have two relationship fields. I need to re-filter choices in second whenever first field value is changed. I know js, I can write those events and AJAX… That’s not a problem.

    For now I did this:

    function my_relationship_query( $args, $field, $post_id ) {
        $show_id = get_field('field_58186b547a1a6', $post_id, true);
        $args['meta_key'] = 'episodes_show';
        $args['meta_value'] = $show_id;
        return $args;
    }
    add_filter('acf/fields/relationship/query/key=field_58186bb77a1a8', 'my_relationship_query', 10, 3);

    And this is working, just you have to save to see the changes.
    Is there a simple way to solve this with AJAX? Do I have to query all posts in ajax php function and return as ‘choices’ JSON or there is some simpler way?

    One more question: there is AJAX call whenever you scroll choices to the bottom (or enter search). How to prevent those calls to repopulate choices with unwanted values?

    Thanks,
    Marko

  • I’m probably as close as you’ll get to an answer to this. The only real way to filter a relationship field is to use the acf/fields/relationship/query
    filter https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/

    Getting the value and doing your own custom AJAX request I can help you with. In the scenario you describe, and this is the part that I don’t know, you would need to figure out how to add the value of the selected post to the AJAX query that ACF is already doing. For that you’d probably need to do a lot of digging around in ACF JavaScript and I have no idea if it’s possible.

    If I were going to do this I might use a relationship field for the first choice but I would probably use a select field for the second field, only because it’s a whole lot easier.

    This example of mine shows how to populate other fields based on the selection in a relationship field https://github.com/Hube2/acf-dynamic-ajax-select-example/tree/master/dynamic-fields-on-relationship

    This example shows how to populate the choices of a select field based on a selection in another select field https://github.com/Hube2/acf-dynamic-ajax-select-example/tree/master/dynamic-select-example

    Like I said, I don’t know how to modify the AJAX request that ACF makes for a relationship field or how to trigger that request when another relationship field is changed. More than likely it’s possible, depending on your JS skills and how much time you want to spend digging through ACF to figure out how.

    Hope this helps in some way.

  • 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;
    	}
  • Thank you for posting this, I was unaware of the relationship_ajax_data filter which will make life easier for many I suspect.

  • There exist no relationship_ajax_result like for the select2 fields?? – is there another filter which i had to choose? Thanks for an answer.

  • It`s must be working, i use this code in my project.
    Can you show you code here?
    And maybe i can write you task?

  • Your documented filter relationship_ajax_data exists and its working perfect! But like i do it with the select2 fields to “change” my result, i want to do the same with the relationship field. But the _result doesnt exist and therefore i asked for a solution.

    My target is to “disable” options in one relationship field if this item is selected in another. Bases on the query i couldnt do this easy with HTML and it would be better to modify the result coming via AJAX.

  • Another problem is: How could i tell the relationship field to get only taxonomies and terms which are not empty OR based on the filtered posts.

    Actually all elements of my taxonomies are shown – not depending on the filtered posts. But i couldnt find a hook to filter the taxonomies for the relationship field. Actually i can only filter the posts. Is there a hack or workaound?

  • If you could show me your code, maybe I could help you.

  • If you want to change the output results from the select2 field, and set conditions on js, you need to do it differently. I’m sorry, I use a translator to communicate with you (I’m from Ukraine), so I may not fully understand your question correctly.

  • I have a piece of code that adjusts the query request for the select2 field through js

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

The topic ‘Relationship field – filter choices with AJAX’ is closed to new replies.