I'm trying to send an email "someone added content" with the URL to the entity as the message body.

function MYMODULE_entity_insert(EntityInterface $entity) {
  if ($entity->getEntityTypeId() === 'node') {
    switch ($entity->bundle()) {
      case 'contact':

function MYMODULE_mail_notify_admin($entity) {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'MYMODULE';
  $key = 'contact';
  $to = '[email protected]';
  # $to = \Drupal::currentUser()->getEmail();
  $params['message'] = $entity->toUrl()->getUri();
  $params['title'] = $entity->label;
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

The problem is that $entity->toUrl()->getUri() gives an error, "This URL has a Drupal route, so the canonical form is not a URI".

How do I get the URL from a URL object? Is this a problem because the entity hasn't been created yet, and the route hasn't been assigned?

1 Answer 1


The URL object is there, you're just calling it wrong.

The code for this is a little complicated:

  $path = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
  $params['message'] = $path;

For more info, see this issue.

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.