使用表单将文件添加到节点

时间:2011-12-15 10:52:38

标签: forms drupal-7

我正在尝试使用表单创建节点(内容类型:歌曲)。我可以设置磁贴/描述,但是当涉及上传文件时,我收到此错误:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
Column 'field_file1_display' cannot be null: INSERT INTO
{field_data_field_file1} (entity_type, entity_id, revision_id, bundle,
delta, language, field_file1_fid, field_file1_display,
field_file1_description) VALUES (:db_insert_placeholder_0,
:db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4,
:db_insert_placeholder_5, :db_insert_placeholder_6,
:db_insert_placeholder_7, :db_insert_placeholder_8); Array (
[:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 67
[:db_insert_placeholder_2] => 67 [:db_insert_placeholder_3] => song
[:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
[:db_insert_placeholder_6] => 55 [:db_insert_placeholder_7] =>
[:db_insert_placeholder_8] => ) in
field_sql_storage_field_storage_write() (line 448 of
/Users/blabla/_server/drupal/modules/field/modules/field_sql_storage/field_sql_storage.module).

这是我写的代码。

function insertnode_form_submit($form, &$form_state) {
    $node = new StdClass();
    $node->type = 'song';
    $node->status = 1;
    $node->language = LANGUAGE_NONE; 
    $node->title = $form['name']['#value'];
    $node->field_song_description[$node->language][0]['value'] = $form['description']['#value'];

    $file_path = drupal_realpath($form['file1']['#file']->uri);

    $file = (object) array(
        'uid' => 1,
        'uri' => $file_path,
        'filemime' => file_get_mimetype($file_path),
        'status' => 1,
    ); 
    $file = file_copy($file, 'public://');
    $node->field_file1[$node->language][0] = (array)$file;

    //$node->field_file1[$node->language][0] = (array)$form['file1']['#file'];//also tried this but nothing

    node_save($node);
}

2 个答案:

答案 0 :(得分:6)

您必须在node对象中添加两个值:fiddispla y

尝试

$node->field_file1[$node->language][0]['fid'] = $file->fid;
$node->field_file1[$node->language][0]['display'] = 1;

答案 1 :(得分:0)

通常在Drupal 7中执行此操作的方法是使用managed_file窗口小部件类型来处理所有文件复制/移动,并将文件添加到文件表中。在$form_state数组中,您将从新创建的文件中传递fid

在您的表单功能中:

$form['my_file_field'] = array(
  '#type' => 'managed_file',
  '#title' => 'File',
  '#upload_location' => 'public://my-files/'
);

然后在你的表单提交功能:

// Load the file via file.fid.
$file = file_load($form_state['values']['my_file_field']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);

$node->field_file1[$node->language] = array(
  0 => array('fid' => $file->fid, 'display' => 1, 'description' => 'The description')
);