How to create Filefield Entries in Drupal?
by Raza on Jan.06, 2011, under Drupal
Hey guys! I wrote a tutorial on how to programmatically create nodes in Drupal. In this tutorial, i will show you how to write FileField entries using a Drupal module.
function YOURMODULE_CALLBACK() {
$arrfiles = return filePaths(YOUR_IMAGES_DIRPATH);
$filesinfo = array();
foreach($arrfiles as $file) {
$fn = basename($file);
//copying from source folder to drupal's sites/default/files
$cp = copy($file,'/sites/default/files'.$fn);
if($cp) {
$files = new stdClass();
$files->filename = basename($file);
$files->filepath = 'sites/default/files'.$fn;
$files->filemime = file_get_mimetype(basename($file));
$files->filesize = filesize($file);
$files->uid = 1;
$files->status = FILE_STATUS_PERMANENT;
$files->timestamp = time();
drupal_write_record('files', $files);
$filesinfo[] = array(
'fid' => $files->fid,
'title' => basename($files->filename),
'filename' => $files->filename,
'filepath' => $files->filepath,
'filesize' => $files->filesize,
'mimetype' => file_get_mimetype(basename($file)),
'description' => basename($file),
'list' => 1,
);
}
}
$node = node_load(NODEID);
$node->field_images = $filesinfo;
node_save($node);
}
function filePaths($path) {
$dir = new DirectoryIterator($path);
$filelist = array();
foreach($dir as $file) {
if($file->isFile()) {
$filelist[] = $file->getFilename();
}
if($file->isDir()) {
filePaths($file->getPath());
}
}
return $filelist;
}
-
Huunq







