Search code examples
imagedrupalentitiesalt

Drupal 7 - Image alt and title text bulk change for existing elements


I have a Drupal commerce website with about 100 000 products. Now customer wants me to change product image filenames and add alternative(alt) texts to images for all existing products - based product names and colors.

File field paths seemed to be great to changing the file names of image files. But I just cannot figure out how to add alt texts to images automatically. I've been trying hook_file_update, hook_file_presave, hook_entity_presave etc. I'm trying to add alt text during File field paths' batch update and all of the hooks are running but for some reason alt text data is not saved to entity.

Product image field is type of Image with Media browser widget.

Any help for this?

Here's hook_entity_presave() code:

if ($entity->type == 'image' && (empty($entity->alt) || empty($entity->field_file_image_alt_text))) {
$product = _get_referenced_product($entity->fid);
if ($product) {
  $full_product = commerce_product_load($product->product_id);
  $title = $full_product->title;

  if (!empty($full_product->field_search_color)) {
    $search_color = $full_product->field_search_color[LANGUAGE_NONE][0]['tid'];
    $search_color = taxonomy_term_load($search_color);
    $color_name = $search_color->name;
  }
  $entity->alt = $title . ' ' .ucfirst($color_name);
  $entity->field_file_image_alt_text = $title . ' ' .ucfirst($color_name);
  object_log('Entity', $entity);
  object_log('Type', $type);
}

}


Solution

  • Actually the problem in my case was that I was trying to set alt field value in wrong way. "Field_file_image_alt_text" field the image element is using is a normal textfield so it clearly needs the following data structure.

    $file->field_file_image_alt_text[LANGUAGE_NONE][0]['value'] = $title . ' ' .ucfirst($color_name);
    $file->field_file_image_alt_text[LANGUAGE_NONE][0]['safe_value'] = $title . ' ' .ucfirst($color_name);
    

    So just a stupid mistake by me! And btw, I ended up using hook_file_presave() hook.