Drupal 7 - 以编程方式创建节点,添加嵌入到字段的youtube

Tox*_*xid 4 php drupal-7

我正在尝试以编程方式创建节点.使用带有youtube扩展程序的媒体模块,我想用youtube数据填充一个字段.从我到目前为止所读到的内容来看,它看起来像这样:

   <?php
    // $value in this case is the youtube ID.
    $file = new stdClass();
      $file->uid = 1;
      $file->filename = $value;
      $file->uri = 'youtube://v/' . $value;
      $file->filemime =  'video/youtube';
      $file->type = 'video';
      $file->status = 1;
      $youtube = file_save($file);

    node->field_youtube[$node->language]['0']['fid'] = (array) $youtube->fid;
    ?>
Run Code Online (Sandbox Code Playgroud)

我通过查看bartik主题中$ content变量中的信息来了解这一点.但是,这会导致"错误的文件扩展名"错误.我也尝试将整个url放在$ file-> uri中并使用file_get_mimetype,然后它没有抛出错误但是视频也没有用.有谁知道如何做到这一点?

Tox*_*xid 5

我找到了答案.函数file_save仅检查文件ID是否已存在于数据库中.但是,youtube uri字段不允许重复.因此我从file_example模块中窃取了这个函数.它检查文件是否存在该uri,如果它存在,则加载该对象.

function file_example_get_managed_file($uri) {
  $fid = db_query('SELECT fid FROM {file_managed} WHERE uri = :uri', array(':uri' => $uri))->fetchField();
  if (!empty($fid)) {
    $file_object = file_load($fid);
    return $file_object;
  }
  return FALSE;
}
Run Code Online (Sandbox Code Playgroud)

所以最后我简单地添加一个if语句,如下所示:

$file_exists = wthm_get_managed_file('youtube://v/' . $value);
if (!$file_exists) {
  $file_path = drupal_realpath('youtube://v/' . $value);
  $file = new stdClass();
    $file->uid = 1;
    $file->filename = $value;
    $file->uri = 'youtube://v/' . $value;
    $file->filemime = file_get_mimetype($file_path);
    $file->type = 'video';
    $file->status = 1;
  $file_exists = file_save($file);
}
$node->field_youtube[$node->language]['0'] = (array) $file_exists;  
Run Code Online (Sandbox Code Playgroud)

这解决了大多数问题.我仍然收到一条消息说文件扩展名不好,但无论如何都可行.