【问题标题】:programatically insert content with image field in Drupal以编程方式在 Drupal 中插入带有图像字段的内容
【发布时间】:2012-12-12 23:57:21
【问题描述】:

我正在尝试编写 PHP 以将大量内容插入我网站的 drupal 6 数据库。 内容类型有 3 个自定义字段:

field_theme_preview_demo_link - 文本字段

field_theme_preview_content_styl - 文本选择器

field_theme_preview_thumb - 带有“alt”的图像字段

我只是手动将图像复制到正确的目录。

我创建了内容类型(并手动插入了一些内容以确认一切正常)。

然后我找到了一些用于以编程方式插入内容的代码示例...

Creating Drupal CCK content programatically/ via API

http://drupal.org/node/458778#comment-1653696 (对于这个我无法理解为 D6 建议的 mod)。

我尝试对其进行修改,但无法使其工作 - 它确实创建了新内容,但图像字段为空白。 (要运行此代码,我只需将其粘贴到“执行 PHP 代码”块中。)

global $user;
$newnode = new stdClass();
$newnode->title = 'New node title';
$newnode->body = "the body";
$newnode->uid = $user->uid;
$newnode->type = 'theme_preview';
$newnode->status = 1;
$newnode->promote = 0;
$newnode->active = 1;

$newnode->field_theme_preview_demo_link[0]['value'] = 'the link';
$newnode->field_theme_preview_content_styl[0]['value'] = 'Books';

$newnode->field_theme_preview_thumb = array(
    array(
      'fid' => 'upload',
      'alt' => 'the alt',
      'filename' =>  'sites/default/files/theme_preview_thumbs/41531.jpg',
      'filepath' => 'sites/default/files/theme_preview_thumbs',
      'filesize' => filesize('sites/default/files/theme_preview_thumbs/41531.jpg'),
    ),
  );

node_save($newnode);

【问题讨论】:

  • 这个问题在专门的 drupal.stackexchange.com 上可能会更好
  • 您需要使用file_save保存文件并将fid设置为该文件保存记录的ID。

标签: php drupal drupal-6 cck


【解决方案1】:

fid 字段设置为“上传”是在实际上传文件时由节点表单完成的操作。如果您以编程方式生成内容,则需要从其他地方获取fid

您可能需要手动使用file api 将文件系统上某处的文件输入文件数据库,然后从生成的对象中绘制您的fid

【讨论】:

    【解决方案2】:

    使用http://drupal.org/project/node_export这个模块将内容导入或导出到特定的内容类型,它真的很适合我,而且图像会自动上传。

    使用此模块必须考虑的一件事,在导入节点后,确保图像与其内容匹配。

    使用此模块,我已将 100 篇新闻文章从我的本地服务器站点上传到我的网站。

    【讨论】:

    • 谢谢,不知道这个——下次可能会用这个
    【解决方案3】:

    @Seth Battin,@Ayesh K,感谢您的提示, 工作代码...

    global $user;
    $newnode = new stdClass();
    $newnode->title = 'New node title';
    $newnode->body = "this is a new node, created by import function";
    $newnode->uid = $user->uid;
    $newnode->type = 'theme_preview';
    $newnode->status = 1;
    $newnode->promote = 0;
    $newnode->active = 1;
    
    $newnode->field_theme_preview_demo_link[0]['value'] = 'test 1';
    $newnode->field_theme_preview_content_styl[0]['value'] = 'Books';
    
    $field = field_file_save_file(
        'sites/default/files/srcImage1.jpg', 
        array(),
        'sites/default/files/theme_preview_thumbs');
    
    if( !isset($field['data']) )  $field['data'] = array();
    $field['data']['title'] = "the image title";
    $field['data']['alt'] = "the image alt";
    
    $newnode->field_theme_preview_thumb = array(0 => $field);
    $newnode = node_submit($newnode);
    node_save($newnode);
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2013-06-07
      • 2012-12-23
      • 1970-01-01
      • 2012-11-30
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多