简体   繁体   English

D8 PHP:通过 set() 和 save() 更新节点实体上的“Text (plain)”字段值,当值从“1”变为“01”时忽略

[英]D8 PHP: Updating "Text (plain)" field value on node entity via set() and save() ignored when value changes from "1" to "01"

Goal: Programmatically change value of string field from "1" to "01" using entity ->set() and ->save()目标:使用实体 ->set() 和 ->save() 以编程方式将字符串字段的值从“1”更改为“01”

When attempting to update a field on a node programmatically (via a custom module's cron hook), the initial value of the "Text (plain)" field is "1".尝试以编程方式(通过自定义模块的 cron 挂钩)更新节点上的字段时,“文本(纯文本)”字段的初始值为“1”。 When attempting to update the field programmatically to "01" (the 0 is important for business purposes), the change is ignored.当尝试以编程方式将字段更新为“01”(0 对业务目的很重要)时,更改将被忽略。 However, it does work if I set to almost any other value.但是,如果我设置为几乎任何其他值,它确实有效。

// DOES NOT save update to field (Current value is "1")
$node = \Drupal\node\Entity\Node::load(1);
$node->set('field_code', '01'); // '01' is indeed a string
$node->save();
// DOES save update to field (Current value is "1")
$node = \Drupal\node\Entity\Node::load(1);
$node->set('field_code', '02');
$node->save();

If I were to make the change via the UI's node edit form, the change is saved in the same scenario.如果我通过 UI 的节点编辑表单进行更改,更改将保存在相同的场景中。

Has anyone else encountered this?有人遇到过这种情况么? It seems that there must be some validation that is occurring that is comparing the strings before saving as '01' == '1'; // true似乎必须进行一些验证,即在保存为'01' == '1'; // true之前比较字符串'01' == '1'; // true '01' == '1'; // true (as string) in PHP. '01' == '1'; // true在 PHP 中为'01' == '1'; // true (作为字符串)。

I encountered the same problem and I finally found the cause.我遇到了同样的问题,我终于找到了原因。

As you know, when updating an existing revision, keep the existing records if the field values did not change.如您所知, 更新现有修订时,如果字段值未更改,请保留现有记录。 And one field value and the original value are compared by not === but == at the last of FieldItemList::equals .并且在FieldItemList::equals的最后一个字段值和原始值通过 not === but ==进行比较。

Unfortunately, it seems like we can't avoid this problem.不幸的是,我们似乎无法避免这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM