Home Forums ACF PRO Relationship field save only last value


Relationship field save only last value

  • Good evening,

    I’m build a simple system with ACF and after going back and forth, I’m close to having a functional logic, entretando I came across a new problem, someone has an idea how I can solve?

    I’m using the ‘save_post validate’ and ‘save_my_data’ to obtain and process the data with AJAX, see:

    /* Função para validar e postar dados ACF via AJAX */
    	$('body').delegate('.acf-form-submit .acf-button','click',function(event){
    		/* Identifica div que receberá erros caso exista */
    		errorcontainer = '#error-'+ $(this).closest('.container-form').attr('parentid');
    		id= $(this).closest('.container-form').attr('id');
    		/* trigger de atualização */
    		/* Prepara campos para validação e submit */
    		var form_data = {'action' : 'acf/validate_save_post'};
    			$('#'+id+' > form#post :input').each(function(){
    				form_data[$(this).attr('name')] = $(this).val();
    		/* Verifica a validação */
    		$.post(ajaxurl, form_data).done(function(data){
    			/* Se existe erros */
    			if( > 0){
    				var msgerros = '';
    					$.each(, function(i,item) {
    						msgerros += '<li>'+item.message+'</li>';
    						var str = item.input;
    						var res = str.substr(4);
    						var fil = res.split(']')[0];
    						$( "*[data-key='"+fil+"']" ).addClass('alert').addClass('alert-danger');
    				/* Alerta de erro de validação do formulário */
    				$(errorcontainer).html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="fa fa-times-circle"/> Campos obrigatórios vazios:</h4><ul>'+ msgerros +'</ul></div>');
    				/* Alerta de salvamento de formulário */
    						$(errorcontainer).html('<div class="alert alert-info"><h4><i class="fa fa-times-circle"/> Salvando formulário... <span class="pull-right fa fa-asterisk fa-spin fa-2x"></span></h4></div>');
    					/* Salva dados do formulário */
    					form_data.action = 'save_my_data';, form_data)
    							vinculado = $('#'+id).attr('vinculado');	
    							typeform = $('#'+id).attr('typeform');	
    								/* Chama função que vincula id em post que aceite vinculo */
    								if (typeform=='new_post' && vinculado != null){
    									$.ajax( {			
    										url: ajaxurl,	
    										type: 'POST',		
    										cache: false,		
    										data:  {action: "quo_vinculoID", vinculado: vinculado, InId: save_data},			
    											success: function(dados) {	
    		 = "default";	
    											error: function(dados) {	
    												/* Informar Erro */
    		 = "default";	
    						/* Fecha Modal */
    						/* Dispara Gatilho */
    						triggerid = $(modalID).attr('gatilho');
    						$( "#"+triggerid ).trigger( "click" );

    My scripts work well for most of the fields (text, image, datapicker and others), but in the field of relationship and users, only the last selected value is saved.

    my scripts work well for most of the fields (text, image, datapicker and others), but in the field of relationship and users, only one value among the selected, this being saved. As my English is bad, below the video link that exemplifies the situation:

    I appreciate any guess

  • This is just a guess, but I believe your problem is here
    $('#'+id+' > form#post :input').each(function(){
    This is looping through the input fields, relationship and user fields are select fields and will not be selected. Textarea fields would also not be selected using $('#'+id+' > form#post :input')

  • John Huebner, Thanks for your suggestion, but I tested a few things in this direction and also can not get the desired result. Any suggestions for how should select any element of the form?

    Maybe it’s really the problem, but doing some ‘table tests’, get in console.log the values that are assigned or selected in the form fields.


    Already I disabled all the hooks and additional plugins, but nothing changes.

    Any other suggestions?

  • I’m not really an expert at using JS to get values from ACF fields, but then I doubt there are many. I’m just trying to give you ideas on how to possibly solve the problem.

    The other thing about relationship and user fields that may be causing you issues is that these are select2 fields which as far as I know don’t work quite the same normal select fields. Could that have something to do with it?

  • I’m also no expert, just a technical curious, and greatly appreciate your attention to this cause.

    One of the tests I have done was just go through the field of interest (by class, by id by name) yet, even giving ‘print’ in the log panel, the values are not saved and not shown in the relevant field.

    What amazes me most is the fact that the field values post-object and user ‘saved’ about to be removed from the list of options, but not to the point of being obtained with get.

    Interestingly, get these fields, only work when I do the exclusion of these fields in my group.

    The more I move, the farther I seem to be a solution to all fields.

    Again, thank you for your suggestions.

  • I just had some time to take a close look at how a relationship field works. When you add an item to the list an li element is added to the selected items. Each of these li items includes a hidden field that has the ID of the post as it’s value. So, there isn’t a single field that contains all of the values but a separate hidden field for each value.

    In order to get all of the input fields that hold the real values of a relationship field

    var $inputs = $('.acf-input .acf-relationship .values input[type="hidden"]');

    would return a list of input elements.

    The main problem I see with this part of your code

    var form_data = {'action' : 'acf/validate_save_post'};
    $('#'+id+' > form#post :input').each(function(){
      form_data[$(this).attr('name')] = $(this).val();

    is that the name attribute of each of these hidden fields is exactly the same, example: acf[field_574e05c19e01e][] so I’m guessing that each one overwrites the previous value which would explain why you are only getting the last value. Somehow in your loop you’re going to need to detect that the field values is part of an array and append it to the values already collected rather than set it.

    Since the user fields works in a similar manner I say that’s also the problem there.

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

You must be logged in to reply to this topic.