Hot answers tagged

107

The other answers are great, accurate, detailed, but I'm not sure they're the "simple words" explaining the bare bones of the concept that the asker was looking for. I think of hooks as a point where the code pauses and shouts "Anyone else got anything to add here?". Any module can have a function that replies to this, and gets triggered with appropriate ...


52

Hooks, are mostly implementations of the Visitor, and Observer patterns. One of the most common hooks implementations is hook_menu, which allows modules to register new paths within a Drupal system. function my_module_menu() { return array('myawesomefrontpage' => array( 'page callback' => 'function_that_will_render_frontpage' )); } A very ...


40

Unfortunately, your self-answer is not so universal. Field language and node language are not the same things. Field language is needed only if you are using Field Translation API (for example Entity translation). When you start using it, some fields are converted to translatable. Translatable fields have language code, which really makes sense. But if ...


40

If you are trying to send the mails via your custom module then you can follow the below mentioned guide. Say, I had one Module called "Commerce Canvas(commerce_canvas)" 1. First Alter the Drupal's mail function to support links and add other encoding types /** * Implements hook_mail_alter() * @param string $message */ function ...


34

There is an official article and discussion regarding the same. You can't. Do not try Automated attacks (by far the most common attacks) do not even inspect the server before trying their exploits. Inspecting the logs of any high-profile site will show thousands of fruitless requests for /AspBB/db/betaboard.mdb _private/cmd.asp /scripts/../../...


32

In layman's terms, hooks are sort of bridges which provide a way for modules to interact with each other, alter each other's structure and data, provide new data etc. In most cases, the word hook_ in function names is replaced by the name of your module, and that provides a way for your module to tap into another module's operation. For example a drupal ...


31

One of the core developers wrote up an article a while ago called "Drupal programming from an object-oriented perspective". It does a good job of explaining how hooks can be thought of as implementing many of the common design patterns. The best explanation of hooks comes from the article: Drupal's hook system is the basis for its interface abstraction. ...


31

Hooks are called in order of Weight, which is defined per module in the database as {system.weight}. Lower weights come earlier in the calling process. Alphabetical, by module name. By default, modules get assigned a weight of 0, so nearly all hooks in the system run in alphabetical order. Some modules will adjust this in their install hooks so they run ...


29

Using unset() isn't a good solution for forms (as I think you know), as you never know what submit/validate handlers might be expecting the unset element to exist when they're processed. This can lead to unwanted errors. There are three methods you can safely use to 'hide' a form element Use '#type' => 'value' on the element, which will have the effect ...


26

