home | career | drupal | java | mac | mysql | perl | php | scala | uml | unix

Drupal example source code file (file.devel_generate.inc)

This example Drupal source code file (file.devel_generate.inc) is included in the DevDaily.com "Drupal Source Code Warehouse" project. The intent of this project is to help you "Learn Drupal by Example".

PHP - Drupal tags/keywords

bundle, destination, directory, field, file, fp, function, if, instance, object, path, php, return, tmp_file

The file.devel_generate.inc Drupal example source code

<?php
// $Id: file.devel_generate.inc,v 1.3 2010/02/08 15:48:15 weitzman Exp $

function file_devel_generate($object, $field, $instance, $bundle) {
  if (field_behaviors_widget('multiple values', $instance) == FIELD_BEHAVIOR_CUSTOM) {
    return devel_generate_multiple('_file_devel_generate', $object, $field, $instance, $bundle);
  }
  else {
    return _file_devel_generate($object, $field, $instance, $bundle);
  }
}

function _file_devel_generate($object, $field, $instance, $bundle) {
  static $file;

  if (empty($file)) {
    if ($path = devel_generate_textfile()) {
      $source->uri = $path;
      $source->uid = 1; // TODO: randomize? use case specific.
      $source->filemime = 'text/plain';
      $destination = $field['settings']['uri_scheme'] . '://' . $instance['settings']['file_directory'] . '/' . basename($path);
      $file = file_move($source, $destination);
    }
    else {
      return FALSE;
    }
  }
  $object_field['fid'] = $file->fid;
  $object_field['display'] = $field['settings']['display_default'];
  $object_field['description'] = devel_create_greeking(10);

  return $object_field;
}

/**
 * Private function for generating a random text file.
 */
function devel_generate_textfile($filesize = 1024) {
  if ($tmp_file = drupal_tempnam('temporary://', 'filefield_')) {
    $destination = $tmp_file . '.txt';
    file_unmanaged_move($tmp_file, $destination);

    $fp = fopen($destination, 'w');
    fwrite($fp, str_repeat('01', $filesize/2));
    fclose($fp);

    return $destination;
  }
}

Other Drupal examples (source code examples)

Here is a short list of links related to this Drupal file.devel_generate.inc source code file:

new blog posts

"Drupal" is a registered trademark of Dries Buytaert.

my drupal tutorials and examples  

Copyright 1998-2016 Alvin Alexander, alvinalexander.com
All Rights Reserved.

Beginning in 2016, a portion of the proceeds from pages under the '/drupal-code-examples/' URI will be donated to charity.