Hot answers tagged

27

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 $...


18

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.


18

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($...


17

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 ...


17

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 ...


16

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') { // ... }


16

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 ...


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();


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['...


13

The correct way of doing this is to respect Drupal's db transaction. If you want to do any database action in hook_node_insert you must consider that the node is not actually saved yet. which means if it fails and rolled back you end up with orphaned data in your database. So Drupal database API should be used and not direct query execution. If you want to ...


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

The way to do this is to use hook_flush_caches in combination with register_shutdown_function. Example code: /** * Implements hook_flush_caches(). */ function mymodule_flush_caches() { // After caches are cleared we will run mymodule_cache_rebuild() register_shutdown_function('mymodule_cache_rebuild'); // We don't want to add any custom cache-...


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 ...


13

Here is a working example I have pulled from a project and altered to have your module name. Add this at the top of your .module file: use Drupal\Core\Form\FormStateInterface; Then copy this in /** * Implements hook_form_alter(). */ function constellator_form_alter(&$form, FormStateInterface $form_state, $form_id) { // Adding custom validation ...


13

Sure, the function still exists: https://api.drupal.org/api/drupal/core%21includes%21database.inc/function/db_truncate/8.5.x. It's deprecated, though, with the advice: Instead, get a database connection injected into your service from the container and call truncate() on it. For example, $injected_database->truncate($table, $options); If you're not ...


12

Like this: if ($node->isNew()) { } Note that this only works before saving, in insert/update, it will always return TRUE, because the node has already been saved and is no longer new.


12

Generally speaking, only alter hooks can be implemented by themes, which means hooks like hook_form_alter() and hook_menu_alter(), or in short all those hooks that are invoked through drupal_alter() in Drupal 7 and lower (ModuleHandler()::alter() or ThemeManager::alter() in Drupal 8). Other hooks, which are invoked by module_invoke_all() (ModuleHandler::...


12

@vinhd proposition is correct, by the way you can also use the isEmpty() method from the field list interface. It can be more adapted for complex field types. if ( $node->hasField('field_your_field') && !$node->get('field_your_field')->isEmpty() ) { //... do something }


11

No, there isn't. Not really. At least not in 6 or 7. Assuming 7: If you will look at drupal_flush_all_caches() you will see it invokes hook_flush_caches(). This hook is meant to: "add cache table names to the list of cache tables that will be cleared by the Clear button on the Performance page or whenever drupal_flush_all_caches is invoked." It ...


11

It seems that it's impossible using only Drupal, which means: variable_set() itself doesn't invoke any hooks, but it uses db_merge(). That function is using the MergeQuery class. Now, it would be nice to hook with hook_query_alter(), but it only works for query classes that implements the QueryAlterableInterface interface. Sadly, this interface is now ...


11

Yes, you can implement any alter hook in a theme, as well as hook_theme() and preprocess hooks. Adding $form_state['redirect'] won't do anything there, though. You need to do that in a submit handler: function MYTHEME_form_phone_book_node_form_alter(&$form, &$form_state, $form_id) { $form['#submit'][] = 'MYTHEME_phone_book_node_form_submit'; } ...


11

When I did this a while ago I adapted the excellent field_example module from the Examples Module which is always the first place to look, as it has a lot of Drupal best practice in it. As they say in the module comments: * Providing a field requires: * - Defining a field: * - hook_field_info() * - hook_field_schema() * - ...


11

An .api.php file contains the hooks that a certain module supports, and is available for reference. It offers documentation and example code on how to use the hooks in other modules. It is not specific to Drupal 8 as several modules in Drupal 7 offer it as well. It does not actually implement or call the hooks and is for reference only. As for an example ...


11

In Drupal 8 the hook hook_node_validate() has been removed. Here are some suggestions. Reference: hook_node_validate() and hook_node_submit() have been removed. Field constraints If you're trying to validate an individual field, use a constraint. /** * Implements hook_entity_bundle_field_info_alter(). */ function ...


10

Variables are cached, so deleting manually is fine so long as you invalidate that cache, e.g. db_delete('variable') ->condition('name', 'mymodule_%', 'LIKE') ->execute(); cache_clear_all('variables', 'cache_bootstrap');


10

Here's how to do it with an entity builder callback. <?php use Drupal\Core\Form\FormStateInterface; use Drupal\node\NodeInterface; //Implements hook_form_FORM_ID_alter() function agenda_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) { $form['title']['#access'] = FALSE; $form['#entity_builders'][] = '...


10

Hooks are still implemented as global, procedural functions; you need to declare them in the .module file just like Drupal 7, not in a controller class: function MYMODULE_entity_update(Drupal\Core\Entity\EntityInterface $entity) { // ... } The system will move to OO in Drupal 9. It's also worth noting that hook_ENTITY_TYPE_update() also exists, so you ...


10

Simplify Menu sounds like what you'd want. The simplify_menu module uses a TwigExtension to gain access to Drupal's main menu's (or any other menu for that matter), render array so it can be accessed from a twig template. Among the many advantages of having full control of the menu's render array in a twig template is the ability to customize the ...


10

In an insert hook the user is already saved and should have an user id. So creating a node and assigning it to the new user as author should be no problem: /** * Implements hook_ENTITY_TYPE_insert() for user entities. * * Adds a first node for a new user */ function mymodule_user_insert(\Drupal\user\UserInterface $user) { \Drupal\node\Entity\Node::...


9

I wanted to contribute something additionally to this. I am not an advocate of hook_init() or hook_boot() for doing tasks like this but tend to look for specific hooks that accomplish what you want. These two hooks are very broad and while they do they job they are also sometimes called multiple times per page load. An alternative I would propose is ...


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