0

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':
        MYMODULE_mail_notify_admin($entity);
    }
  }
}

function MYMODULE_mail_notify_admin($entity) {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'MYMODULE';
  $key = 'contact';
  $to = 'secret@secret.com';
  # $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

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, privacy policy and cookie policy

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