Hubert
Hubert

Reputation: 495

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

I've got an "agency" node type which has a boolean field called "has_subscription".

Then I've got a view that only shows the agencies that have "has_subscription" true.

All good.

I'm updating the value of the field programmatically like this:

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

If I then edit the node, I can see that the checkbox for the boolean field is now checked. Great.

However, the view is still not displaying this node. It only starts appearing if I save the node edit page.

Is there anything I need to add to the code?

Upvotes: 0

Views: 7552

Answers (3)

Vernit Gupta
Vernit Gupta

Reputation: 339

Use below code

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

Upvotes: 0

Rahul Chauhan
Rahul Chauhan

Reputation: 119

Set node to published on 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();

Upvotes: 2

Shripal Zala
Shripal Zala

Reputation: 92

If you're using Drupal 8 then please rewrite below code in your file and check it.

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();

Upvotes: 0

Related Questions