You can set a node's title with the "Set a data value" action - you don't need to write your own action. I'm going to assume that you're putting this into your own action because there are other things you want to do that you haven't mentioned or because you are learning how to write an action - if this is ONLY about setting the title then I don't see the point of a custom action.
Problems with the approach and the partial solution given in the initial post:
You don't need to get the entity ID then load the entity from
storage, because Rules is already passing you the loaded entity.
You're using entity instead of node, which wrong - Nodes have
titles, Entities in general DON'T.
You're hardwiring in a title taken from a specific field 'field_xyz'.
Instead, you should pass in a string variable which holds the title.
That way the Rule configuration can get the value out of 'field_xyz'
or out of 'field_nlm' or from a thousand other places - writing the
action with a string parameter will make it far more useful.
The EntityManager has been deprecated since Drupal 8.0 and should not be used. You should be using EntityTypeManager instead. But as I said in #1, this isn't even needed.
You don't have to save the node, Rules will handle the saving
automatically.
This really only requires one line of code (plus some boilerplate code, like all plugins...). Here's a complete solution that takes two context variables:
- The node to change.
- The title to use.
namespace Drupal\my_module\Plugin\RulesAction;
use Drupal\node\NodeInterface;
use Drupal\rules\Core\RulesActionBase;
/**
* Sets the title of a content item.
*
* @RulesAction(
* id = "rules_node_set_title",
* label = @Translation("Sets the title of the selected content item"),
* category = @Translation("Content"),
* context_definitions = {
* "node" = @ContextDefinition("entity:node",
* label = @Translation("Node"),
* description = @Translation("Specifies the content item to change."),
* assignment_restriction = "selector"
* ),
* "title" = @ContextDefinition("string",
* label = @Translation("Title"),
* description = @Translation("The new title.")
* ),
* }
* )
*/
class NodeSetTitle extends RulesActionBase {
/**
* Executes the action with the given context.
*
* @param \Drupal\node\NodeInterface $node
* The node to modify.
* @param string $title
* The new title.
*/
protected function doExecute(NodeInterface $node, $title) {
$node->setTitle($title);
}
/**
* {@inheritdoc}
*/
public function autoSaveContext() {
// The node should be auto-saved after the execution.
return ['node'];
}
}