title: What is the basic concept behind hooks?

text:
# Question
Title: What is the basic concept behind hooks?
I am intermediate in PHP. To polish my skills I start learning Drupal 7. While learning Drupal architecture concepts, the terms *hooks* and *bootstrapping* puzzled me a lot. I read the "Pro Drupal development" book, and some documentation on drupal.org, but it is so advanced for me to learn how hooks work in Drupal to display the web page.

Can anyone tell me what hooks are in simple words?

# Answer
> 113 votes
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 data passed to it at that point in the code.

A nice straightforward example is hook\_node\_delete(). Any module can use it to make things happen every time a node is deleted. The docs tell you this hook passes the module the object of that deleted node to work with, and outlines other useful information such as about the exact timing of when it's called (e.g. that it is before the node data is actually deleted from the database), and where in Drupal's code the hook is called (which can be more than one place).

You can explore what hooks exist and find out what data is passed to them by exploring things starting with "hook\_" in the Drupal api.

Hooks work by a name conventions: using `hook_node_delete` as our example, when the node deletion process reaches the point where the hook is called, for every module with a function like this `[modulename]_node_delete()` where the word hook in the hook's name is replaced with the module's name (e.g. `my_amazing_module_node_delete()` ), those functions get called.

Why? So any module can do anything at these key points: for example you could look at the deleted node and do things if it meets a certain condition (say, email an administrator, or launch some long process).

Some hooks let you alter things that have been generated just before they're processed. For example, hook\_menu\_alter() passes you the current menu items that the system has generated. Any module can define a function some\_modulename\_menu\_alter() and look at them, optionally change them (delete some, add some, sort them...), and pass the newly altered menu back in.

It's simple, really powerful and is at the heart of how Drupal works as a modular system. Implementations of hooks are at the heart of most Drupal modules.

When looking through the code of a Drupal module, you can spot which functions come from hooks (as opposed to functions that are simply called from within the module code itself), as the Drupal community enforce a convention whereby each implementation of a hook has a comment in front of it like this (note the "Implements hook\_..." bit):

```
/**
 * Implements hook_some_hook().
 *
 * Some descriptive summary of what this does
 */
function my_amazing_module_some_hook() {

```

Some modules that act as APIs define their own hooks. For example, Views defines many hooks that allow you to add to, read and edit data at various points in the process of creating or displaying a view. You can find information about hooks created in custom modules from two places (assuming the module follows conventions etc):

* The code and comments in the `modulename.api.php` file in the module folder
* drupalcontrib.org \- for example, here's their list of D7 modules they have info on, and here's their page of Views hooks

Bootstrapping is, as others explained, basically booting up - I won't duplicate the other good clear explanations.

# Answer
> 55 votes
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 frequent pattern in Drupal is having a `[DATATYPE]_info` hook, and a `[DATATYPE]_info_alter` hook. If you want to create a new field type, you will implement `hook_field_info()`; if you want to manipulate an existing one, you will implement `hook_field_info_alter()`.

The observer pattern is *object* oriented, which Drupal 7 is still, mostly, not. There is however a wiki page, Drupal programming from an object-oriented perspective (Created by JonBob on April 4, 2005), which explains how Drupal uses object oriented code patterns despite this. It's interesting to note that it mentions observers, but not visitors.

This is still rather early, and is subject to change, but I want to add that while hooks have for quite some time been the de-facto standard in adding functionality to Drupal, the concept of plugins will become much more visible in Drupal 8, and will give us new ways of interacting with Core. See the relevant issue, and documentation.

# Answer
> 34 votes
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 core module called "node" invokes various hooks. One of them is `hook_node_update` which gets invoked everytime an existing node is updated. When this hook is invoked, your module's (say we call it `mymodule`) implementation of `hook_node_update` is called, which in this case will be a function in your module's .module file called `mymodule_node_update` (Obviously this function can be in any file in your module's folder as long as it's included in the .module file as well). This hook will also be passed the necessary parameters (variables) which it can use, modify and/or return back to the function that invoked the hook.

When I first started learning Drupal, I was in the same boat as you are now, it's bit tricky to grasp at first, but once you get it, it's oh so simple and intuitive. Good luck.

# Answer
> 32 votes
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. Hooks define the operations that can be performed on or by a module. If a module implements a hook, it enters into a contract to perform a particular task or return a particular type of information when the hook is invoked. The calling code need not know anything about the module or the way the hook is implemented in order to get useful work done by invoking the hook.

# Answer
> 21 votes
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.
For example if you use 'hook\_form\_alter' to add a custom check-box to a form, Drupal's bootstrap will make sure it runs that code, just before it renders your form.

One issue with the bootstrap is that the entire process takes time to run, even if you are only returning a small amount of data. When using Drupal with the services module as an API and returning many small XHTML or JSON responses, running through the entire bootstrap isn't very performant. Some clever people are looking at clever ways around this for Drupal 8.

But for rendering normal Drupal pages, the bootstrap process works great, it uses Drupals caching system to speed things up, and gives you total control over every part of your site. If you do find your site slow, you can always use something like APC or MemCached to help speed things up.

I hope my answer was accurate and explains things simply for you, I'm no expert, but I think that's how it works.

# Answer
> 15 votes
*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 that load files when a class, or an interface is not found
* Initializing the Drupal variables
* Initializing the PHP session
* Initializing the language variable
* Loading the enabled modules

Except some operations that are specific for a Drupal version, most of the operations are independent from the Drupal version.

A hook is a PHP function that can be called from Drupal, or third-party modules, when necessary to do a task. Instead of having a prefixed list of functions to call, the list is build checking the enabled modules, and the functions they implement.
For example, Drupal uses `hook_node_update()`; when a node is being saved with `node_save()`, the following code is executed.

```
// Call the node specific callback (if any). This can be
// node_invoke($node, 'insert') or
// node_invoke($node, 'update').
node_invoke($node, $op);

```

What `node_invoke()` does is:

* Getting the list of all the enabled modules
* Checking if the enabled modules has a function whose name ends in "\_node\_update" and starts with the short name of the module
* Calling that function, passing `$node` as parameter

Hooks can save their own data in a database, or alter the value returned from a function. The last case is, for example, what happens with `hook_form_alter()`, which alters the value of `$form` passed as reference to `drupal_prepare_form()`.

Drupal hooks are generally invoked using three functions:

`drupal_alter()` is the function used to invoke specific hooks whose purpose is to alter the data passed them as reference, such as `hook_form_alter()`, `hook_hook_info_alter()`, and `hook_tokens_alter()`.

There are other functions that are used to invoke hooks, such as `node_invoke()`, but those functions essentially use one of the functions I listed before.

