Create a Custom Ajax in form alter

29/07/2018


Hi i have a problem to create a custom ajax, i have the following code.

the problem is i cannot make the code working no response nothing working for ajax callback, is simple but i try to put i src but still dont works, any help for make this to work, thanks

use DrupalCoreDependencyInjectionContainerInjectionInterface;
use DrupalCoreEntityEntityTypeManagerInterface;
use DrupalCoreMessengerMessengerTrait;
use DrupalCoreStringTranslationStringTranslationTrait;
use SymfonyComponentDependencyInjectionContainerInterface; 
use DrupalCoreFormFormStateInterface;
use DrupalCoreAjaxAjaxResponse;
use DrupalCoreAjaxAppendCommand;
use DrupalCoreControllerControllerBase;
use DrupalCoreUrl;
use SymfonyComponentHttpFoundationResponse;


/**
 * Implements hook_form_alter().
 */
function custom_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_comandas_edit_form' || $form_id == 'node_comandas_form') {

    $form['#attached']['library'][] = 'custom_form/custom_form.library';

    foreach ($form['field_producto']['widget'] as $key => $value) {
      if (is_numeric($key)) {
        if ($value) {
          $valor_producto = $value['subform']['field_cantidad']['widget'][0]['value']['#default_value'] * $value['subform']['field_precio']['widget'][0]['value']['#default_value'];
          $total += $valor_producto;
        }
      }
    }

    // Wrap textfields in a container. This container will be replaced through
    // AJAX.

    // This form is rebuilt on all requests, so whether or not the request comes
    // from AJAX, we should rebuild everything based on the form state.
    // Checkbox values are expressed as 1 or 0, so we have to be sure to compare
    // type as well as value.


    $form['field_total']['widget'][0]['value']['#default_value'] = $total;
    $form['field_total']['#ajax'] = [
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element
      // changes.
      'callback' => '::custom_form_value_change',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'total-wrapper',
      'event' => 'click',
      'effect' => 'fade',
      'progress' => array(
        'type' => 'throbber',
        'message' => 'cargando',
      ),
    ];
  }
}

function custom_form_value_change($form, FormStateInterface $form_state) {
    $reponse = 'total-wrapper';
    //$response = new AjaxResponse();
    //$valor = 40000;
    //$response->addCommand(new HtmlCommand('total-wrapper', $valor));
    return $response;
  }

قالب وردپرس