Categories
CMS Drupal Mastering Development

How do I add a button with a custom redirect to a node view?

I’d like to add a "More info" button to the bottom of a node view. The button should redirect the user to a URL based on the current node, e.g. node/1/info:

/**
 * Implements hook_node_view
 *
 * Add the "More Info" button to idea content
 */

function implementations_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $build['implementations_addition'] = [
    '#type' => 'button',
    '#value' => t('More Info'),
    '#submit' => ['implementations_submit_impl'],
    '#weight' => 1000,
    '#attributes' => [
      'class' => ['btn', 'btn-primary'],
      //'onclick' => "location.href='https://google.com'" # dirty hack I really want to avoid
    ],
  ];
}

function implementations_submit_impl(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
  # just a mock redirect for now
  return new Symfony\Component\HttpFoundation\RedirectResponse(\Drupal\Core\Url::fromRoute('user.page'));
}

The above code results in the button correctly appearing, but when I click on it, nothing happens. What am I doing wrong here? Is there a better way?

Leave a Reply

Your email address will not be published. Required fields are marked *