Skip to main content
4 of 5
deleted 123 characters in body; edited title
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

Show the value of a node-form field inside an AJAX field added via hook_form_alter()

I have created a simple content type "reservation" with an integer field called "field_km" with a default value of 50.
On the node creation form, I want to have a markup field showing the value of the "field_km" field. So, I have created a simple module with the following code:

/**
 * @file
 * Drupal Module : myresa
 * Adds custom code specific to this Drupal 7 site.
 */

function myresa_form_reservation_node_form_alter(&$form, &$form_state, $form_id) {
  $form[‘box’] = array(
    ‘#type’ => ‘markup’,
    ‘#prefix’ => ‘’,
    ‘#suffix’ => ‘’,
    ‘#markup’ => ‘Price not computed',
  );

  $form[‘mybtn’] = array(
    ‘#type’ => ‘button’,
    ‘#id’ => ‘mybtn’,
    ‘#ajax’ => array(
      ‘callback’ => ‘myresa_callback’,
      ‘wrapper’ => ‘box’,
      ‘name’ => ‘mybtn1’,
    ),
    ‘#value’ => t(‘Compute the price’),
  );
}

function myresa_callback($form, $form_state) {
  $element = $form[‘box’] ;
  $element[‘#markup’] = «The price for » . $form_element[‘field_km’][‘#default_value’] . » km is 35 euros» ;
  return $element ;
}

The form shows the 'box' markup, the button, and when clicked the button activates the callback and shows the wanted text, but not the value of 'field_km'. It is probably a simple syntax mistake, but it beats me.