Thursday, January 28, 2016

Drupal 7: Set Default Image to Content with Update Hook


Here is the update hook to add default image to article content:

/**
 * Update default image on field base.
 */
function mymodule_update_7300() {
  $field_name = 'field_fb_article_image';
  $filename = 'images.png';
  $source = drupal_get_path('module', 'mymodule') . '/includes/images' . '/' . $filename;

  // Load field info.
  $field = field_info_field($field_name);

  // Create new file object and get new fid.
  if (file_exists($source)) {
    $file = new stdClass;
    $file->filename = $filename;
    $file->timestamp = REQUEST_TIME;
    $file->uri = $source;
    $file->filemime = file_get_mimetype($source);
    $file->uid = 1;
    $file->status = 1;
    $file = file_copy($file, 'public://files', FILE_EXISTS_REPLACE);
    $fid = $file->fid;

    // Replace old fid with new fid.
    $field['settings']['default_image'] = (string) $fid;

    // Update field.
    field_update_field($field);
  }

}

No comments:

Post a Comment