# Answer
> 11 votes
Hooks are pointcuts and `module_invoke_all()` is the weaver. (The implementation isn't clear and there are other weaving functions.) As far as I am aware, Drupal is the only system to implement AOP with PHP functions.

See also How does AOP work in Drupal? where one of the answers states:

> Drupal mimics AOP paradigms through hooks, which basically allow developers to weave in bits of code during the flow of execution. You can take a look at the hooks a developer can implement on the list of Drupal hooks shown in the Drupal documentation site, which just lists the hooks invoked from Drupal core and its modules.

Putting it in different words, as another answer does:

> Drupal's AOP paradigm might be better visualized as event-driven, and it all happens through Drupal's concept of hooks. For example, when you do the following:
>
> * Write a module called mymodule
> * In mymodule.module, create a `mymodule_init()` function
> * Install this module in Drupal
>
> What you are declaring is, in pseudo-code:
>
> ```
> subscribe mymodule to "hook events" of type init
>
> ```
>
> When Drupal's core then runs `module_invoke_all('init')`, Drupal is saying:
>
> ```
> notify all subscribers to "hook events" of type init that this has occurred
> by passing any relevant arguments to them
> and letting them run the code they define in their hook_init()
>
> ```
>
> So while PHP is still a procedural language—and your `mymodule_init()` could do all sorts of crazy, un-encapsulated things if you really wanted—Drupal is still in charge. Drupal in a sense decides whether or not to call your code in the first place.

# Answer
> 6 votes
If you want to see the hooks Drupal lets you call, go to api.drupal.org, tab over to the search box, and type 'hook\_'. This will give you a big list of most of the hooks defined by Drupal. Do the same thing for '\_alter' and see even more.

The Node API Hooks page offers a chronological list of all the hooks invoked during node operations. You can see the Node module and the Entity and Field systems giving each other turns at invoking hooks.

For instance, if you scroll down and look at the section for `node_load()`: The Node module will give you a hook\_load(), and then pass control to the entity system which loads some fields. There are a whole host of field hooks not listed, and then when that's over the entity system invokes `hook_entity_load()`, before passing control back to Node which invokes `hook_node_load()`.

This gives your code the chance to act on the node in question as it is loaded, piece by piece. Learning these hooks and when and why they're called is part of the adventure of Drupal coding. :-)

Other systems have hooks, too. Such as `hook_init()` and `hook_boot()`. This gets to the bootstrap part of your question. `hook_boot()` is invoked by Drupal before the caching system has loaded. So if your module needs to do something before Drupal has really started up, and you want your code to run regardless of caching, then you'd implement `hook_boot()`. Otherwise, if you only care about pages that aren't cached, you'd implement `hook_init()`.

This gives you the option of implementing something early in the loading process, before Drupal has fully booted, while giving you some flexibility as to which point in the process you want to intercept.

If you need to make sure Drupal has booted to a certain point before you proceed, you can call `drupal_bootstrap()`. If you click through to that documentation you can see the bootstrap levels available, from nothing to everything.

And, finally, you can see some extensively documented code for any given subsystem at the Examples project.

# Answer
> 6 votes
Hooks are php functions, building blocks based on the naming conventions "yourmodulename\_hookname", they are meant to ease developers ability to create **modules**.

Modules are the real deal because they enable both CORE and custom functionalities in your Drupal system. Thus, modules are made of **hooks** and when a module is activated in your Drupal install, its hooks functions can be called from others modules thanks to the module.inc function module\_invoke\_all($hook) or module\_invoke.

Therefore, to properly understand what hooks are, you should really get your hands dirty and try module development. For this purpose, get started by downloading and trying some of Drupal's Examples for Developers, you should get familiar with modules creation as well.

Here are some of the useful Drupal's examples for developers mentioned above :

**hook\_block\_view()** implementation example in block\_example module

```
/**
 * @file examples/block_example/block_example.module line 127
 *
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function block_example_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'example_configurable_text':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Title of first block (example_configurable_text)');

```

This hook give you access to Drupal's blocks creation to display custom blocks on your website. It is possible because the block.module has a \_block\_render\_block function which enable all modules to define their hook\_block view (notice the module\_invoke last line):

```
/**
 * @file modules/block/block.module, line 838
 *
 * Render the content and subject for a set of blocks.
 *
 * @param $region_blocks
 *   An array of block objects such as returned for one region by _block_load_blocks().
 *
 * @return
 *   An array of visible blocks as expected by drupal_render().
 */
function _block_render_blocks($region_blocks) {
  ...
  foreach ($region_blocks as $key => $block) {
    ...
    $array = module_invoke($block->module, 'block_view', $block->delta);

```

**hook\_menu()** implementation example in render\_example module

```
/**
 * @file examples/render_example/render_example.module line 22
 *
 * Implements hook_menu().
 */
function render_example_menu() {
  ...
  $items['examples/render_example/arrays'] = array(
    'title' => 'Render array examples',
    'page callback' => 'render_example_arrays',
    'access callback' => TRUE,
  );

```

This hook is linked to Drupal's url routing system and define url patterns with associated render callbacks used by your module. It is invoked from system.module.

About the bootstrap, basically, you just need to know it is executed on each page request. I really advise you to read this stackoverflow answer, it explains how bootstrap and hooks are related but separated.

Regarding display of the web page, Drupal's website html display is mostly achieved with render arrays and theming.

# Answer
> 3 votes
Anywhere a module calls module\_implements() http://api.drupal.org/api/drupal/includes%21module.inc/function/module\_implements/7 Drupal will fire all the correctly named functions in the right order based on their weight. These are called hook functions because in the documentation for modules that use module\_implements you see things like hook\_menu (for when the menu calls all functions designed to return menu items). The word "hook" just needs to be replaced with the name of the module implementing it and Drupal does the rest.

There is also a drupal\_alter() function that fires all the correctly named alter functions, with the intention to let you alter things that were previously registered by another hook.

Generally alters will pass in arguments by reference so you can edit the object directly, whereas "normal" hooks usually get you to return new things.

The idea is that any module (including your own) can easily be extended by asking Drupal to call all the required hook functions and get back what they return to be processed. The module calling the hook functions doesn't need to know anything about the modules that implement the hooks, and the modules implementing the hook don't really need to know anything about the module calling the hook. The only thing both modules need to know is the structure of the data being returned or altered.

In practice hooks are most commonly usually used to:

* respond to events, like hook\_user\_login is called when a user logs in
* register something new that can be used to extend the system like hook\_menu
* theme/render html or build/validate/submit forms

# Answer
> 1 votes
You have a lot of answers above but i want to give an answer in much simpler way to understand the very basic concept behind hooks. Hooks are actually built in functions in drupal core to manage different things & done different jobs in core, you can synchronized your own functions with these built in functions of drupal core to add their functionality in your own functions by calling different hooks.

I hope you will get the point!

# Answer
> 1 votes
To me it's all about the module\_implements function when it comes to hooks and core (D7). One thing that I think is crucial to understand is that by writing a hook to modify something, you by no means have the last say in what happens to the data structures you are dealing with. Your hook simply gets in the line (queue) of functions that are ALSO acting on the same data structures whether those be menus, menu\_links, blocks, nodes, users or any entity or render element.

So to really see your hooks be utilized in an expected fashion you need to know or be aware of where you (your hook) stands in line. This is determined by your mondule's weight. Drupal core simply calls the properly named hooks in the ascending weight order and whatever happens to the data happens.

I've written hooks before that didn't have any effect, only to learn after hours of headbanging that my module weight was too light and sub-sequent hooks were effectively un-doing what I did or totally disregarding it all together.

A well written hook will not "man-handle" or "force" themselves to be last but will "place nice with others" by making sure they maintain the data structures as expected by the rest of the hooks down the line.

And speaking of "The Line" of hooks. Over the years I've trolled google for Drupal stuff, this image seems to be a good representation of the preprocess and process hook list of possibilties.

# Answer
> 1 votes
Hooks. Allow modules to interact with the Drupal core. Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo\_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook.

# Answer
> 0 votes
In much simpler way, hooks help the developer to alter the existing functionality according to the requirements without making changes to the existing code. More like Abstract function in php.

Example: You have created a module for booking a bus ticket. According to your code if the ticket is once booked then pick up location is not editable which was your requirement for that project.Suppose your friend need the same module for similar requirement with exception that the user can change the pickup location. Somehow he has to use your module and you do not want him to do any code changes. So you provide a interface(hook in our case) where he could implement his changes without making changes in your module.

In drupal till drupal-7 we have hooks for modules as well as themes. To know how hook works check is drupal.org hooks to create a custom hook check this link

---
Tags: hooks, bootstrapping
---


# Question
Title: How to render a block provided by a contrib module in a node template
I installed Better Social Sharing Buttons and I can not understand how to programmatically display the block of this module in `node.html.twig`. I display the blocks created by me like this:

```
function MYTHEME_preprocess_node(&$variables) {
  $block_entity = Drupal\block_content\Entity\BlockContent::load(6);
  $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'foo bar');
  $variables['MyCustomBlock'] = $block_view;
}

```

and then `{{ MyCustomBlock }}` in `node.html.twig`.

How to display the block created by the Better Social Sharing Buttons module?

# Answer
Go for Twig Tweak.

> Twig Tweak is a small module which provides a Twig extension with some useful functions and filters that can improve development experience.

Then it's just

```
{{ drupal_block('better_social_sharing_buttons_block') }}

```

Read the docs about Rendering blocks with Twig Tweak.

> This subject is rather confusing because too many things in Drupal are referred to as "Blocks". So it is essential to understand what kind of block you are going to render. This guide covers three main cases you may deal when rendering blocks in a Twig template.
> 3 votes

---
Tags: 8, theming, blocks
---


title: Add a table class name to a View table

text:
# Question
Title: Add a table class name to a View table
Can I add a custom table class name to a View that outputs a table, Or just add the name of the view to the table class name? There isn't a setting in Views to add a table class name, you can only add row class names.

My View name is view-a1. I would like to the name of the View to all table class names.I am trying to do it with hook\_preprocess\_views\_view\_table. But I don't know how.

The default twig template uses this markup

The method in the url below worked, it will add a custom hardcoded table class name. I changed the hook in the example to hook\_preprocess\_views\_view\_table. What I really want to do it add the name of the View as the table class name. How can I do that?

https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file

# Answer
> 2 votes
Using Datatables too, I had to add an ID to a table generated by a View displaying a page (system name = page\_1).
I did that duplicating `views-view-table.html.twig` into `views-view-table--members--page_1.html.twig` and changed

```
<table{{ attributes.addClass(classes) }}>

```

into

```
<table{{ attributes.addClass(classes) }} ID="ListOfMembers">

```

Maybe that can help you...

# Answer
> 3 votes
Views have the **CSS class** option under `Advanced` (third column). There you can set the class to be output to all displays of that Views or override for single Displays.

Most themes won't output that class directly on the `<table>` element, it is usually output on a `<div>` that contains the table.

That can be enough for styling in CSS, but if you want you can override the twig template or use the preprocess function in your theme for more control.

# Answer
> 3 votes
Try this out it works for me:

```
use Drupal\Component\Utility\Html;
/**
 * Implements hook_preprocess_views_view().
 */
function MYTHEMENAME_preprocess_views_view_table(&$vars){
  $view = $vars['view'];
  $vars['attributes']['class'][] = Html::cleanCssIdentifier($view->id());
}

```

---
Tags: views, 8, theming
---


# Question
Title: How to programmatically set the node updated/changed timestamp
Some migrated content needs the "updated" timestamp set to the original timestamp, instead of the time the node was saved duration migration.

Setting the "changed" field in the database appears to have no affect for the node updated time?

Here's a sample query:

```
update node_field_data set changed = 1535805325 where nid = 2148716;
Query OK, 1 row affected (0.01 sec)
...
select nid,changed,from_unixtime(changed) from node_field_data where nid = 2148716;
+---------+------------+------------------------+
| nid     | changed    | from_unixtime(changed) |
+---------+------------+------------------------+
| 2148716 | 1535805325 | 2018-09-01 12:35:25    |
+---------+------------+------------------------+
1 row in set (0.02 sec)

```

When loading the node, the original `changed` timestamp is returned:

```
[changed] => Array
(
    [x-default] => 1532090833
)

```

I've tried clearing all caches, including clearing the cache tag and fully restarting the cache services (redis+varnish), but to no avail, the previous changed timestamp is always returned!

Any suggestions on how to set the updated/changed timestamp for this case?

# Answer
OK, for this approach, the solution was to ensure another table was also updated with the changed timestamp: `node_field_revision`

e.g:

```
update node_field_revision set changed = 1535805325 where nid = 2148716 and vid = 2803575;

```

After that, a normal cache clear showed the new updated timestamp for the node.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: Drupal 8 Metatag and Media Entity modules to set meta image tags
On a Drupal 8 content type, I have a field with an entity reference field to a Media Entity field. I would like to use the Metatag module to set the image that is on this Media entity in the og:image meta tag.

* Featured Image - `[node:field_im]` \- Returns the entity name
* Featured Image type with delta 0 - `[node:field_im:0]` \- Returns the entity name
* Media - `[node:field_im:0:entity]` \- Returns the entity name
* Media ID - `[node:field_im:0:target_id]` \- Returns the entity ID

In Drupal 7, the following token was available:

`[node:field-fimg:0:file:url]`

But I don't see anything like it in D8. Could someone point me in the right direction?

# Answer
If I understand your question correctly you'll need to do the following:

* Check on your modules page that the "Metatag: Open Graph" submodule is enabled.
* Go to metatag config page (Configuration \> Search and metadata \> Metatag).
* Add a new "default metatag" and select your content type in the "Type" selectbox.
* Fill in the rest of the fields similar like following picture (just don't forget to use your own field names:

Here are some things you need to know about my tokens:

* field\_teaser\_img: is the fieldname of my media entityreference on my content type.
* field\_me\_img: is the fieldname of my image field on my media entity type.
* facebook: is the imagestyle name I created for these metatags
* height, mimetype & width: are property fields of the media entity type yet I didn't create those fields but it does seem to work.

I hope this helps.
> 9 votes

# Answer
From http://drupalsun.com/glassdimly/2017/08/23/drupal-8-how-get-image-style-tokens-metatags

```
[node:field_my_image_field:entity:field_image:my_image_style:url]
[node:field_my_image_field:entity:field_image:my_image_style:width]
[node:field_my_image_field:entity:field_image:my_image_style:height]

```

This worked very well for me, where `field_my_image_field` is my media-reference-field name
> 2 votes

---
Tags: 8, media, meta-tags
---


# Question
Title: What is the equivalent of calling drupal_lookup_path()?
`drupal_lookup_path()` have been remove in Drupal 8. However, I cannot find a way to achieve the same functionality. All, I'm trying to do is to provide Drupal with a path and he is going to look to see if exist, if exist is going to provide me the node id. If does not exist that path he going to give me an error or null/0.

How can I achieve this on Drupal 8?

# Answer
> 4 votes
**Drupal 7:**

```
$path .= drupal_lookup_path('alias', $path);

```

**Drupal 8:**

```
$alias =
  \Drupal::service('path.alias_manager')
    ->getPathAlias($path);

if (strcmp($alias, $path) == 0) {
  $alias = '';  // No alias was found.
}

$path .= $alias;

```

Reference Link

***8 calls to drupal\_lookup\_path()***

# Answer
> 4 votes
In my case i got it work by using this

$path = "certainpath"; $alias = \Drupal::service('path.alias\_storage')-\>aliasExists($path, 'en');

it will return true if path exists.

---
Tags: 8, path-aliases
---


# Question
Title: How can I make SMTP plugin work with multiple languages?
I'm using the SMTP Authentication Support plugin for mail from my Drupal 8 server.

Sending mail from a webform works fine as long as the visitor is using the default language, which is English. It does *not* send when using any other language.

The message in the error log is not helpful:

> Error sending e-mail from email@site.com to email@site.com: SMTP Error: Could not connect to SMTP host.

This makes no sense to me. How can it not be connecting, when the same connection information is ok on English?

How can I resolve this? Here's what I've tried to do:

* I've asked for support on SMTP's issues page, but have not received any response yet.
* Set the language detection up two different ways: by domain or by URL. Same result on both.
* Tried two different SMTP servers, with the same result on both.
* Tried SSL and standard protocols for SMTP.

# Answer
> 2 votes
The problem is that the parameters are not translatable. In my case it has been solved by overriding the values of the port and protocol variables in `settings.php`.

```
$config['smtp.settings']['smtp_port'] = '587';
$config['smtp.settings']['smtp_protocol'] = 'tls';

```

# Answer
> 1 votes
I applied this patch https://www.drupal.org/node/2865696

After that I copied smtp.settings.yml in the language folder, and I launched drush cim.

I don't know if you use cim/cex for configuration management, but in this way I can send email in other languages

# Answer
> -1 votes
Just for someone who is using Drupal 7 to fix the same issue, because this module's Drupal 7 version does not even have that stupid smtp.schema.yml file. For Drupal 7, go to /sites/all/modules/smtp and in that folder, edit the file called smtp.phpmailer.inc. Find out "Sets connection prefix." and change the "public $SMTPSecure = '';" into "public $SMTPSecure = 'ssl';". Then remember to clear the cache and reenable the SMTP module.

---
Tags: 8, emails
---


title: How to change the markup for a field

text:
# Question
Title: How to change the markup for a field
I'd like to change the output from the field formatter view from the Field API. I'd like a cleaner markup without unnecessary tags. What's the best way to clean up field formatter view output? Many thanks.

Ideally to change from this:

```
<div class="field field--name-field-visualisation field--type-mango-maker field--label-above">
    <div class="field__label">Visualisation: </div>
    <div class="field__items">
        <div class="field__item even">
            <div class="something"></div>
        </div>
    </div>
</div>

```

to this:

```
<div class="field field--name-field-visualisation field--type-mango-maker field--label-above">
    <div class="field__label">Visualisation: </div>
    <div class="something"></div>
</div>

```

heres my hook\_function\_field\_formatter\_view function:

```
function mango_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

  $output[0] = array(
    '#theme' => 'container',
    '#attributes' => array(
      'class' => array('something'),
    ),
  );
  return $output;
}

```

# Answer
> 0 votes
If you want to change output of the field in a Views, use Semantic Views

You can also turn on the Theme Developer module, check which .tpl is used to display piece of content you want to change and then create this file in a way you want.

Another modules that provide similar functionalities are:

Quickest solution, just turn this module and forget about drupal's nested divs:

Fences

More complex, this lets you to set up fields markup - for views as well as full node:

Semantic CCK

The most complex, apart from fields markup, this lets you to set up columns, headers, footers etc. inside of full node view, as well some views integration:

Display Suite

# Answer
> 0 votes
I recently came to this same obstacle and managed to find a solution. @15dk51 did an excellent job of explaining the answer to this.

Removing divs added by render and node.tpl.php

Best solution I found was installing Fences which has effectively removed allot of the "drupal rendered" css classes which seem unnecessary when building your own theme.

I hope this helps.

# Answer
> 0 votes
I always lean to templates when I can. Using templates is a great way to control the markup of your fields or other elements in a Drupal friendly way.

More than likely you would be looking at creating a file called "field--name-field-visualisation.tpl.php" or whatever your field name is.

Reference: https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7.x

Couple things to help when using .tpl template files... Depending on your site configuration, you may have to add theme hook suggestions to "$variables" in your theme file. Also, kpr() or dpm() is your magic for finding what's available how to print it in your template file.

Don't forget to clear cache when you create a new template file!

Related reading: https://www.drupal.org/docs/7/theming/template-theme-hook-suggestions

# Answer
> 0 votes
There are two crucial guides I'd like to warmly recommend to you: Core templates and Template suggestions.

You want to completely customize the markup of one field. Then you need to find your current theme's or base theme's `field.tpl.php` file and duplicate that into your theme's `/templates` folder. Then you can rename it along the following patterns (choose one) to selectively customize the output for only one desired field (instead of overriding markup globally for all fields):

```
field--FIELD-NAME--NODE-TYPE.tpl.php
field--NODE-TYPE.tpl.php
field--FIELD-NAME.tpl.php
field--FIELD-TYPE.tpl.php

```

---

Additionally (and this only is an extra step after you tried to tweak things with the above options) you can also provide your own custom field formatter to fine-tune the field value output even more.

See the answers to How do I write an additional field formatter for an existing field?, which will tell you to implement `hook_field_formatter_info()` and `hook_field_formatter_view()`, both.

---
Tags: 7, entities, theming
---


title: Modify date popup structure

text:
# Question
Title: Modify date popup structure
I would like to modify the date popup structure, in the image below you can see how date module builds the element. Drupal's default label is hidden, and it generates other to display the title. I want to show that label, and hide the date module label. Where should i modify this? Using some hooks in a .module, create a custom template or just overwrite it with css? Thanks all for help!

PD: This change must concern to every page in my site.

# Answer
> 1 votes
Override `theme_date_popup` in your theme or custom module.
See the following tutorial how to do it.

---
Tags: 7, theming, hooks, datetime
---


# Question
Title: How to add a column to DB with weight by using hook_update_N?
I want to add a column to a database by using hook\_update\_N(), but it should be 3rd column instead of last column. How I can achieve that please help in this regard. I tried to add **weight** but not working. below is my code which is creating a column at the last in the existed table.

```
function test_update_7001() {
  $column3 = array(
    'type' => 'varchar',
    'length' => 256,
    'not null' => FALSE,
    'weight' => 3,
  );
  db_add_field('test_table', 'column3', $column3);
}

```

# Answer
`db_add_field` doesn't support `AFTER`, which you would need to create your desired query.

You'll need to build an appropriate SQL string and run it through `db_query()` instead.
> 1 votes

---
Tags: 7, database, hooks, updating
---


title: How to call a function in a Twig file

text:
# Question
Title: How to call a function in a Twig file
Let's say I create a function in a module file:

```
function _get_test() {
  return 'test';
}

```

How can I call this in any Twig file? For example `*.html.twig`, `page.html.twig`, `node.html.twig` etc.

OR

How can I pass a variable from PHP to Twig and display in any Twig file. For example `*.html.twig`, `page.html.twig`, `node.html.twig` etc.

# Answer
You can define your own custom Twig functions in a custom module (but not in a theme). To find an example for how to do this, see this example in `core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php`.

---

Also see this blog post: Create Twig extensions for Drupal 8.

> In this example, we will build an extension to display a Drupal block directly in a Twig template:
>
> ```
> {{ display_block('my_block_id') }}
>
> ```
>
> **src/MyTwigExtension.php**
>
> ```
> <?php
>
> namespace Drupal\MyTwigModule;
>
> /**
>  * Class DefaultService.
>  *
>  * @package Drupal\MyTwigModule
>  */
> class MyTwigExtension extends \Twig_Extension {
>
>   /**
>    * {@inheritdoc}
>    * This function must return the name of the extension. It must be unique.
>    */
>   public function getName() {
>     return 'block_display';
>   }
>
>   /**
>    * In this function we can declare the extension function
>    */
>   public function getFunctions() {
>     return array(
>       new \Twig_SimpleFunction('display_block',
>         array($this, 'display_block'),
>         array('is_safe' => array('html')
>       )),
>   }
>
>   /**
>    * The php function to load a given block
>    */
>   public function display_block($block_id) {
>     $block = \Drupal\block\Entity\Block::load($block_id);
>     return \Drupal::entityManager()->getViewBuilder('block')->view($block);
>   }
>
> }
>
> ```
>
> **src/MyTwigModule.services.yml**
>
> ```
> services:
>   MyTwigModule.twig.MyTwigExtension:
>     class: Drupal\MyTwigModule\MyTwigExtension
>     tags:
>       - { name: twig.extension }
>
> ```
> 9 votes

# Answer
You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess

```
function MYTHEME_preprocess(array &$variables, $hook) {
  //this is a global hook, its variables are available in any template file
  $variables['foo'] = 'bar';
}

```

`{{ foo }}` will then render `bar`, but this global preprocess might run into caching problems though
> 4 votes

---
Tags: 8, theming
---


# Question
Title: How to restrict each user to making only 1 comment per node?
Does anybody know if there is any way I can restrict each site user to making only one comment per node on my Drupal 7 site? I haven't found anything yet.

I've just tried a complicated setup with flags and rules and triggers and actions and redirects. This didn't work too well.

# Answer
> 8 votes
Implement `hook_form_alter()` in a module. If the form is the node comment form, check if the currently logged-in user has commented on this node earlier. (You might have to write a custom function for this.) If the user has commented on the node, disable the submit button and the textarea.

# Answer
> 1 votes
Tagged Drupal 7, but I'm going to throw caution to the wind and supply an answer for Drupal 8…

My method: hide the form completely by setting `$form['access'] = false;`

Here's some code for *mymodule.module* that identifies the parent node, then does a database query on the comments attached to it, filtered by user. (This is taken from a project where I'd creating a "ratings" comment type in addition to standard comments).

```
/*
 * Implements HOOK_form_alter
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  switch ($form_id) {
    // change this to the correct form name for your site
    case 'comment_ratings_form':
      $current_user = \Drupal::currentUser();

      // Find which node this comment form is attached to
      $comment_entity = $form_state->getFormObject()->getEntity();
      $review_nid     = $comment_entity->get('entity_id')->target_id;

      // Remember: the comments field in a node doesn't contain the actual
      // comments, just settings and stats.  We need to do an entity query
      // and find all the comments pointing to the node.

      // Has user already commented?
      $rating_ids = \Drupal::entityTypeManager()
                           ->getStorage('comment')
                           ->getQuery('AND')
                            // attached to the current node
                           ->condition('entity_id', $review_nid)
                           // authored by current user
                           ->condition('uid', $current_user->id())

                           // if you have multiple comment types, you could
                           // filter by those too
                           //->condition('comment_type', 'ratings')

                           ->execute();

      if (!empty($rating_ids)) {
        // already commented, hide the form
        $form['#access'] = FALSE;
      }
      break;
  }

}

```

# Answer
> 0 votes
5 years later ... If you don't want to write custom code, or use the Comment limit module (which only has a dev version for D7), then you can use the Rules and Flag module for this, as described below.

# Step 1: flag nodes with comments

Use the Flag module to create a (none-global) flag with a label of something like "Comment submitted" (and machine name `comment_submitted`).

# Step 2: register comment submission

Use Rules to create a custom rule with Rules Event "*After saving a new comment.*".

This rule should perform a Rules Action "Flag node" (using the flag created in step 1).

# Step 3: unpublish additional comments

Use Rules to create a custom rule to unpublish additional comments from users for nodes to which a user commented before (= nodes that were flagged by the comment author). Here is the rule you can use for that (in Rules export format, update the machine name of the flag you use and then import it in your own site):

```
{ "rules_unpublish_additional_comments" : {
    "LABEL" : "Unpublish additional comments",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "flag_flagged_node" : {
          "flag" : "comment_submittedr",
          "node" : [ "comment:node" ],
          "flagging_user" : [ "comment:author" ]
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "comment:status" ], "value" : "0" } } ]
  }
}

```

**Note**: this rule does as in the title of Step 3 (= *unpublish additional comments*). So it does not hide the comment form (which is not asked explicitly in the question either). Adding a "set message" as an extra rules action could help clarify that. So as per the comment from OPer below the question, this answer should illustrate that there is "a" way to achieve a similar result using Rules (which I'd rather use instead of adding another module which has a dev version only).

---
Tags: 7, users, comments
---


# Question
Title: How to provide a specific node template in a custom module
I am using a custom module and using Bartik theme(from Drupal 8 core module) and hence need to define a content type specific template like node--\[type\].html.twig

I added hook\_theme in my custom module as follows

```
function custom_autofill_reference_theme($existing, $type, $theme, $path){
   drupal_set_message($path);
   return [
    'node' => [
      'path' => $path . '/templates',
      'template' => 'node',
    ],
  ];
}

```

but not sure on how to add a content type specific template in a custom module without the need to create a custom theme?

# Answer
> 5 votes
```
/**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'node__custom_content_type' => [
      'base hook' => 'node',
    ],
  ];
}

```

Then make sure that you have the content type template under `custom/templates/node--custom-content-type.html.twig`

---
Tags: 8, theming
---


# Question
Title: Entity Reference - User reference field Hide "Restricted access" label instead of showing useless choices
i have an entity reference (7.x-1.5) select-list within a checkout pane which is being used to allow the user to attach a child to a product during a checkout process.

The user can add multiple "child" under their account via field collections

The user adds a product to their cart, then checks out. During the checkout they can select a "Child" to be attached to the registrations.

My issue is when a user goes to checkout, the select list is constantly growing in values the user(from every user). The current user does not have access to these fields so the select list values simply say: `-Restricted access-`.

I assumed this would only show values from the logged in user, but apparently, the widget grabs ALL values from every user but hides the data the current user does not have access to. I simply need to hide all data which says `-Restricted access-` this data so if the user has not entered any "child" field collection data, there will be no option to select from.

Has anyone ever dealt with this issue, and what options are there to fix this? I can simply use an autocomplete widget to solve this issue, but this is poor UX in my opinion.

# Answer
You change the reference widget to use Views as a filter to provide the options with Views Reference Filter. Then in Views, provide this users UID as a contextual argument to only get their own relationships instead of every user.
> 1 votes

---
Tags: 7, entities, users
---


# Question
Title: Sub-theme navigation menu and footer menu not showing
I have created a sub-theme using a purchased theme. While creating sub-theme I followed these steps as mentioned in the documentation:

1. I have created `subtheme.info.yml` and `subtheme.libraries.yml` files.
2. I have also copied regions to `subtheme.info.yml` file from `basetheme.info.yml`.
3. Then created context as it was there on base theme.

Now everything is working fine but main navigation and footer links are not showing. I also confirmed the position of each block in "Block layout".

I am new to drupal so not getting how to solve this issue. I am using drupal `8.6.1`

**EDIT 1**

Here are some images get idea about the issue:

**Headers**

Above screenshot is from parent theme as a default.

Above screenshot is from sub-theme. Here you can see the nav links and logo text link is missing

**Same with footers:**

Footer parent theme

Footer sub-theme. Links/Blocks missing.

**yml files**

Subtheme: https://pastebin.com/KmhD2BSh

Parent Theme: https://pastebin.com/T1XQq8T8

**EDIT 2**

**subtheme.theme**

(I picked it from official resource but added after the subtheme was set as default)

```
/**
 * Implements hook_theme_suggestions_HOOK_alter for blocks.
 */
function subtheme_theme_suggestions_block_alter(&$suggestions, $variables) {

  // Load theme suggestions for blocks from parent theme.
  foreach ($suggestions as &$suggestion) {
    $suggestion = str_replace('subtheme', 'virgor', $suggestion);
  }
}

```

**EDIT 3**

I noticed all the links on navigation bar including logo text link is showing on other pages like contact, blog but the styling is not getting applied to them. And getting this error inside console:

```
js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:2062 Uncaught Error: Quick Edit could not associate the rendered entity field markup (with [data-quickedit-field-id="node/5/uid/en/teaser"]) with the corresponding rendered entity markup: no parent DOM node found with [data-quickedit-entity-id="node/5"]. This is typically caused by the theme's template for this entity type forgetting to print the attributes.
    at processField (js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:2062)
    at HTMLSpanElement.<anonymous> (js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:2179)
    at Function.each (js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:2)
    at r.fn.init.each (js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:2)
    at Object.attach (js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:2178)
    at js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:62
    at Array.forEach (<anonymous>)
    at Object.Drupal.attachBehaviors (js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:59)
    at js_XPobW92vm-QdWeFPYokxAO-5aOHsW7b5uAqFwCBjrZM.js:244
    at HTMLDocument.t (js_BKcMdIbOMdbTdLn9dkUq3KCJfIKKo2SvKoQ1AnB8D-g.js:4)

```

**EDIT 4**

I enabled template debug and found that `main navigation` block was not automatically placed as it is in parent so I place it but still `site_branding` block is not placed by default and there is no region to place it.

# Answer
> 0 votes
After searching for longtime, waiting for an answer and many hair pulling events I finally found the solution...

* Initially I was trying to compare `admin/structure/context` for sub-theme (enabled) homepage with parent theme (enabled) homepage and those `conditions` and `reactions` matched perfectly.
* Then as Ismail Cherri mentioned in his answer I did all the checks but no avail.
* Enabled twig template debug as @cchen mentioned in a comment. (It helped me lot to know how blocks and templates working).
* Checked if all the blocks are enabled from `admin/structure/Block Layout`

**Solution:** Finally I got to know that parent theme had those missing blocks by default present that is why comparing homepage context with parent theme homepage made me confused. So adding them in a proper region solved the issue.

I still didn't get why those block were present on parent theme even when they were not placed in `context`. I will update my answer when I will get the explanation to that and will also check if this is the behaviour with this theme only or every themes reacts the same.

**Update 1**

> I still didn't get why those block were present on parent theme even when they were not placed in `context`

So there was a `context` named "Global" which had `condition` `current_theme` and in `reaction` all the blocks that theme was providing was there. But when I created sub-theme and set it as default all those default contexts duplicated with no `reaction` and `condition`. So this was the main reason why Main Navigation and Footer Menu was missing in sub-theme and not in Parent theme.

# Answer
> 2 votes
Here are some suggestions:

1. Check that you added the same theme regions in your child theme as the parent theme
2. Check the documentation of the parent theme for Drupal version compatibility. Usually purchased themes come with a demo that contains a Drupal installation. Try working with that first.
3. Try disabling JS related core modules: BigPipe, Contextual Links, QuickEdit
4. Try disabling JS aggregation from `/admin/config/development/performance`

---
Tags: 8, theming
---


# Question
Title: How can I (programmatically) display a custom block with user profile links in dropdown?
I would like to display a custom block with some links for authenticated users like drupal.org does.

I would like to display username next to user's picture, and custom menu items. For example, "My contents" where url is something like this: "/user/{uid}/my-contents".

Do you have any idea how to create that?

Ps: I tried "menu\_token" module but it didn't work for me correctly.

# Answer
> 2 votes
If you don't have any issue rendering a block of menu, you can just show up a menu there which I suppose you've got that covered. for the `UID` part there are couple of workarounds for this:

1. Using Views
2. Menu Token
3. Me (Drupal 7) only
4. Templating: Much easier approach

**The Views way**

Number 1, using views is a long story, I'll keep it short and I move on to number 2, my own approach. With views you can use contextual filters and build your own custom links using "Current logged in user" filter, you can randomly get a view from whatever and override it with the HTML structure of your need. in case you need a more in depth answer for this, let me know and I will update my answer

**Menu Token**

This module is exactly what we need, but we have to consider some bugs that it currently has, if you check the issue queue there are some major issues with it, but still, you can manage to get it working with a little bit of dirty hacking, using jQuery/JavaScript

The issue with this module is that you cannot use the token in middle of a string for instance: `/user/{uid}/my-contents` wouldn't work but simply `/{uid}` works just fine.

So in our case, we override the `href` attribute and hardcode the path we want to it as prefix and suffix, using the UID

This is not the best practice at all, but in case anyone wants a quick solution, this is what I suggest, in case you need help with the jQuery part, let me know and I will update the answer.

**ME module - Drupal 7 only**

for those who have this issue in Drupal 7, this module considers `/me` as the user ID if configured properly, so a link in question would become something like this: `/user/me/my-contents`

**Templating**

So let's say we edit our `page.html.twig` file so we can create our custom structure for our menu, then in our case, we can simply refer to the current user's UID like so:

```
<a href="{{ path('entity.user.canonical', {'user': user.id}) }}/my-contents">Test menu item</a>

```

---
Tags: 8, users, blocks
---


title: Custom entity translation interface

text:
# Question
Title: Custom entity translation interface
I created a new custom entity using drupal console, I enabled translation and all looks ok in code.

The problem is that I don't know how to translate an entity from the admin interface, I don't see any options to do this. I looked through the generated files and I don't see any translation related functionality there.

Am I missing something? Should I build my own admin interface and logic to manage translations?

# Answer
I've missed configuration at admin/config/regional/content-language :|
> 0 votes

---
Tags: 8, entities, i18n-l10n, console
---


title: Attach file to email

text:
# Question
Title: Attach file to email
I have a site with a webform, which when submitted sends an email. The form has a file upload which should then attach the file as an attachment to the email. I'm not getting any attachment.

I've created a hook for `hook_mail_alter` and tried hardcoding any attachment to be sent but every email i get has no attachment.

```
function my_module_mail_alter(&$message) {
  $file_content = file_get_contents('sites/default/files/tmp/test.pdf');
  $message["params"]["attachments"] = array(
    'filecontent' => $file_content,
    'filename' => 'test.pdf',
    'filemime' => 'application/pdf'
  );
}

```

I've debugged the `MailManager.php` just before the email is sent and the `$message` variables `param['attachement']` has the valid contents from the code above.

I've instaled modules: **SMTP** (so i can send emails from my local), **MimeMail** and enabled **MailSystem** The emails are being sent without any issue, but again never with an attachement.

I don't know what i'm doing wrong, any ideas?

Core: 8.6

# Answer
> 1 votes
Here's the answer, which is just an extension on the comment from @berramou

```
$file = file_load($fid);
  $message["params"]["attachments"][] =[
    'filepath' => $file->getFileUri(),
    'filemime' => '' // argument must be present, but can remain empty
  ];
}

```

---
Tags: 8, webforms, mimemail
---


# Question
Title: Add an extra to the price of the product
Guests can add a meal plan to their cart. They can compose their own formula. Type of sandwich, drink and dessert.

For example the list of drinks is a list of 'taxonomy' terms. However some drinks can give a supplement. For example the formula costs 1 € more if I take a coke.

I do not know how to do this possibility. I had imagined adding a field in the taxonomy of drinks where we can put the blow of the supplement. But I did not find with Rules how to add this extra to the cart.

Have an idea of how I could do it? Thank you for your help

# Answer
We've covered this concept before in our "pizza store" tutorial, though it appears the video may not be online any more: https://drupalcommerce.org/videos/tutorials/customizable-products-pizza-store

The steps would be the same, though. I'd basically add a price field to the taxonomy vocabulary and then include the upcharge in the price field for the options the customer is selecting. Rather than using this taxonomy as a product attribute, you'd put it on the line item type as a custom line item field. Then you'd create a pricing rule that evaluates the fields on the line item type to look for a value in the upcharge price field and adds that amount to the unit price of the line item.

This is about as in depth as I can go on StackExchange. To learn how to use any of those particular features outside of getting this recipe, you should find real-time support at a local meetup or else in the Drupal Slack #commerce channel.
> 0 votes

---
Tags: 7, commerce, ubercart
---


# Question
Title: Multiple Relations and Contextual Filters in a Translated View
I have a View designed to filter down translated content (of type "Asks, Actions, and Updates") using three arguments: 1) country 2) year 3) month.

