2012-01-04 81 views
2

我正在製作一個自定義的「視頻」字段,應該接受幾個文件(對於不同的視頻格式)和標題。到目前爲止,模式沒有問題,但我無法上傳並存儲實際的文件。Drupal 7自定義字段與多個文件字段

我在hook_field_widget_form代碼如下所示(僅粘貼相關位):

$element['mp4'] = array(
    '#type' => 'file', 
    '#title' => 'MP4 file', 
    '#delta' => $delta, 
); 
$element['ogg'] = ... /* similar to the mp4 one */ 
$element['caption'] = array(
    '#type' => 'textfield', 
    '#title' => 'Caption', 
    '#delta' => $delta, 
); 

而且,在我.install文件:

function customvideofield_field_schema($field) { 
    return array(
    'columns' => array(
     'mp4' => array(
     'type' => 'int', 
     'unsigned' => TRUE, 
     'not null' => TRUE, 
     'default' => 0, 
    ), 
     'ogg' => ... /* similar to mp4 */ 
     'caption' => array(
     'type' => 'varchar', 
     'length' => 255, 
    ), 
    ) 
); 
} 

而我得到的錯誤是,當我嘗試存儲數據。我得到了表單,數據庫看起來很好(至少是Drupal生成的字段),但是當它嘗試執行INSERT時,它會失敗,因爲它嘗試進入這些整數字段的值是空字符串。

從我的理解,他們必須是整數,對不對? (fid s?)但我猜這些文件沒有被上傳,即使我的上傳文件的界面正確。

Drupal向您展示了它試圖執行的INSERT查詢,這是太長而無法在此處發佈的,但我可以看到caption字段(它只是一個文本字段)的值在查詢中很好,所以這只是文件字段的問題。

回答

3

你可能想使用managed_file字段類型相反,它處理上傳文件並登記其在managed_files表爲您服務。然後,你想補充一個提交功能,你的widget形式,把下面的代碼(來自鏈接到上面的FAPI頁):

// Load the file via file.fid. 
$file = file_load($form_state['values']['mp4']); 

// Change status to permanent. 
$file->status = FILE_STATUS_PERMANENT; 

// Save. 
file_save($file); 

// Record that the module (in this example, user module) is using the file. 
file_usage_add($file, 'customvideofield', 'customvideofield', $file->fid); 

希望幫助

編輯

核心文件模塊處理這個使用hook_field_presave()的實際提交,我最好的猜測是,這個代碼將工作:

function customvideofield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) { 
    // Make sure that each file which will be saved with this object has a 
    // permanent status, so that it will not be removed when temporary files are 
    // cleaned up. 
    foreach ($items as $item) { 
    $file = file_load($item['mp4']); 
    if (!$file->status) { 
     $file->status = FILE_STATUS_PERMANENT; 
     file_save($file); 
    } 
    } 
} 

假定您的字段的文件ID列是名爲mp4的文件ID列。

記得清除Drupal的緩存當你實現新的鉤子或它不會被註冊。

+0

這真的讓我朝着正確的方向,謝謝!你知道我應該把這個代碼放在哪裏嗎?它是'hook_field_update_field()'? – cambraca 2012-01-04 15:38:59

+0

@cambraca:我已經更新了答案,希望它有所幫助:) – Clive 2012-01-04 18:17:07

+0

因此,如果您使用'hook_field_presave',那麼不需要使用'file_usage_add'來註冊文件? – Beebee 2013-09-17 08:58:48

0

我還沒有嘗試過在我的Drupal模塊中上傳文件,但是你可以檢查你的表單標籤是否具有屬性enctype =「multipart/form-data」?

我期望Drupal應該自動包括這個,但沒有它的文件字段將無法正常工作,這似乎是你正在經歷的。

詹姆斯

相關問題