I need to programmatically generate nodes using some data that I extract from different import files. For the node creation I use Entity API. I've written a simple function to which I pass the node data in a structured array and the function imports each field depending on how it's defined:
function my_module_create_function($item, $node_type, $language) {
$node = entity_create('node', array ('type' => $node_type));
$entity = entity_metadata_wrapper('node', $node);
$entity->language = 'es';//LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
//strings
foreach ($item as $key=> $field) {
switch ($field['field_type']) {
case 'multiple-reference':
if(is_array($field['value'])){
$entity->$key = $field['value'];
}else{
//some alert log
}
break;
case 'file':
if (file_exists($field['value']) && isset($field['filename']))
{
$file = file_get_contents($field['value']);
$filename = $field['filename'];
if(isset($field['folder']) && file_exists($field['folder'])){
$folder = $field['folder'];
}else{
$folder = "public://";
}
$file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
$entity->$key= (array)$file;
}
else
{
// some alert log
}
break;
case 'long-text':
$entity->$key->set(array(
'value' => $field['value'],
//'summary' => '',
'format' => 'full_html',
));
break;
case 'geolocation':
$entity->$key->set(array(
'latitude' => $field['value']['latitude'],
'longitude' => $field['value']['longitude'],
//other elements added here (province, postal_code, country [es, en,...],additional, ...)
));
break;
default:
$entity->$key= $field['value'];
break;
}
}
$entity->status = 1; //(1 or 0): published or not
$entity->promote = 0; //(1 or 0): promoted to front page
$entity->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
// Save the entity
return $entity->save();
}
This function works great except for the file field type. When I try to import a node with a file it gives me this error:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'my_field_display' cannot be null
the thing is that I have used the same structure:
$file = file_get_contents("file_path");
$file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
$entity->$key= (array)$file;
for image fields (or multiple image fields using "[] =
" instead of " =
") it works without any problem. Anyone knows if I'm doing anything wrong with this file field?
Any advice would be helpful