I have translated the content type and content, all three vocabularies and terms, and the View.

I want the URL to be readable, so the View has a relationship to the three vocabularies. I also have four "Translation language" filters, one for the content, which is being shown, and one each for the three vocabularies.

I also have three contextual filters that use the taxonomy "Name" and filter correctly in English with the following contextual filters entered into the preview:

```
burkina-faso/2018/july

```

However, for some reason, the contextual filters do **not** work for French with these parameters:

```
burkina-faso/2018/juillet

```

Interestingly, the following does work

```
burkina-faso/2018/all

```

but when the last argument is 'juillet' (which is the French translation), it acts as through the name does not validate (no query shows in the preview section).

Why is this happening, and what can I do to have these filters work in both languages?

Here are images of the set-up of the third contextual filter:

# Answer
OK, I had to play with this myself. The problem is the validator "Taxonomy term name" in the contextual filter. It doesn't accept the translated term name and hence no query is run.

My suggested solution is to remove the validator. AFAICT you get no matches ("page not found") for non-existing terms without the validator.

PS! I consider the non-working validator (for translated terms) a bug in Views.
> 1 votes

# Answer
Not sure if there's anything else that could be configured.

Something you could consider is using something like `hook_views_pre_view()`. Internally then you can check the language of the site for that request, read the values of the month, and using a table, translate internally `juillet` to `july`.
> 1 votes

