I'm extracting IPTC and EXIF data when the user uploads an image using the Media Library UI.

Using hook_form_alter I can get the URI of the uploaded file in the media_library_add_form_upload form, and extract the data from it. So far, so good.

However, the form does not (yet?) contain the other fields attached to the media type (e.g. title, description, copyright) so I can't set the values.

How can I set the values in the form that is shown after I've selected and upload an image?

1 Answer 1


The form fields are nested under $form['media'][0]. Having extracted data from the uploaded file, we can set the data as default values on the fields.

 * Implements hook_media_form_alter().
function ds_media_exif_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id !== 'media_library_add_form_upload') {

  if (!array_key_exists('upload', $values)) {

  $upload_id = $values['upload'][0];
  $file = File::load($upload_id);
  $uri = $file->getFileUri();

  // Extract exif, iptc data here.
  $data = extractFileData($uri);

  // Title defaults to the file name.
  if (isset($data['title'])) {
    $form['media'][0]['fields']['name']['widget'][0]['value']['#default_value'] = $data['title'];
    // Set alt field to title.
    $form['media'][0]['fields']['field_media_image']['widget'][0]['#default_value']['alt'] = $data['title'];

  // Some more fields: field_description and field_copyright.
  $form['media'][0]['fields']['field_description']['widget'][0]['#default_value'] = $data['description'] ?: '';
  $form['media'][0]['fields']['field_copyright']['widget'][0]['value']['#default_value'] = $data['copyright'] ?: '';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.