0

On the user profile page, I want to add link field which will link to a view page.

For example, if the current path is:

sitename/user/1 (profile page of user-1)

The link should be:

sitename/user/1/view-page

It should take the user-id from the current-path. It should redirect to sitename/user/1/view-page, in general sitename/user/%/view-page, which is my contextual view path.

How can build this link field for the profile page?

3

One way to go about this is a theme override of the user profile page:

  • Copy over core/modules/user/templates/user.html.twig over to your theme's template directory.
  • Have your theme implement template_preprocess_user() in your MYTHEME.theme file to inject a custom URL variable.
  • Modify your theme's user.html.twig to contain the HTML for the link.

For example, in your MYTHEME.theme:

use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_user() for user.html.twig.
 */
function MYTHEME_preprocess_user(&$variables) {
  if (\Drupal::request()->get(RouteObjectInterface::ROUTE_NAME) == 'entity.user.canonical') {
    $variables['view_page_path'] = Url::fromUri('base:' . \Drupal::service('path.current')->getPath())->toString() . '/view-page';
  }
}

In your user.html.twig:

{% if view_page_path %}
  <a href="{{ view_page_path }}">MY VIEW PAGE</a>
{% endif %}
  • This works perfectly, Just one correction, I had to use $variables['view_page_path'] = '/drupal8101' . \Drupal::service('path.current')->getPath() . '/view-page'; "drupal8101" is my site name, so with previous one it was taking taking site-name. Other thing, the Link is appearing at author-by stamp also, in articles or teasers. – CodeNext Jul 31 '16 at 20:40
  • Yeah, appears user.html.twig is used in other locations where a user entity might be rendered. The code has been updated for route checking & Url generation. – Shawn Conn Jul 31 '16 at 21:32
  • This works perfectly, Thanks for your effort. Appreciated. – CodeNext Jul 31 '16 at 21:48
  • Hi, I want to use this answer to solve this Question. I will provide full reference to this answer & you. Even that question I was trying to solve and this part I was not able to figure out hence for that I thought to raise new question. Since this answer is provided by you so I am asking your permission for using this answer to solve that question. – CodeNext Aug 3 '16 at 0:53
  • Thanks for the courtesy, feel free to cite anything you want. It's not uncommon to cite other answers on here, just make sure to link back so readers can follow your thoughts. – Shawn Conn Aug 3 '16 at 1:26

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.