---
Tags: views, 8, i18n-l10n
---


title: adding js and css to custom templates

text:
# Question
Title: adding js and css to custom templates
i created a custom module, which renderes a custom template.

i followed this tutorial

now basically i want to add, bootstrap, jquery, and some custom stling and scripts,

I read this article,

and i am not able to attach any files to my timplate..

my file structure:

```
 - product_tree
  - templates
     - products-tree.html.twig
  - src
     - Controller
         - productTreeController.php
  - js
     - bootstrap.min.js
     - customScripts.js
     - ...

  - css
     - customStyles.css
     - bootstrap.min.css
     - ...

  - product_tree.libraries.yml
  - product_tree.info.yml
  - product_tree.module

```

this is my libraries file:

```
# producttree.libraries.yml
product-tree-libraries:
 version: 1.x
  css:
   theme:
    css/customStyles.css: {}
  js:
   js/customScripts.js: {}
  dependencies:
   - core/jquery

```

this is my hook:

```
function product_tree_theme($existing, $type, $theme, $path) {
  return array(
    'products_tree' => array(
      'variables' => array('items' => array(), 'title' => '')
    )
  );
}

```

i tried attaching it through the renfer array

```
$build =  array(
    'page' => array (
        '#theme' => 'products_tree',
        '#items' => $items,
        '#title' => 'products',
        '#attached' => array(
            'library' => array(
              'product_tree/product-tree-libraries',
            ),
        ),
    )
);

```

