Drupal - Generate node edit link

Given a node or node id is there a way to generate an admin edit link to its edit form?

Absolutely, the Url class has a fromRoute method:

$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
$link = Link::fromTextAndUrl('edit', $url);
$build = [
  ...
  'link' => $link->toRenderable(),
];

Given a node or node id is there a way to generate an admin edit link to its edit form?

If you have the $node itself, then you can you can use the toUrl() method to get one of the defined links:

$url = $node->toUrl('edit-form');
$link = Link::fromTextAndUrl('Title', $url);
$build = [
  //...
  'link' => $link->toRenderable(),
];

The various link names for the entity are on the annotation for the Node class:

/**
 * Defines the node entity class.
 *
 * @ContentEntityType(
 *   id = "node",
 *   ...
 *   links = {
 *     "canonical" = "/node/{node}",
 *     "delete-form" = "/node/{node}/delete",
 *     "delete-multiple-form" = "/admin/content/node/delete",
 *     "edit-form" = "/node/{node}/edit",
 *     "version-history" = "/node/{node}/revisions",
 *     "revision" = "/node/{node}/revisions/{node_revision}/view",
 *     "create" = "/node",
 *   }
 * )
 */

Tags:

Nodes

8