2

How do I programmatically delete a node with a specific internal url alias?

Background: We are trying to delete this node so that it can be replaced during an update hook.

  • Did you want to delete a node by node/nid or the actual alias that is stored inside the url_alias table? Like articles/this-is-a-title? – anoopjohn Nov 12 at 3:47
2

After some digging around through the available services and core classes, I have determined you need to get the nid through the path.alias_manager. Additionally you need to wrap everything in a couple of conditions or you will throw errors if the path does not exist. (eg. if you are trying to roll this change out to a fleet of sites that might or might not have this path already)

Below is my example code:

  // Check the path is valid before proceeding.
  $pathIsValid = \Drupal::pathValidator()->isValid('/blog');

  if ($pathIsValid) {
      $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/blog');
      $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
      // Get nid.
      $nid = $params[$entity_type];
      $node = Node::load($nid);

      // Check if node exists with the given nid.
      if ($node) {
      $node->delete();
    }
  • 1
    I think you'll find that the lines starting "$nodeObj = " and "$node =" are essentially doing the same thing. $params[$entity_type] will be the node ID. So you can simplify the code a bit – Alfred Armstrong Nov 12 at 14:28
  • @AlfredArmstrong not true. $nodeObj is what is used to get the NID from the aliases in the routing table. We can then delete the node once we have the NID. – Mariano Crivello Nov 12 at 23:32
  • You have the nid already. Print $params[$entity_type] and see what you get. And \Drupal::entityTypeManager()->getStorage($entity_type)->load() is equivalent to Node::load() when entity_type is node. – Alfred Armstrong Nov 13 at 9:14
  • @AlfredArmstrong. Thanks for following up, you are correct :) Updating the answer above to reflect your recommendations. Cheers! – Mariano Crivello Nov 13 at 20:21

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.