and in the twig template:

```
{{ attach_library('product_tree/product-tree-libraries') }}

```

but still no luck,

in the twig i call the css and scripts

```
<link href="css/style.css" rel="stylesheet">

```

i dont know if that is needed, but i tried with and with out, when i include it, i see in the browser inspector that the css file being uploaded, but then "canceled"

can any one tell me what should i do? or what am i doing wrong ?

EDIT: in the controller, I am renderiung the page like this:

```
$items = array(
    array('name' => 'product one'),
    array('name' => 'product two'),
    array('name' => 'product three'),
    array('name' => 'product four')
);
$build =  array(
    'page' => array (
        '#theme' => 'products_tree',
        '#items' => $items,
        '#title' => 'products',
    )
);

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new Response();
$response->setContent($html);

return $response;

```

i made This according to this answer

because i want it to be separated from drupal. maybe this is the problem?

when i use `BareHtmlPageRenderer` to render the page (according to this answer). i see drupal imports and the page looks more alive, but still my custom css and js are not there!

# Answer
I Found the Solution for this.. and it is by using the `BareHtmlPageRenderer` (found it here) and then attach the files in the controller php file like this

```
$build['#attached']['library'][] = 'product_tree/product-tree-libraries';

```

with out the attachments hook function.

so the controller would look like:

