Skip to main content

How to prevent editing of media files from the node edit form

Media module comes with the media widget, by default this includes an 'Edit Media' button that allows the user to edit other fields on the file from the node edit form. This post covers removing the edit button from the media widget.

by lee.rowlands /

How media works

Media module implements hook_element_info to return a new element 'media'. This is a form element like 'textfield', 'select' etc. A form alter or a hook_field_attach_form implementation won't have a chance to remove the 'Edit' button because at that stage the media element has not been processed, it's still '#type' => 'media'.

Enter hook_element_info_alter

hook_element_info_alter allows your module to modify the form element after media module has 'processed' it. Drop something like this into a custom module:

/**
 * Implements hook_element_info_alter().
 */
function mymodule_element_info_alter(&$types) {
  $types['media']['#pre_render'][] = 'mymodule_media_pre_render';
}

/**
 * Pre-render callback
 */
function mymodule_media_pre_render($element) {
  $element['edit']['#access'] = FALSE;
  return $element;
}

Enable your module and reload the page - the edit button will be removed.