thierry-b
12/16/2014 - 8:42 AM

Add file size to description or filename of a file field.

Add file size to description or filename of a file field.

<?php
function __format_file_size($size, $display_bytes = false) {
  if($size < 1024) {
    $filesize = $size . ' bytes';
  }
  elseif($size >= 1024 && $size < 1048576) {
    $filesize = round( $size/1024, 2 ) . ' KB'; 
  }
  elseif($size >= 1048576) {
    $filesize = round( $size/1048576, 2 ) . ' MB';
  }
  if($size >= 1024 && $display_bytes) {
    $filesize = $filesize . ' (' . $size . ' bytes)';
  }
  return $filesize;
}

//FIELD PREPROCESSING 
function the_aim_theme_process_field(&$variables) {
  // list of field names to add file size to
  $field_add_filesize = array(
    'field_file'
  );

  if(in_array($variables['element']['#field_name'], $field_add_filesize) && $variables['element']['#field_type'] == 'file') {

    foreach($variables['items'] as $key => $val) {

      if(!empty($val['#file']->description)) {
        $val['#file']->description = $val['#file']->description . " (" . __format_file_size($val['#file']->filesize) . ")";
      }
      else {
        $val['#file']->filename = $val['#file']->filename . " (" . __format_file_size($val['#file']->filesize) . ")";
      }

    }

  }
}