1

This is a continuation of this issue, where I couldn't get the ajax to fire on an entity reference field in a node edit form. With the following code, I'm able to get the ajax to fire.

/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function mymodule_form_blog_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_video_reference']['#ajax'] = array(
    'callback' => 'mymodule_video_ajax_callback',
    'wrapper' => 'my-path-div',
  );

  $form['my_path'] = array(
    '#markup' => t('My path'),
    '#prefix' => '<div id="my-path-div">',
    '#suffix' => '</div>',
    '#weight' => 6,
  );

  if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = 'Token path: http://www.mysite.org/node/' . $form_state['node']->field_video_reference['und'][0]['target_id'];
  }
}

function mymodule_video_ajax_callback($form, $form_state) {
  return $form['my_path'];
}

The problem is that the value from field_video_reference isn't being passed to the if statement in the form builder or my callback, so the value from that field isn't displayed in the my_path field when the value is first selected on the node create form (it works fine if the node has already been saved and there is a value in field_video_reference when I edit the node). I'm following examples from the "Drupal 7 Module Development" book as well as from the Examples module, so I can't see what I'm missing.

Thanks.

0

$form_state['values']['field_video_reference']['und'][0]['target_id'] looks wrong to me.

I would expect the value to be in $form_state['values']['field_video_reference'].

If you haven't already then install the Devel module and then use can use dpm($form_state); to output the array to the message area and inspect it to find the correct path.

Sometimes for ajax requests Devel Debug Log is also useful as it allows you to send a dump of a variable to a log so you can inspect it even if it is not possible to send content to the message area.

  • With Xebug and PHPStorm, I've used my debugger to inspect every available variable in just about every place possible. – wonder95 Mar 25 '14 at 18:28
0

Try to replace with the code

if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = t('Token path: http://www.example.com/node/' . $form_state['node']->field_video_reference['und'][0]['target_id']);
  }

The issue was that you need to put every content of #markup into the t('text') function.

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.