function menu_link_field_update in Menu Link (Field) 7
Implements hook_field_update().
File
- ./
menu_link.field.inc, line 227 - Defines a menu link field type.
Code
function menu_link_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
// Load the field items as they are stored in the database before update.
$original = entity_create_stub_entity($entity_type, array(
$id,
$vid,
$bundle,
));
field_attach_load($entity_type, array(
$id => $original,
), FIELD_LOAD_CURRENT, $options = array(
'field_id' => $field['id'],
));
// Initially asume that all links are being deleted; later on in this function,
// links that are kept are removed from this array.
$delete_links = array();
if (!empty($original->{$instance['field_name']}[$langcode])) {
foreach ($original->{$instance['field_name']}[$langcode] as $item) {
$delete_links[$item['mlid']] = $item['mlid'];
}
}
$path = _menu_link_path($entity_type, $entity, $langcode);
foreach ($items as $delta => &$item) {
if (empty($field['settings']['link_path_field']) || empty($item['link_path'])) {
$item['link_path'] = $path;
}
// If the options array was serialized on a previous insert or update,
// unserialize it back to an array for menu_link_save().
if (isset($item['options']) && is_string($item['options'])) {
$item['options'] = unserialize($item['options']);
}
// If field is not translatable, make menu item same language as entity.
if (!$field['translatable'] && !empty($entity->language)) {
$item['language'] = $entity->language;
$item['options']['langcode'] = $entity->language;
}
if (!menu_link_save($item)) {
drupal_set_message(t('There was an error saving the menu link.'), 'error');
// TODO what to do?
}
else {
// Workaround, menu_link_save during entity creation process
// can lead to incomplete cache entries, let's discard those.
$cid = "field:{$entity_type}:{$entity->id}";
cache_clear_all($cid, 'cache_field');
}
$item['options'] = serialize($item['options']);
// Don't remove menu links that are being kept.
unset($delete_links[$item['mlid']]);
}
// Delete any menu links that are no longer used.
if (!empty($delete_links)) {
menu_link_delete_multiple($delete_links);
}
}