1

Back in Drupal 7, I was able to create a link (Ajax enabled) like this:

$page['profile']['links']['videos'] = array(
        '#type' => 'link',
        '#title' => t('Videos'),
        '#href' => 'profile/videos/' . $uid . '/nojs',
        '#attributes' => array('class' => array('use-ajax', 'profile-button-videos')),
        '#prefix' => '<div class="profile-bio-link button-profile button-profile-video">',
        '#suffix' => '</div>', 
      );

Though there are plenty of examples about how to create a link from a URI, or external URL; and how to attach attributes, I can't find a shred of documentation on how to append something as simple as "nojs" on the end of the URL...

My code so far is this in Drupal 8 (and it works). But, it lacks the /nojs on the end.

Note: I an not using the the Forms API; strictly Render Elements.

$url = Url::fromRoute('people.profile', ['uid' => $uid]);
    $render_array['people']['bio'] = [
      '#title' => $this->t('Publications link'),
      '#type' => 'link',
      '#url' => $url,
      '#attributes' => array('class' => array('use-ajax', 'profile-button-bio')),
    ];

The end result should be a link that looks something like this:

/profile/publications/{uid}/nojs

2

You will not be able to use a route, as /no-js would be its own route. Instead, you should use Url::fromUri. You should be able to use:

Url::fromUri('internal:/profile/publications/' . $user->id() . '/nojs');
3
  • I could have sworn I tried that... but one little space in the wrong space... You were very very close. Can't have a space after internal:^/ $url = Url::fromUri('internal:/profile/publications/' . $uid . '/nojs');
    – sea26.2
    Feb 6 '19 at 2:51
  • 1
    Oops. I was going off memory. I've updated accordingly.
    – Jaypan
    Feb 6 '19 at 3:58
  • Note that it's a best practice to use Url::fromRoute where possible over Url::fromUri, as the actual path may change sometime, which will break code that uses fromUri(), but won't break code that uses fromRoute(). In this case, that wasn't possible, which is why fromUri() is the solution.
    – Jaypan
    Feb 6 '19 at 3:59

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.