drupaldrupal-10

Drupal 10 is not updating ajax form field value for change event when field is not disabled


I am encountering an issue with Drupal and AJAX where a field is not updating its value when it's enabled but works when it's disabled.

 function my_module_form_node_event_video_edit_form_alter(&$form, FormStateInterface $form_state) {
  add_video_ajax($form, $form_state);
}

function add_video_ajax(&$form, &$form_state) {

  // add ajax callback to Video ID field
  $form['field_video_id'] ['widget'] [0]['value']['#ajax'] = [
    'callback'  => 'ajax_callback',
    'event' => 'change',
    'wrapper' => 'replace-container',
  ];


  $form['field_aspect_ratio'][ '#prefix'] = '<div id="replace-container">';
  $form['field_aspect_ratio'][ '#suffix'] = '</div>';


  $value = $form_state->getValue('field_video_id');
  $value = isset($value[0]) ? $value[0]['value']: NULL;

  if($value){
    $form['field_aspect_ratio'] ['widget']['#default_value'] = $value;
  }
}



function ajax_callback($form, $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(
    new ReplaceCommand( '#replace-container', $form['field_aspect_ratio'])
  );
  return $response;
}

This code is not working because updating field is not disabled. I want without disable( $form['field_aspect_ratio'][ '#disabled'] = true;) this code work because I want to allow user manually select this field drop down.


Solution

  • If it is not possible I have a plan to use another way

    function ajax_callback($form, $form_state) {
      $response = new AjaxResponse();
      $response->addCommand(
        new InvokeCommand( 'selector', 'method', 'arguments')
      );
      return $response;
    }
    

    //js

     $.fn.method = function(data) {
       //will work here
      });