Adjuntar archivos mediante programación


25

Creé el tipo de contenido "Galería" y agregué dos campos: "foto" y "documento". Luego usé el siguiente código para cargar un archivo en el campo "documento":

$file = file_save_upload('document', array(
    'file_validate_extensions' => array('txt doc'), // Validate extensions.
));

// If the file passed validation:
if ($file) {
// Move the file, into the Drupal file system
if ($file = file_move($file, 'public://')) {
  $file->status = FILE_STATUS_PERMANENT;
 // $file->file_display = 1;
  $file = file_save($file);

} else {
  $output = t('Failed to write the uploaded file the site\'s file folder.');
}       
 } else {
$output = t('No file was uploaded.');
 }

Adjunto este archivo al nodo usando el siguiente código:

$customNode->field_document[$customNode->language][0] = (array)$file;

Cuando llamo a la node_submit()función, aparece el siguiente error:

Infracción de restricción de integridad: 1048 La columna 'field_document_display' no puede ser nula

¿Alguien sabe lo que estoy haciendo mal?

Respuestas:


29

Por lo general, no tiro la (array)$filelínea porque realmente lo único que necesitan los datos de campo es el fid, la descripción y la visualización. Por lo general, hago lo siguiente:

$node->field_image[LANGUAGE_NONE][] = array(
  'fid' => $file->fid,
  'display' => 1,
  'description' => '',
);
node_save( $node );

De esta manera, si se requiere la pantalla, no recibo un error. Pero solo soy yo ...


Confuso para mí por qué no tiene valores predeterminados.
— 32i

No ve los valores predeterminados porque esta es una asignación directa.
— Lester Peabody

7

Su solución es casi correcta; sin embargo, en algunos casos requiere que también configure la visualización y la descripción.

Para que su código funcione, haga esto:

$file = file_save_upload('document', array(
    'file_validate_extensions' => array('txt doc'), // Validate extensions.
));

// If the file passed validation:
if ($file) {
// Move the file, into the Drupal file system
if ($file = file_move($file, 'public://')) {
  $file->status = FILE_STATUS_PERMANENT;
 // $file->file_display = 1;
  $file = file_save($file);
  //set the extra values needed to make node_save work
  $file->display = 1;
  $file->description = "";
} else {
  $output = t('Failed to write the uploaded file the site\'s file folder.');
}       
 } else {
$output = t('No file was uploaded.');
 }

2

Creo que la clave aquí son esas líneas

$file->display = 1;
$file->description = "";

como señaló Eric van Eldik. Estaba luchando con exactamente el mismo problema, agregando solo

$file->display = 1;

no ayudó, pero

$file->description = "";

me alegró el día.


0

Para agregar archivos mediante programación al nodo, puede usar

$managed = TRUE; // Whether or not to create a Drupal file record
$filename = 'public://imdb-cast-' . time() . '.jpg';
$iamge_file = system_retrieve_file($url,$filename , $managed);
if($iamge_file){
$file = file_load(db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField());
$node->field_image['und'][0] = (array) $file;
  }
}

0

Solo para pegar mi solución aquí también, necesitaba crear un nuevo nodo y cargar una imagen mediante programación.

$filepath = variable_get('file_public_path') . '/xmas_banner.jpg';
$file_temp = file_get_contents($filepath);
$file_temp = file_save_data($file_temp, file_default_scheme() . '://' .'xmas_banner_nl.jpg', FILE_EXISTS_RENAME);

$node = new stdClass();
$node->type = 'carousel'; // custom content type
$node->title = 'XMAS NL';
$node->field_banner_image['und'][0] = (array) $file_temp;
$node->uid = 1;
$node->status = 0;
$node->active = 0;
$node->promote = 0;
node_save($node);

0

Adjunte múltiples archivos mediante programación en Drupal 8:

foreach ($fileIds as $fid) {
  $node->field_images[] = [
    'target_id' => $fid,
    'alt' => 'ALT TEXT',
    'title' => 'TITLE TEXT'
  ];
}
$node->save();
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.