How to Master Contextual Links On Your Drupal Website
While developing Drupal websites, I have been faced with the problem of adding custom contextual links to different elements like: taxonomy terms displayed as rendered entities, blocks created with Ctools plugins, custom blocks and other.
Contextual links are links attached to elements such as nodes, blocks, views displays and others. When you hover on a specific region, a gear image appears. Upon clicking it, the image shows the list of contextual links. You can see an example below.
Some modules provide contextual links that allow users to edit views, nodes, taxonomies and other elements, but there are situations when contextual links need to be created in a custom implementation.
Add a Custom Contextual Link to the Taxonomy Term View
In my case, I have a view that shows Taxonomy terms from the Service Category vocabulary as Rendered entities, without fields.
For each term, a contextual link should be added to the page where the term information can be edited, and the link would allow privileged users access to that page. This task can be accomplished using template_preprocess_taxonomy_term() to edit variables that will be used in the template file (taxonomy-term.tpl.php or taxonomy-term--service_category.tpl.php) and hook_contextual_links_view_alter(). In the preprocess function, the contextual link element can be added in the $title_suffix array.
In hook_contextual_links_view_alter() are the altered contextual links elements before they are rendered. In this case, a new link is added.
An important thing is that a class should be added for the region wrapper that includes contextual links. This class is contextual-links-region, and it makes it possible to show the contextual links region when you hover on the gear icon.
As a result, the taxonomy term entities will be displayed with a contextual link that will allow users that have administer taxonomy permission to access the term edit page.
Custom Contextual Links as Render Elements
Contextual links can be added to elements like blocks using a renderable array. For example:
Theme function in the example is used to add a template where the wrapper with the contextual-links-region class will be added:
And the content of the template file:
Finally, the result will be a block in which content is wrapped with a contextual link region. Clicking on the gear icon will display the link to the vocabulary edit page.
You can find more info here: https://drupal.org/documentation/modules/contextual . Please post any comments below. And make sure to subscribe to our mailing list to receive our blog feed.
Tags: DrupalDevelopmentcontextual linksCheck this option to include this post in Planet Drupal aggregator: planetTopics: Tech & Development