0

I am trying to activate an AJAX callback on every change by the user of a text_format field (which is part of a standard bundle edit form). The name of the field in the snippets below is field_reponse

The code works perfectly with other fields (dropdown, textfield), but not for the formatted text areas of type "text_format".

I suppose it is connected with the post-processing of CKEditor. Am I right ? In any case, is there a workaround?

    function MY_MODULE_form_node_shut2_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    // Autosave

    $form['field_reponse']['widget'][0]['#ajax'] = array(
            'callback' => 'Drupal\MY_MODULE\Form\FormAutosave::autosave',
            'event' => 'click',
            'wrapper' => 'autosave_ajax_placeholder',
            'progress' => array(
              'type' => 'throbber',
              'message' => NULL,
        ),
    );


  // Add placeholder for Ajax response markup
  $form['autosave_ajax_response'] = array(
            '#type' => 'html_tag',
            '#tag' => 'div',
            '#value' => t('Placeholder for ajax response'),
            '#attributes' => array(
              'class' => array('hidden'),
              'id' => array('autosave_ajax_placeholder'),
        ),
    );
    } 

    return $form;
}

The callback:

<?php

namespace Drupal\MY_MODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class FormAutosave {

  public static function autosave(array &$form, FormStateInterface $form_state) {

    // Load the shut2 and get changed form element
    $node = $form_state->getFormObject()->getEntity();
    //$curr_values = $form_state->getValues();
    //$triggering_element = $form_state->getTriggeringElement();
    //drupal_set_message($triggering_element));
    // Set and save node with new value for field
    //$node->set($triggering_element, $triggering_element['#value']);
    $node->set('field_reponse', $form_state->getValue('field_reponse'));
    $node->save();

    // Add an Ajax response to avoid error 
    $response = [
      '#markup' => t('Sauvegardé automatiquement !'),
    ];
    return $response;

  }

}
0

I think the event should be keyup not click.

  • Didn't work. Why did you think it would solve the problem? – Yellows Aug 12 '17 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.