I want to update or set value of specific node/entity with one button that have function to update specific field on that node / entity?

And put in on view tab on that specific node on a button?

How can I achieve that?

I found that simple code will achieve that:

use Drupal\node\Entity\Node;

$nodeObj = Node::load(10); // Loading the Node by its Id.  
$nodeObj->set('title', 'New title updated');
$nodeObj->set('body', 'The body text has been updated');
$nodeObj->set('field_date', '2017-10-25');
$nodeObj->save(); // Saving the Node object.

But how do I use it, I am new to drupal. Sorry if the question is not good.


@yulvianda, By seeing your question it seems that you are not getting how to use the piece of code you have shared in your question. If that is the case, then you can use any of the following hooks of Drupal where you can check for your content type (like this: $node->getType() == 'name of the content type') and can put your code: hook_node_update / hook_entity_update.

For reference - https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_update/8.3.x


The two most obvious places to run the piece of code you shared probably are:

  1. In a form submit handler, that's been fired upon pressing a submit button.
  2. In an update hook, that's been fired upon performing database updates.

For creating custom forms with their own submit handler under your own URL see the Form API Example module.

Demonstrates the Drupal Form API.

For running the code inside an update hook, learn about hook_update_N.

Perform a single update between minor versions.

  • I don't think hook_update_N is a good choice for this, as the OP want's to trigger it manually with a button click, and hook_update_N is an one-time update after a code change. – Hudri Sep 4 '19 at 13:06
  • @Hudri – Yupp maybe a too general answer to a too broad question. Maybe you can drop a more precise answer. – leymannx Sep 4 '19 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.