Support

Account

Home Forums Backend Issues (wp-admin) ACF Javascript API dynamic elements not saved

Solving

ACF Javascript API dynamic elements not saved

  • Hello!
    I want to dynamically add “options” to a “select” field using Javascript.
    I achieved it, but after saving the page, the selected option is lost and not saved in the database.
    This is my code:

    
    acf.add_action('load_field/key=${key}', () => {
        getElements().then((element) => {        
            const selector = document.querySelector('[data-key=${key}]').querySelector('select');
            for (let i = 0; i < element.length; i++) {
                let opt = document.createElement('option');
                opt.value = element[i].id;
                opt.innerHTML = element[i].description;
                selector.appendChild(opt);
            }
        });
    })
    
  • You need to do one of 2 things.

    1) You need to add an acf/update_value filter on the field. In this filter you need to add new choices to the field and call acf_update_field(). See the code for the radio field type.

    2) Add an acf/prepare_field filter that checks the field value against the allowed choices and add values to choices for those that don’t already exist.

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

You must be logged in to reply to this topic.