3

I just installed a custom module and created a controller with index function in it. I want to have a contextual link for this. I have following code in index function.

public function index() {
    return [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: hello'),
        '#contextual_links' => [
            'mymodule' => 'mymodule.another_action',
        ],
    ];
}

File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure Custom Module'
  route_name: 'mymodule.another_action'
  group: 'my_module'

Please suggest the right way.

1

I did this using a reference from below.

Adding the contextual link render element

I added a variable to the theme, and passed contextual link in controller function to twig template using that variable. Please see code below.

File : mymodule.module

function mymodule_theme() {
  return [
    'mymodule' => [
      'template' => 'mymodule',
      'variables' => [              //Added a variable content
        'content' => '',
      ]
    ],
  ];
}

File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure My Module'
  route_name: 'mymodule.route_name'
  group: 'mymodule' 

File : IndexController.php

public function index() {
    $data['content'] = [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: index'),
    ];

    $data['#contextual_links'] = [
        'mymodule' => [
            'route_parameters' => [],
        ],
    ];

    return [
        '#theme' => 'mymodule',
        '#content' => $data,        //Pass Contextual link to the variable
    ];
}

File : mymodule.html.twig

{%
set classes = [
'contextual-region'
]
%}

<div {{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}                     //Render here
</div>

--

Thanks

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.