```
    $build =  array(
        'page' => array (
            '#theme' => 'products_tree',
            '#items' => $term_data,
            '#title' => 'products',
        )
    );

    $build['#attached']['library'][] = 'product_tree/product-tree-libraries';

    $attachments = \Drupal::service('html_response.attachments_processor');
    $renderer = \Drupal::service('renderer');

    $bareHtmlPageRenderer = new BareHtmlPageRenderer($renderer, $attachments);

    $response = $bareHtmlPageRenderer->renderBarePage($build, 'Page Title', 'markup');
    return $response;

```

it could also be in the `$build` array it self i think.. but this way its better when looking at it..

and still no need for:

```
{{ attach_library('product_tree/product-tree-libraries') }}

```

Or

```
<link href="css/style.css" rel="stylesheet">

```
> 2 votes

# Answer
1. Check the yml indentation:

```

product-tree-libraries:
  version: 1.x
    css:
      theme:
        css/customStyles.css: {}
    js:
      js/customScripts.js: {}
    dependencies:
      core/jquery

```
2. Attach your library with `hook_page_attachments` To attach to hole page.

```

    /**
     * Implements hook_page_attachments().
     */
    function product_tree_page_attachments(array &$attachments) {
      //- Note YourModuleName/Library name
      $attachments['#attached']['library'][] = 'product_tree/product-tree-libraries';
    }

```
3. No need for:

```

    {{ attach_library('product_tree/product-tree-libraries') }}

```

Or

```
<link href="css/style.css" rel="stylesheet">

```
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: How Print individual fields in a view row by row
I have so much fields in a content like "title", "field\_image", "field\_description", and i use a view for create a block and put it on my front page...

I will make a slider with a jquery plugin (jssor slider), i need use the structure of jssor slider. then in my view, i use "views-view-fields--\[name\_machine\]--block.html.twig" for print individual fields. but the file "views-view-fields..." print for each content, run all code on this file,and i need to put the initial containers of this plugin only once, and the code of the images several times.

I try to put the initial containers of the plugin in the "page.html.twig" but when i print the block with the "views-view-fields..." inside he puts a lot of code and many labels and containers that I do not need and the plugin stops working. let me show the files.

