Drupal 8:以编程方式更新节点不会更新视图中节点的状态

Drupal 8: updating node programmatically does not update the state of the node in a view

我有一个 "agency" 节点类型,它有一个名为 "has_subscription" 的布尔字段。

然后我得到一个视图,该视图仅显示 "has_subscription" 为真的机构。

一切顺利。

我正在像这样以编程方式更新字段的值:

$node = node_load($nid);
$node->set("field_has_subscription", 1);
$node->save();

如果我随后编辑该节点,我可以看到布尔字段的复选框现在已选中。太棒了

但是,视图仍然没有显示这个节点。如果我保存节点编辑页面,它只会开始出现。

我需要在代码中添加什么吗?

如果您使用的是 Drupal 8,请在您的文件中重写以下代码并检查它。

use Drupal\node\Entity\Node;

$node = Node::load($nid);

//set value for field
$node->field_has_subscription->value = TRUE;

//save to update node
$node->save();

将节点设置为在保存时发布

use Drupal\node\Entity\Node;

$node = Node::load($nid); 
//set value for field
$node->field_has_subscription->value = TRUE;
// set node to publish 
$node->setPublished(TRUE);
//save to update node
$node->save();

使用下面的代码

$node  =  \Drupal\node\Entity\Node::load($nid);
$node->set('field_has_subscription', 1);
$node->save();