11

I'm attempting to dynamically generate a node edit link. I understand that I can manually create it by using

$editpath = '/node/'.$nid.'/edit';

but I have multiple sites that use subfolders like

/site1_subfolder/node/123/edit

and

/site2_subfolder/node/123/edit

I looked at the node class and I couldn't see any method that would generate this link for me. I did see that there's a NodeForm class but I didn't see any static methods I could take advantage of either.

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

NOTE: If that's not possible I would be fine with using a function to get the subfolder names so I could do $editpath = '/'.$subfolder_name.'/node/'.$nid.'/edit';

But I'm not sure how to do that either.

UPDATE: I suppose I could do a $node->toUrl()->toString() to get the direct path and add edit at the end but this would only give me the alias, is there a way to not get the alias from this and get the direct link to the node instead?

0

2 Answers 2

10

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(),
];
9

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",
 *   }
 * )
 */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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