my page.html.twig {# Header #} {% if page.banner\_front %}

```
    <div id="jssor_1">
      <!-- Loading Screen -->
      <div data-u="loading" class="jssorl-009-spin">
          <img src="/images/spin.svg" />
      </div>
      <div data-u="slides">

        {% block banner_front %}
            {{ page.banner_front }}
        {% endblock %}

      </div>
     </div>

```

then my views-view-fields--banner--block.html.twig:

```
           <div data-b="0">
                <img data-u="image" src="{{ fields.field_imagen.content }}"/>
                <div class="caption-banner" data-u="caption" data-t="0">
                    <div class="title-banner">
                        {% if fields.title.content %}
                            {{ fields.title.content }}
                        {% endif %}
                    </div>
                    <div class="description-banner">
                        {% if fields.banner_description.content %}
                            {{ fields.banner_description.content }}
                        {% endif %}
                    </div>
                    {% if fields.field_url.content %}
                        <a href="#" target="_blan">
                            <div class="btn-ver">Ver más</div>
                        </a>
                    {% endif %}
                </div>
            </div>

```

to work correctly, the label `<div data-b = '0'>` must be left of the label `<div data-u = 'slides'>`, but when the region is printed the system prints many labels and containers that damage the structure of the slider.

On Drupal 7 i used inside of the foreach the code of the images, and outside the inicial structure, and works well but now, i dont know how to this.

Thanks a lot.

# Answer
If you work with **Format:Unformatted list** try to override the `views-view-unformatted.html.twig`, you will have the ability to add class to parent or inside each row.
> 0 votes

---
Tags: views, 8, theming
---


# Question
Title: Serving Drupal from within a sub-directory of my web root
I need my Drupal 8 website to be served from within a subdirectory of my `NGINX_SERVER_ROOT` but is doesn't work.

Drupal should be reached at **mydomain.com/drupal**.

My `NGINX_SERVER_ROOT` is `/var/www/html/web`.

When the source code is in `/var/www/html/web` it works fine. But when moved to `/var/www/html/web/drupal` and I try to reach mydomain.com/drupal, it doesn't work.

I have edited the `.htaccess` file within the drupal subfolder and set `RewriteBase /drupal` as explained in the file itself.

Here is the log when I try to access my Drupal installation.

```
nginx_1    | 2018/10/09 12:58:38 [error] 42#42: *5 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 192.168.160.4, server: default, request: "GET /drupal HTTP/1.1", upstream: "fastcgi://192.168.160.5:9000", host: "d8site.local:8000"
nginx_1    | 192.168.160.4 - - [09/Oct/2018:12:58:38 +0000] "GET /drupal HTTP/1.1" 404 47 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
nginx_1    | 192.168.160.4 - - [09/Oct/2018:12:58:38 +0000] "GET /favicon.ico HTTP/1.1" 200 43 "http://d8site.local:8000/drupal" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"

```

Could someone point me in the right direction?

# Answer
> 2 votes
You have to edit the nginx virtual host file of your website. You'll usually find it at `/etc/nginx/sites-available/yoursitename.vhost`.

Open it with write permissions, and **edit root directive** at the top of server block as following:

```
server {
    listen x.x.x.x:yyyy; #IP:port
    server_name www.example.com;
    root /var/www/html/web/drupal;

```

Save the file and reload nginx conf : `sudo systemctl reload nginx.service`

---
Tags: .htaccess, 8
---


title: Disable block caching

text:
# Question
Title: Disable block caching
I just made a simlple block by using block \> custom block, so I didn't make it programmatically.

I am a Drupal 8 newbie, and I look for a simple and clear solution how to disable caching for that block.

What code should I use ? In what file to put the code ? How to target that unique block ?

Thanks !

# Answer
> 2 votes
if you have a custom module let's suppose it called `custom_module`, your `custom_module.module` implement `hook_preprocess_HOOK`.

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function custom_module_preprocess_block(&$vars) {
  //- Change the block-id-name by your block id
  if($vars['derivative_plugin_id'] == 'block-id-name') {
    //- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;

  }

```

**Edit** :
if you don't know the exact `block id` you can install Block Content Machine Name module, it will give you the possibility to give a machine name to your custom block, and then implement the hook like the following:

```
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function custom_module_preprocess_block(&$vars) {
  //- Change the block-machine-name by your block machine name
  if (isset($vars['elements']['content']['#block_content']) &&
    $vars['elements']['content']['#block_content']->get('machine_name')->value == 'block-machine-name'
  ) {
    $vars['#cache']['max-age'] = 0;
  }
}

```

---
Tags: 8, blocks, caching
---


# Question
Title: How to set and use direct files folder path in a multisite installation
Drupal 8 multisite install where

1. First site is on a subdomain one.example.com
2. Second site is in a subfolder one.example.com/two

**How can files folder for both sites to be accessible via URL/files and not URL/sites/domain/files**

* current: one.example.com/sites/one.example.com/files
* desired: one.example.com/files
* current: one.example.com/two/sites/two/files
* desired: one.example.com/two/files

I tried several variants listed here https://www.drupal.org/node/53705 and put them at following locations, but nothing worked.

1. Drupal8/.htaccess
2. Drupal8/files/.htaccess
3. Drupal8/sites/two/files/.htaccess

Setup information is provided below

---

Filesystem setup

```
--Drupal8
  --index.php
  --one.example.com (sym link ln -s . one.example.com)
  --two (sym link ln -s . two) Not required in D8, but could not get the subfolder site to work without it.
  --sites
    --default (sym links to one.example.com)
    --one.example.com
      --settings.php, services.yml
      --files, modules,etc
    --two
      --settings.php, services.yml
      --files, modules,etc

```

Sites.php

```
$sites = [];
$sites['one.example.com'] = 'one.example.com';
$sites['one.example.com.two'] = 'two';

```

Apache setup : One virtual host for one.example.com

# Answer
> 0 votes
In /.htaccess, above other rewrite rules, use something like this example for foo.bar.com:

```
RewriteCond %{HTTP_HOST} ^foo\.bar\.com
RewriteRule ^files/(.*)$ sites/foo.bar.com/files/$1 [NC,L]

```

# Answer
> 0 votes
Since in this case one site is on subdomain the other on subfolder, single rule as mentioned by @cilefen is not sufficient. So we need to make two rules in this case, one for the subfolder site and other for the subdomain site. The subfolder site rule is hardcoded as we can't generalize it.

The rewrite rules need to be added to Drupal core's .htaccess (i.e one next to index.php). This will also require changes to .htaccess on every Drupal upgrade as the stock file won't have these rules.

```
  # Subfolder site
  # match subfolder site url path and amend its file path
  RewriteCond %{REQUEST_URI} /two/files/
  RewriteRule ^files/(.*)$ sites/two/files/$1 [L]

  # Subdomain site
  # if the url path matches subfolder site skip this rule
  RewriteCond %{REQUEST_URI} !/two/files/
  RewriteRule ^files/(.*)$ sites/%{HTTP_HOST}/files/$1 [L]

```

These rules need to be above the following, else they won't work

```
  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

```

Thanks to @cilefen for putting me on the correct path.

# Answer
> 0 votes
No need for any server config. You can do this by setting `$settings['file_public_path'] = 'files';` in both your sites `settings.php` files.

See `default.settings.php` (click "View source")

> ```
> /**
>  * Public file path:
>  *
>  * A local file system path where public files will be stored. This directory
>  * must exist and be writable by Drupal. This directory must be relative to
>  * the Drupal installation directory and be accessible over the web.
>  */
>
> # $settings['file_public_path'] = 'sites/default/files';
>
> ```

---
Tags: 8, files, multi-sites, .htaccess
---


# Question
Title: How to set a multi-value image field's default value from author's profile field on a node create form?
On /admin/config/people/accounts/fields page, there is an optional multi-value image field *field\_proof\_images*. There is a content type *Proof*, I reuse the *field\_proof\_images* in *Proof*. Then on /node/add/proof page, I want the *field\_proof\_images* to be automatically filled with the images from *field\_proof\_images* in the user accounts.

How to make this in Drupal 7?

# Answer
> 0 votes
You can prepopulate from other content through Tokens and Entityreference field. Here's a tutorial: Automatically Populate Drupal Fields From Other Content.

I don't know if it works with images but I don't see why it wouldn't. Not sure about the multi-value fields, you can try and see.

---

For a custom module solution you can lean on Prepopulate.

---

In Drupal 8 you can create a custom Media Entity browser that would show only the current user images from that field, then you might be able to choose them, or maybe even set as default.

---

Saving the images into the Content types ensures that if the user changes their user images it won't affect the Proof content. But if you want to always have them the same then you shouldn't add that to the Proof content at all. Simply create a contextual Views Block that would always display the content author's proof images and display it on the Proof nodes.

---
Tags: forms
---


# Question
Title: Image field causes #access to reset to default
I am using ajax to show/hide a field based on a date field. I set the default access to TRUE. If the user selects a date of birth over 18 years old, `$is_younger` and consequently the access switch to FALSE.

```
function mrpeanut_form_record_node_form_alter(&$form, &$form_state, $form_id) {
    // some other stuff here
    $is_younger = TRUE;
    $values = !empty($form_state['values']) ? $form_state['values'] : array();
    $dob_date_combo_element = &$form['field_dob']['und'][0];
    $dob_date_combo_element['#ajax'] = [
      'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
      'wrapper' => 'minor-ajax',
      'effect' => 'fade',
    ];

    if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
    }

    $form['field_minor_agreement']['und']['#access'] = $is_younger;

```

This is working great until the user selects and uploads an image on a separate image field. Then, `$is_younger` switches back to TRUE, regardless of whether they are over 18 or not. I can't seem to figure out why.

I think the error is happening on this line:

```
if (!empty($values['field_dob']['und'][0]['value']))

```

After I upload an image, I get this error if I try to watchdog the value.

> *Notice*: Undefined index: field\_dob in *mrpeanut\_form\_record\_node\_form\_alter()*

I think `$values` is getting overwritten after the image is uploaded and therefore date of birth can't be calculated again and it reverts back to `$is_younger = TRUE`.

Here's my callback:

```
function mrpeanut_form_record_node_form_minor_agreement_callback($form, $form_state) {
  $commands = array();
  $commands[] = ajax_command_replace('#edit-field-minor-agreement-wrapper', drupal_render($form['field_minor_agreement']));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 0 votes
I would try refactoring your code, so that the part that produces the value of `$is_younger` first checks whether the triggering element is the `field_dob` field.

As an example:

```
// some other stuff here
$dob_date_combo_element = &$form['field_dob']['und'][0];
$dob_date_combo_element['#ajax'] = [
  'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
  'wrapper' => 'minor-ajax',
  'effect' => 'fade',
];

// Were we called by the #ajax-ified element?
if (isset($form_state['triggering_element']) &&
  $form_state['triggering_element']['#name'] === 'field_dob[und][0][value]') {
  $values = !empty($form_state['values']) ? $form_state['values'] : array();
  $is_younger = TRUE;

  if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
  }
  $form['field_minor_agreement']['und']['#access'] = $is_younger;
}
// Initial form loading.
else if (empty($form_state['input']) {
  // Place initial loading logic here for field_minor_agreement.
}

```

---
Tags: 7, hooks
---


title: Pay-Per-Node Functionality

text:
# Question
Title: Pay-Per-Node Functionality
My client would like a content type that has to be purchased by a registered user on a node-per-node basis.

A previously registered user will see a view with the available content they can purchase and then that user can purchase individual nodes. These nodes that have been purchased will also appear in a My Library view as well.

I have found multiple tutorials on how to do this via D7; however, I can't seem to find anything that shows how to do this on D8.

Can Drupal 8's Commerce Module do this out of the box or will I need to install additional modules to reach this functionality.

I am trying to find the right configurations of Products, Orders, and Stores but so far to no avail.

# Answer
We're doing something similar.

1. The User gets a role, that determines what he may buy
2. A custom field on the productVariation lists which roles it is available for
3. In a preprocess function we compare the user's roles to the accepted roles on the variation and set a flag
4. twig evaluates that flag

Since we only have 5 products, where we have to differentiate, this works. I imagine if you had hundreds, it might be cumbersome.
> 0 votes

# Answer
I think the proper way to handle this in Drupal 8 would be with Commerce License.
> 0 votes

---
Tags: 8, nodes, commerce
---


# Question
Title: How to use Twig expression in content fields and render?
How to use twig expression in Drupal 8 content field and render. If I embed following twig expression in field value

```
{% if variable == 1 %}
   you are logged in
{% endif %}

```

When I render the field template I want to print "you are logged in".

Right now it renders as:

```
{% if variable == 1 %}
  you are logged in
{% endif %}

```

Though views allow Twig expression. Can we achieve same in content fields?

# Answer
You cannot use Twig code as field value. You have to put that code in a template file. Or you can use Twig code in Views field value rewriting (but not as field value). 2nd is limited to variables of the view that are before to rewritten field. The function can be found in Views UI by clicking on the field name in the "Fields" section.
> 0 votes

# Answer
I think you can do that if you try to install this module https://www.drupal.org/project/twig\_field
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to implement search autocomplete for specific content types?
How to implement search autocomplete it should show suggestions for specific content type only suppose recipe and collection .

I have used **search exclude(node)** module for searching nodes of specific content types.

But i am not able to figure out how to add search autocomplete programatically or by using some module.

# Answer
> 4 votes
Create a new view of content. Click on `+ Add`  select `Autocompletion Callback` and add a path/url to it.

In Filter add Type filter so only shows certain content types.

In `/admin/config/search/search_autocomplete` edit the search block

For **WHAT - WHAT TO DISPLAY IN SEARCH AUTOCOMPLETE SUGGESTIONS?** change this to your view's autocompletion callback.

For more info read the documentation.

---
Tags: 8
---


title: File Types Question

text:
# Question
Title: File Types Question
Is it possible to store .obj and .dwg files and/or Unity asset bundles in a Drupal CMS?

If so, is it then possible to use API requests to upload and download these files?

Cheers

# Answer
Yes. The only thing you need is to properly configure the media type with file extensions

Check: https://www.drupal.org/docs/8/core/modules/media/creating-and-configuring-media-types
> 0 votes

---
Tags: files
---


# Question
Title: How to change the text in the revision log message?
I would like to change the bottom text, "Provide an explanation of the changes you are making. This will help other authors understand your motivations.", in the revision log message section. See attached screenshot.

How should I go about changing the text?

# Answer
> 6 votes
Use the following code in a custom module or in your theme's template.php:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOURMODULE_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['log']['#description'] = t('Your new instructions.');
}

```

*Note:* replace `YOURMODULE` with your module/theme name and `CONTENTTYPE` with machine name of the content type you want to change.

# Answer
> 2 votes
Another alternative is to use the String Overrides module:

http://drupal.org/project/stringoverrides

One of the major advantage is that you don't have to code anything and you will access to change the wording at any time thru the admin interface.

# Answer
> 0 votes
Instead of node\_form\_alter we can alter the revision text by using form\_alter also.

Ex:

```
function your_custom_module_form_alter(&$form, $form_state, $form_id) {
    if($form_id == "custom_node_form") {
       $form['revision_information']['log']['#description'] = t('Your new instructions.');
    }
}

```

---
Tags: 7
---


# Question
Title: Cannot upload files to private file system using s3fs
We have migrated our Drupal 7 site to AWS with S3 bucket. Integrated s3 bucket with the site using s3fs module. We have made all the necessary configurations. We are having issue uploading files to private file system

We tried with each of the following as Default download method. \- Amazon Simple Storage Service \- Public files served from Amazon S3.
\- Private files served from Amazon S3

We are receiving error the following error

```
Guzzle\Common\Exception\RuntimeException: Error creating resource. [message] fopen(https://xxxx.xxx.s3bucketpath/s3fs-private/XXXX.docx): failed to open stream: "DrupalRemoteStreamWrapper::stream_open" call failed [file] /var/app/current/sites/all/libraries/awssdk2/Guzzle/Stream/PhpStreamRequestFactory.php [line] 217 in Guzzle\Stream\PhpStreamRequestFactory->createResource() (line 279 of /var/app/current/sites/all/libraries/awssdk2/Guzzle/Stream/PhpStreamRequestFactory.php)

```

Just to add a note on this we are using file field path module for the field. This patch (https://www.drupal.org/node/2527768) seems to be for older version of File field path module

# Answer
Check on PHP's setting for `allow_url_fopen` ... it's generally turned off by security-aware system administrators, which will block `fopen`'s ability to access to resources over http(s).
> 0 votes

# Answer
I had an exact problem and turned out it was a firewall issue. Everytime I `requested /admin/config` and `/admin/reports/status` I always got the same error.

This error happened around the time when our company implemented our own firewall. So after pulling out all the hair, I found out that our company's firewall had its own certificate (.pem) file for in out requests. Guzzle has its own pem certificate in its resource so in the `guzzlehttp/src/Guzzle/Http/Resources/cacert.pem`, I appended our own certificate. and the error was gone.
> 0 votes

---
Tags: 7
---


# Question
Title: How to render taxonomy field_custom in page--taxonomy--term.twig?
I have a custom field in my taxonomy. How to render programmatically this taxonomy field in page--taxonomy--term.twig?

# Answer
You need to prepare the Twig variable in a preprocess hook:

```
function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['field_example'] = $term->field_example->view();
  }
}

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Add a sticky class to node displayed via View
How to add class for sticky nodes in Drupal 8, so I can theme views (sticky having different background etc).

I have seen a post that it can be done through Twig, but I cannot understand in which template should I put the lines and frankly...which lines?

# Answer
You already get the sticky class on views-row in most themes if your Format Show is set to `Content`.

But if it's set to `Fields` you can do it through the interface with the help of **Content: Sticky at top of lists** field.

1. Add the `Sticky at top of lists` field from `Content` Category to your View
2. Under `Output format` setting for this field choose **Custom** and then enter your desired class name into the offered field:
**Custom output for TRUE**
`node--sticky`
**Custom output for FALSE**
\[\____leave empty\____\]
3. Under `Rewrite results` uncollapse the **Replacement patterns** and copy the code for this field. It will be something like `{{ sticky }}`.

Don't enable Rewriting, this step is just to copy the pattern.
4. Save the Field settings and check the views results - do you see the class name listed for nodes that you know are stickied? If yes then edit the field again and **Exclude from display**
5. Under **Format: Settings** paste the pattern into the **Row class** input field

You will now have the text you entered for the TRUE sticky state appear as one of the classes next to `views-row` class.
> 1 votes

---
Tags: views, 8, theming
---


# Question
Title: Change markup shown before the search result
How do I change this markup from my .theme file?

Line 119 and following in core/modules/search/src/Controller/SearchController.php contain this code.

```
if (count($results)) {
  $build['search_results_title'] = array(
    '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
  );
}

```

I want to remove the `<h2>` tags from my search page.

I am able to change the search form above, and the result list after that tag using `hook_preprocess_form()`on the search form and `hook_preprocess_search_result()` on the search results.

Is there a preprocess function I am missing, or can I use a custom template?

# Answer
> 2 votes
This answer has already been answered on Core search module, change markup. This is what the accepted answer for that question says.

> You have to alter the route defined by the search module. In order to do so:
>
> 1. Define in your `mymodule.services.yml` file following:
>
> ```
> services:
>   mymodule.route_subscriber:
>     class: Drupal\mymodule\Routing\RouteSubscriber
>     tags:
>       - { name: event_subscriber }
>
> ```
> 2. Create a class that extends the `RouteSubscriberBase` class on /mymodule/src/Routing/RouteSubscriber.php as following:
>
> <pre><code>/**
>  * @file
>  * Contains \Drupal\mymodule\Routing\RouteSubscriber.
>  */
>
> namespace Drupal\mymodule\Routing;
>
> use Drupal\Core\Routing\RouteSubscriberBase;
> use Symfony\Component\Routing\RouteCollection;
>
> /**
>  * Listens to the dynamic route events.
>  */
> class RouteSubscriber extends RouteSubscriberBase {
>
>   /**
>    * {@inheritdoc}
>    */
>   public function alterRoutes(RouteCollection $collection) {
>     // Replace dynamically created "search.view_node_search" route's Controller
>     // with our own.
>     if ($route = $collection->get('search.view_node_search')) {
>       $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleSearchController::view');
>     }
>   }
>
> }
>
> 3. Finally, the controller itself located on /mymodule/src/Controller/MyModuleSearchController.php
>
> ```php
> namespace Drupal\mymodule\Controller;
>
> use Drupal\search\SearchPageInterface;
> use Symfony\Component\HttpFoundation\Request;
> use Drupal\search\Controller\SearchController;
>
> /**
>  * Override the Route controller for search.
>  */
> class MyModuleSearchController extends SearchController {
>
>   /**
>    * {@inheritdoc}
>    */
>   public function view(Request $request, SearchPageInterface $entity) {
>     $build = parent::view($request, $entity);
>     // Unset the Result title.
>     if (isset($build['search_results_title'])) {
>       unset($build['search_results_title']);
>     }
>
>     return $build;
>   }
>
> }
> </code></pre>

# Answer
> -2 votes
I had a similar problem wherein i had to hide the Search Results H2 tag entirely.

I could manage to do it with Jquery with the below code :

```
$('h2:contains("Search results")').css("display", "none");

```

---
Tags: theming, 8, search
---


# Question
Title: How can I get a user by email address using a service?
I have a custom service that I created to do some stuff with users. I want to be able to GET and DELETE users by email address because I may not know the uid.

I have the service set up now. It works through Postman, but through the actual client, it returns a 406 error because of the .com in the email.

How do I pass the email to the service if not through the URL?

This is the definition of the service.

```
'retrieve' => array(
    'help' => 'Retrieve a user',
    'file' => array(
        'type' => 'inc',
        'module' => 'user_service',
        'name' => 'user_service',
    ),
    'callback' => '_my_user_resource_retrieve',
    'access callback' => '_my_user_resource_access',
    'access arguments' => array('view'),
    'access arguments append' => true,
    'args' => array(
        array(
            'name' => 'email',
            'type' => 'int',
            'description' => 'The email of the user to retrieve.',
            'source' => array('param' => 'email'),
            'optional' => false,
        ),
    ),
),

```

The callback function is the following.

```
function _my_user_resource_retrieve($mail) {
  return user_load_by_mail($mail);
}

```

# Answer
Apparently Params are only for index functions. So you need to implement an index function, something like this from the `user_resources.inc` file in the Services module:

```
'index' => array(
    'help' => 'List all users',
    'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/user_resource'),
      'callback' => '_user_resource_index',
      'args' => array(
        array(
          'name' => 'page',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'The zero-based index of the page to get, defaults to 0.',
          'default value' => 0,
          'source' => array('param' => 'page'),
        ),
        array(
          'name' => 'fields',
          'optional' => TRUE,
          'type' => 'string',
          'description' => 'The fields to get.',
          'default value' => '*',
          'source' => array('param' => 'fields'),
        ),
        array(
          'name' => 'parameters',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Parameters',
          'default value' => array(),
          'source' => array('param' => 'parameters'),
        ),
        array(
          'name' => 'pagesize',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'Number of records to get per page.',
          'default value' => variable_get('services_user_index_page_size', 20),
          'source' => array('param' => 'pagesize'),
        ),
        array(
          'name' => 'options',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Additional query options.',
          'default value' => array(
            'orderby' => array(
              'created' => 'DESC'
            )
          ),
          'source' => array('param' => 'options'),
        ),
      ),
      'access arguments' => array('access user profiles'),
      'access arguments append' => FALSE,
    ),
  ),

