You are here

function managed_file_element_submit in Managed File 7

Submit managed file.

Parameters

array $element: Form element. Needed to obtain submitted values.

array $form_state: Drupal form state.

string[] $file_usage: An array of arguments (module, type, id) for file_usage_add().

1 call to managed_file_element_submit()
managed_file_test_form_submit in tests/managed_file_test/managed_file_test.module
Implements hook_form_submit().

File

includes/managed_file.common.inc, line 298
Auxiliary functionality.

Code

function managed_file_element_submit(array $element, array &$form_state, array $file_usage) {
  if (!empty($element['#parents']) && !empty($element['#value']) && count($file_usage) >= 3) {

    // Load file by MD5 hash and return it instead of ID.
    $use_md5 = function_exists('file_md5_load_file');
    $value = $element['#value'];

    // Image style.
    $style = '';

    // File ID or MD5 hash.
    $fid = 0;
    $file_load = function ($argument) use ($use_md5) {
      $id = is_array($argument) ? $argument['fid'] : $argument;
      return empty($id) ? FALSE : ($use_md5 ? file_md5_load_file($id) : file_load($id));
    };
    $file_operation = function ($op, \stdClass $file) use ($file_usage) {
      call_user_func("file_{$op}", $file);
      array_unshift($file_usage, $file);

      // @see file_usage_add()
      // @see file_usage_delete()
      call_user_func_array('file_usage_' . ('save' === $op ? 'add' : 'delete'), array_slice($file_usage, 0, 5));
      return $file;
    };
    $file = $file_load($value);

    // File is attached and should be saved.
    if (FALSE !== $file) {
      $file->status = FILE_STATUS_PERMANENT;
      $file_operation('save', $file);
      $fid = $use_md5 ? $file->md5 : $file->fid;
    }
    elseif (!empty($data)) {
      $file = $file_load($data);
      if (FALSE !== $file) {
        $file_operation('delete', $file);
      }
    }

    // An image style should be saved only if file present.
    if (!empty($value['style']) && !empty($fid)) {
      $style = $value['style'];
    }
    $values =& drupal_array_get_nested_value($form_state['values'], $element['#parents']);
    if (empty($element['#extended'])) {
      $values = $fid;
    }
    else {
      $values = [
        'fid' => $fid,
        'style' => $style,
      ];
    }
  }
}