I am using the following code.

 $form['test'] = array(
        '#type' => 'link',
        '#href' => "javascript:;",
        '#title' => t('Show'),
        '#attributes' => array(
            'onclick' => "show_this();",
            'onsubmit' => 'return false',
        '#id' => 'myid',

Its output is the following.

<a href="/javascript%3A%3B" onclick="show_this();" onsubmit="return false" id="myid">Show</a>

The onclick event is working properly. I want to disable href.

How can I achieve this?


You don't need the #href to prevent the event.

$form['test'] = [
  '#type' => 'link',
  '#href' => '#',
  '#title' => t('Show'),
  '#attributes' => [
    'onclick' => "alert('hello');return false",
  '#id' => 'myid',

In the above example, I removed the #href and the onsubmit handler and added return false after the alert() function in the onclick handler.
I don't know what you're trying to achieve in your code, but the above example is working for me.

UPDATE: I update the #href in my answer.

  • Thanks, @ismail-cherri, but i got error : Notice: Undefined index: #href in drupal_pre_render_link() – helpdoc Dec 21 '18 at 8:33
  • I updated the answer to include a # for href – Ismail Cherri Dec 21 '18 at 8:38

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.