You are here

function entityreference_autofill_form_autofill in Entity reference autofill 7

AJAX callback for entity selection.

Return value

array Array of AJAX commands.

2 string references to 'entityreference_autofill_form_autofill'
entityreference_autofill_field_attach_form in ./entityreference_autofill.module
Implements hook_field_attach_form().
entityreference_autofill_field_widget_form_alter in ./entityreference_autofill.module
Implements hook_field_widget_form_alter().

File

./entityreference_autofill.module, line 206
Entity reference autofill module.

Code

function entityreference_autofill_form_autofill($form, $form_state) {

  // Need entity type to continue.
  if (!isset($form_state['entityreference_autofill']['#element_info'])) {
    return;
  }
  $element_info = $form_state['entityreference_autofill']['#element_info'];
  $entity_type = $element_info['#entity_type'];

  // @todo Will bundle always be set? Check with user entity.
  $bundle = isset($element_info['#bundle']) ? $element_info['#bundle'] : $entity_type;
  if (!isset($form_state['entityreference_autofill'][$entity_type][$bundle])) {

    // Nothing to return.
    return;
  }

  // Load field names and their mapped wrapper ids.
  $parents = !empty($element_info['#field_parents']) ? $element_info['#field_parents'] : array();
  $autofill_wrapper_map = drupal_array_get_nested_value($form_state['entityreference_autofill'][$entity_type][$bundle], $parents);

  // No values to fill.
  if (!$autofill_wrapper_map) {
    return;
  }

  // Build AJAX replace commands.
  $field_parent = drupal_array_get_nested_value($form, $parents);
  $commands = array();
  foreach ($autofill_wrapper_map as $field_name => $wrapper_id) {

    // Attach status messages to fields.
    if ($messages = theme('status_messages')) {
      $field_parent[$field_name]['messages'] = array(
        '#markup' => '<div class="views-messages">' . $messages . '</div>',
      );
    }
    $commands[] = ajax_command_replace('#' . $wrapper_id, drupal_render($field_parent[$field_name]));
  }

  // Allow other modules to add additional
  // ajax commands to return on an autofill
  // callback.
  // @see entityreference_autofill.api.php
  $context = array(
    'form' => $form,
    'form_state' => $form_state,
  );
  drupal_alter('entityreference_autofill_ajax_commands', $commands, $context);
  return array(
    '#type' => 'ajax',
    '#commands' => $commands,
  );
}