As mentioned by Ivan Jaros You can use hook_preprocess_page_title. You just have to load the node from the route first, to get some context. function yourtheme_preprocess_page_title(&$variables) { // Load the node entity from current route if ($node = \Drupal::routeMatch()->getParameter('node')) { // Load the label of the bundle $...


25

This is off the top of my head so use caution... $query = db_select('node', 'n') ->fields('n', array('nid', 'title')) ->condition('n.type', 'test') ->condition('tn.tid', array(23, 37)) ->condition('n.title', '%' . db_like('name') . '%', 'LIKE') ->condition('n.status', 1) ->groupBy('n.nid'); // Add the COUNT expression $query-&...


23

You have to use hook_form_alter or hook_form_FORM_ID_alter Add your submit handler to $form['#submit'] like this $form['#submit'][]='my_submit' And write your code: function my_submit($form, &$form_state) { // your code }


20

The Bootstrap is the process Drupal goes through to build a page, basically running over all the core, theme and module code in order. It's basically how Drupal boots up, and prepares to do it's job as CMS. It's clever, in that it allows us to put hooks anywhere in our modules and themes, and the bootstrap process makes sure they get run at the right point. ...


20

hook_init() is invoked by Drupal only once for each requested page; it is the last step done in _drupal_bootstrap_full(). // Drupal 6 // // Let all modules take action before menu system handles the request // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('...


20

When Drupal runs cron tasks, it automatically handles any cron queue defined from modules, in drupal_cron_run(); first hook_cron() implementations are invoked, and then the cron queues are emptied. Inmplementing hook_cronapi(), you can add an entry for another function handling the cron queue of your module. function mymodule_cronapi($op, $job = NULL) { $...


17

hook_node_view() hasn't really been removed, the way it's invoked has just changed. As you mentioned, it's now handled by hook_ENTITY_TYPE_view(). So you can either use: hook_entity_view() or hook_node_view() The latter would make more sense if you're targeting nodes specifically.


16

You need to implement the hook_entity_presave() /** * Implements hook_entity_presave(). */ function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { switch ($entity->bundle()) { // Here you modify only your day content type case 'day': // Setting the title with the value of field_date. $entity->setTitle($...


15

To call the function of one module in another module: If the function is not in the .module file, call module_load_include() //Load node.admin.inc from the node module module_load_include('inc', 'node', 'node.admin'); Call the function from the other module function_you_want_to_call();


15

In Drupal forms, form_alter hooks can be used to change almost anything in the form. Additional submit handlers can be handled, validation can be done, elements can be added, etc. But for all of these to work, Drupal need to be the responsible party in both form build phase and the form submit phase. When you set $form['#action'] = url('https://[url path ...


15

You can get the display ID through the current_display property of the View object, e.g. $view = $vars['view']; if ($view->name == 'foo' && $view->current_display == 'bar') { // ... }


15

To get the content type of a node, you just use $variables['node']->getType() or $variables['node']->bundle(). The first method just calls the second, so calling one or the other one doesn't make much difference. public function getType() { return $this->bundle(); } The only difference is that bundle() is defined for every entity, since the ...


14

Bootstrap is the process during the which Drupal initializes itself; the process actually includes: Setting the error, and the exception handlers Initializing the value of some spec-global variables contained in $_SERVER Initializing some variables with init_set() Finding the cached version of the page to serve Initializing the database Setting the handlers ...


14

hook_init() is run on every page load except for cached pages, so depending on your use case that might be an option. function MYMODULE_init() { // Custom logic } hook_boot() is run on every page, including cached pages, so might be more useful (again depending on your use case). However if you have complex logic to process this will obviously slow down ...


14

You can do this by creating a theme suggestion alter hook in your theme. /** * Implements hook_theme_suggestions_user_alter(). * * An array of alternate, more specific names for template files or theme * functions. */ function MYTHEME_theme_suggestions_user_alter(&$suggestions, $vars, $hook) { // Define the view mode. $mode = $vars['...


14

You can't listen to an event. You can either use a hook or implement a method like postSave() in your custom entity. Here is the order of hooks and other events that happen during an entity save: Entity::preSave() is called on entity objects, and FieldItemListInterface::preSave() on field objects. hook_ENTITY_TYPE_presave() hook_entity_presave() Entity is ...


13

The views_plugin_query_default class has a query() method that will take the parameters currently held in the object and provide you with a standard SelectQuery (un-executed of course). Since the SelectQuery class implements the magic __toString() method you can then cast it directly to a string, which will be the SQL query itself: $select_query = $query-&...


13

The problem is upper/lowercase in your module name. To be able to run update functions, your module must consist of lowercase characters only. Unlike all other hooks, those are detected through regexes and the way it's implemented isn't compatible with mixed case.


13

When developing a module, you should keep in mind the following notes. The implementation of a hook done from a module is a function whose name is prefixed with the module short name (also called the machine name); from the hook name, take off the hook part, and replace it with the module machine name. For example, the implementation of hook_menu() done ...


13

Probably a little late to respond, but I came across this thread this morning whilst looking for a way to override the breadcrumb in Drupal 7, it helped a little so I thought I would add my solution. This creates extra crumbs based on content types and adds the current page to the crumb. I'm using this to add a crumb to a filtering view seen before the ...


13

You can implement the new hook_theme_suggestions_HOOK_alter() hook. Alters named suggestions for a specific theme hook. This hook allows any module or theme to provide altenative theme function or template name suggestions and reorder or remove suggestions provided by hook_theme_suggestions_HOOK() or by earlier invocations of this hook. You can use ...


Only top voted, non community-wiki answers of a minimum length are eligible