toddddos
toddddos

Reputation: 361

Inject php/html into user profile

I have made a custom module for Drupal 7 that works with user data (has it's own db tables and classes that do some logic with these data). I want to show them on user's profile but I do not want to use drupal fields etc (I dont need another db tables to store the data).. 

Simply put, on each user profile I need to instantiate new class from my module (e.g. new UserDataPresenter($user_id)) and on the profile itself I need to "inject" (?) some html/php data e.g.:

<?php $user = new UserDataPresenter($user_id); ?>
e.g. <b>User's apples: <?php echo $user->getUserApples() ?>
etc... 

This would be shown at the top of the user profile, something like this:

enter image description here

Is this possible in Drupal 7 (without any external modules)

I just want to present the user relevant data on each user's profile page - that's it! Nothing more.

Thank you for your answer.

Upvotes: 0

Views: 80

Answers (1)

Syscall
Syscall

Reputation: 19764

You could use the hook hook_user_view_alter()

function MYMODULE_user_view_alter(&$build) {
  $build['#post_render'][] = 'MYMODULE_user_post_render';
}

function MYMODULE_user_post_render($arg1, $form) {
  $user_id = $form['#account']->uid ;
  $user = new UserDataPresenter($user_id);
  return "<b>User's apples: ".$user->getUserApples() ;
}

Edit Instead of using #post_render, you could directly add an entry into the $build array :

function MYMODULE_user_view_alter(&$build) {
    $uid = $build['#account']->uid;
    $user = new UserDataPresenter($uid);

    $build['my_html'] = [
        '#markup' => '<b>User\'s apples: '.$user->getUserApples().'</b>',
        '#weight' => 99,
    ] ;
}

Then use could #weight to place your markup at the place you want.

Upvotes: 1

Related Questions