User login

How to fetch a file at a URL and set it as the default image in an image field

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

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.