You are here

function svg_image_field_attach_presave in Svg Image 7

Implements hook_field_attach_presave().

When saving a entity, this hook is called to make any adjustments to the entire entity's fields before attempting to write to the database. When Image module encounters an SVG image, it sets the height and width values to be empty strings, which would cause a database constraint error when a string is inserted into an integer column.

This implementation loops through all fields attached to an entity, finds those that are an image field, then sets the width and height values within that field. These changes are made by reference, so they are in the $entity object when Field module saves to the database.

File

./svg_image.module, line 62

Code

function svg_image_field_attach_presave($entity_type, $entity) {

  // Get information about which fields are on this type of entity.
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $bundle_field_info = field_info_instances($entity_type, $bundle);

  // Loop through each of the fields and find those that are image fields.
  foreach ($bundle_field_info as $field_name => $instance_info) {
    $field_info = field_info_field($field_name);
    if ($field_info['type'] === 'image') {

      // Rely on locale API to retrieve the correct langcode
      $langcode = field_is_translatable($entity_type, $field_info) ? field_language($entity_type, $entity, $field_name) : LANGUAGE_NONE;
      if (!isset($entity->{$field_name}[$langcode])) {
        continue;
      }

      // Update the field values (by reference) for SVG images.
      $field_values =& $entity->{$field_name}[$langcode];
      foreach ($field_values as $delta => $field_value) {
        if (!isset($field_value['fid'])) {
          continue;
        }
        $file = file_load($field_value['fid']);
        if ($file && svg_image_is_svg($file->uri)) {

          // Set default 100x100 as a default values.
          $field_values[$delta]['width'] = SVG_IMAGE_DEFAULT_WIDTH;
          $field_values[$delta]['height'] = SVG_IMAGE_DEFAULT_HEIGHT;
          if ($svg_dimensions = svg_image_get_dimensions($file->uri)) {
            $field_values[$delta]['width'] = $svg_dimensions['width'];
            $field_values[$delta]['height'] = $svg_dimensions['height'];
          }
        }
      }
    }
  }
}