Home ›
How to fetch a file at a URL and set it as the default image in an image fieldHow to fetch a file at a URL and set it as the default image in an image field
Submitted by Benjamin Melançon on June 14, 2012 - 9:29am
There's two separate cool things here that you might want to do. One, simply know how to save a file from a URL (there's a secret Drupal function for that in system module) and two, how to give an image field a default image when creating it programmatically (that part is outsourced to the fieldhelp module).
<?php
/**
* Add the book cover image field. {
*/
function libcat_book_add_field_cover_image() {
drupal_load('module', 'fieldhelp');
$field_name = LIBCAT_BOOK_FIELD_LIBCAT_COVER;
$file = libcat_book_save_default_cover_image_file();
// Create the field, passing in the default cover image file ID.
fieldhelp_image_create_field($field_name, $file->fid);
}
/**
* Save the cover image as a regular file.
*/
function libcat_book_save_default_cover_image_file() {
$directory = file_build_uri('libcat_book');
if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
// If our directory doesn't exist and can't be created, use the default.
$directory = NULL;
}
$source = drupal_get_path('module', 'libcat_book') . '/images/default_cover.png';
$url = $GLOBALS['base_url'] . '/' . $source;
$file = system_retrieve_file($url, $directory, TRUE);
}
?>
Searched words:
drupal 7 file save from url
drupal get current site URI
Comments
Post new comment