Messed-up div IDs for ajax-modified form field I want to change, using Ajax, some attributes to field2 (a select widget) when field1 changes:

In mymodule.module:

function mymodule_form_NODETYPE_FORM_alter(&amp;$form, &amp;$form_state, $form_id) {
    $form['filed1']["widget"]['#ajax'] = array(
        'callback' =&gt; 'on_filed1_change',
        'wrapper' =&gt; 'edit-field-filed2-wrapper', 
        'event' =&gt; 'change',
        'method' =&gt; 'replace',
    );
}

function on_filed1_change(array $form, FormStateInterface $form_state)  {
    $form['field2'] = $modified_field2;
    return $form['field2'];
}


This works only the first time.

I found out the following id's have been changed with additional trailing random numbers:


edit-field-field2-wrapper--GCPg2vSCav0 for field2 wrapper &lt;div&gt;
edit-field-field2--EXhOuuWQld8 for field2 &lt;select&gt; element


Since the original Ajax wrapper edit-field-field2-wrapper no longer exists, no further modifications to field2 are possible.

Why does this happen? And how can I prevent this from happening, or use the new IDs as wrapper in the Ajax call?

I'm using 8.6.0-dev.
function mymodule_form_NODETYPE_FORM_alter(&amp;$form, &amp;$form_state, $form_id) {
    $form['field2']['#attributes']['id'] = 'my_dom_id_for_elem2';
    // or if it doesn't work properly you can wrap the element
    // $form['field2']['#prefix'] = '&lt;div id="my_dom_id_for_elem2"&gt;';
    // $form['field2']['#suffix'] = '&lt;/div&gt;';

    $form['filed1']["widget"]['#ajax'] = array(
        'callback' =&gt; 'on_filed1_change',
        'wrapper' =&gt; 'my_dom_id_for_elem2', 
        'event' =&gt; 'change',
        'method' =&gt; 'replace',
    ); }

function on_filed1_change(array $form, FormStateInterface $form_state) {
    // This line is not necessary, at this time $form['field2']
    // has already been modified and you can just return the form element itself, it will be used as response.data by javascript.
    //$form['field2'] = $modified_field2;
    return $form['field2']; 


}