```
> 0 votes

---
Tags: 7, services
---


# Question
Title: Get username in custom user twig template
I have a twig template for the compact display of a user where I am able to output the defined content fields. Is there a way to output the username of that user?

# Answer
> 12 votes
`{{ user.name.0.value }}`

should give you what you want.

The preferred way is inject the username as a variable in a preprocess function. To do so, tweak that in your theme's .theme file

```
<?php

/**
 * Implements hook_preprocess_user().
 */
function yourtheme_preprocess_user(&$variables) {
  /** @var User $account */
  $account = $variables['elements']['#user'];

  $variables['username'] = $account->getDisplayName();
}

```

then in your user template you can use that as `{{ username }}`.

Edit:

To get the full URL:

* In your template `{{ path('entity.user.canonical', {'user': user.id}, {}) }}`
* In yourtheme\_preprocess\_user(): `$variables['user_url'] = Url::fromRoute('entity.user.canonical', ['user' => $account->id()])->setAbsolute()->toString();`

# Answer
> 20 votes
The display name is not a field you can configure in `{{ content }}`. You can get it directly from the user entity:

```
{{ user.displayname }}

```

Reference for the php method: AccountInterface::getDisplayName

# Answer
> 2 votes
This answer is specifically for getting the username in menu.html.twig

The solution of passing the username through macro worked for me. Setting a variable and passing it into the macro is needed as these are out of scope of the macro in menu.html.twig

```
{% set username = user.account.name %}
{{ menus.menu_links(items, attributes, 0,logged_in,username) }}
{% macro menu_links(items, attributes, menu_level,logged_in,username) %}
{{ username }}
{% endmacro %}

```

---
Tags: 8
---