【问题标题】:How to create node programmatically with entity reference type - Drupal 8如何使用实体引用类型以编程方式创建节点 - Drupal 8
【发布时间】:2021-10-27 06:47:16
【问题描述】:

我知道有这个解决方案 (https://drupal.stackexchange.com/questions/213379/programmatically-update-an-entity-reference-field)

但我没有为我工作,我有一个错误: Drupal\Core\Entity\EntityStorageException: SQLSTATE[01000]: 警告: 1265 数据在第 1 行被截断为“created”列:INSERT INTO {taxonomy_index} (nid, tid, status, sticky, created) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1 , :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4);数组( [:db_insert_placeholder_0] => 791 [:db_insert_placeholder_1] => 10 [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => 2021-08-17T12:32:12.397 )在 Drupal\Core \Entity\Sql\SqlContentEntityStorage->save()(core\lib\Drupal\Core\Entity\Sql\SqlContentEntityStorage.php 的第 846 行)。

当我尝试使用实体引用字段创建节点时。 该实体是一个分类术语,不需要创建它们。 我使用 API 调用来填充我的内容类型。

这是我的代码:

$newJob = Node::create([
    'type' => 'jobs',
    'title' => $job->label,
    'uid' => 219,
    'field_api_id' => $job->id,
    'created' => $job->publishedDate,
    'field_jobs_title_function' => [
      'value'   =>  $job->label
    ],
    'field_jobs_purpose' => [
      'value'   =>  !is_object($job->JobDataSet->JobData->role)            ? $job->JobDataSet->JobData->role            : '',
      'format'  => 'full_html_no_ckeditor'
    ],
    'field_jobs_how_to_apply' => [
      'value'   =>  !is_object($job->JobDataSet->JobData->requiredFiles)   ? $job->JobDataSet->JobData->requiredFiles   : '',
      'format'  => 'full_html_no_ckeditor'
    ],
    'field_link_cta' => [
      'uri'   =>  !is_object($job->JobDataSet->JobData->applyUrl)          ? $job->JobDataSet->JobData->applyUrl        : '',
      'title' =>  'Postuler maintenant !'
      ],
  ]);

  $newJob->setPublished(TRUE);
  $newJob->save();

  $newJob->field_domain->target_id = $domain;
  $newJob->save();

$domain 是现有分类术语的 int 对应项,当我加载它时它可以工作:

Term::load($domain);

但是当我想创建节点时,我总是遇到错误 SQLSTATE[01000]。

我试过了:

,
    'field_domain' => [
      'target_id' => $domain
    ],

$newJob->field_domain->target_id = $domain;

为什么这对 Drupal 不正确? 谢谢你

【问题讨论】:

  • 在不添加实体引用的情况下是否可以工作?
  • 不,它不起作用

标签: php mysql drupal drupal-8


【解决方案1】:

我找到了解决办法。

问题在于日期的格式。

它必须是一个时间戳,我不知道为什么。

$newJob->setCreatedTime((new DrupalDateTime($newJob->getCreatedTime()))->getTimestamp());
$newJob->field_domain->setValue($domain);
$newJob->save();

【讨论】:

    【解决方案2】:

    如果该字段是实体引用,您应该只需要提供一个目标 id 来将实体链接到彼此。在您的情况下,以下内容就足够了:

    $newJob = Node::create([
        ...
        'field_domain' => $domain,
        ...
    ])
    

    其中 $domain 变量只是对应于其他实体的 id。 不需要指定这个变量就是目标id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-02
      • 2019-11-27
      • 1970-01-01
      • 2017-10-03
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多