You are here

function menu_link_field_formatter_prepare_view in Menu Link (Field) 7

Implements hook_field_formatter_prepare_view().

1 call to menu_link_field_formatter_prepare_view()
menu_link_field_formatter_view in ./menu_link.field.inc
Implements hook_field_formatter_view().

File

./menu_link.field.inc, line 353
Defines a menu link field type.

Code

function menu_link_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  $mlids = array();

  // Collect every possible menu link attached to any of the fieldable entities.
  foreach ($entities as $id => $entity) {
    foreach ($items[$id] as $delta => $item) {

      // Prevent notices in previews of unsaved entities.
      if (!empty($id)) {

        // Prevent doing things twice.
        if (!empty($item['mlid']) && empty($item['title'])) {

          // Force the array key to prevent duplicates.
          $mlids[$item['mlid']] = $item['mlid'];
        }
      }
    }
  }
  if (!empty($mlids)) {
    $menu_links = menu_link_load_multiple($mlids);

    // Iterate through the fieldable entities again to attach the loaded menu
    // link data.
    foreach ($entities as $id => $entity) {
      $rekey = FALSE;
      foreach ($items[$id] as $delta => $item) {

        // Prevent notices in previews.
        if (!empty($id) && !empty($item['mlid'])) {

          // Check whether the menu link field instance value could be loaded.
          if (isset($menu_links[$item['mlid']])) {

            // Replace the instance value with the menu link data.
            $items[$id][$delta] = $menu_links[$item['mlid']];
          }
          else {
            unset($items[$id][$delta]);
            $rekey = TRUE;
          }
        }
        if ($rekey) {

          // Rekey the items array.
          $items[$id] = array_values($items[$id]);
        }
      }
    }
  }
}