# Question
Title: Commerce one-off products in admin interface
Is there a way I can create the capability for an admin to add a one-off product when creating an order through the admin interface? (For example, it could have a SKU of "CUSTOM" but we'd need the ability to enter a custom description that would show up in the line item in the receipt).

These are for customizations that are not available to the general public/only available if an admin enters them and would only be useful one time, so creating a full-fledged product for each one is not feasible.

I have done some testing with Commerce Customizable Products but it seems to allow customizable fields on the front end, but not in the admin "Add Order" screen where I need it.

# Answer
> 1 votes
The line item title in 1.x is derived from the line item type's title callback. Your simplest option is going to be to define a new line item type, as you've surmised, and have its title callback pull the value from a field you add to the line item type and expose to administrators to edit. Alternately you could edit the various Views to render this field directly ... but then you'd still need some way to allow creating ad hoc line items on the back end.

Sorry, I wish it were easier.

---
Tags: 7, commerce
---


# Question
Title: How to split up the renderd page in a tpl file?
In my D7 template I have a tpl file called:

html--events.tpl.php

```
  <html class="no-js" lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<?php endif; ?>
<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body<?php print $attributes;?>>
  <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

</body>
</html>

```

I would like to add a page header image to this page by changing the template.

So therefore I would like to split the rendered content of this page for e.g. like this:

```
  <?php print $page_top; ?>
  <?php print $pageheader; ?>
  <?php print "<div><img src='sites/default/files/animage.png'>/div>" ?>
  <?php print $pagetitle; ?>
  <?php print $pagemaincontnet; ?>
  <?php print $page_bottom; ?>

```

However the var $page contains already all the rendered header. How can I split the rendered page into smaller blocks? I tried to replace:

```
<?php print $page; ?>

```

into

```
 <?php print render($page['content']); ?>

```

but then got a message : Only variables can be passed by reference

Any suggestion is very welcome.

# Answer
`$page` is the rendered content from page.tpl.php - you can't alter it in the HTML template without resorting to nasty string manipulation.

Fortunately your desired output lends itself nicely to being handled in the page template anyway. You won't automatically have the same template name suggestions available, although a theme/module might already make them available in your installation. If not, you can add it yourself:

```
function MYTHEME_preprocess_page(&$vars) {
  // This condition may need to change depending on your exact needs
  if (arg(0) == 'events' && !arg(1)) {
    $vars['theme_hook_suggestions'][] = 'page__events';
  }
}

```

Then in page--events.tpl.php you'll have access to the individual elements of the `$page` array, and you can render them as needed.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: What Multiple contributors means in Drupal Translations site?
I just notice that when you go to the different Drupal Translations sites (for example the French site) there is a user named ***Multiple contributors*** but I can't figure out what this means, is a user or a contribution that is made from a different site?

# Answer
See the Working with translation files offline documentation under the **Contributing back to the community** header:

> When you have finished, contribute the translation back to localize.drupal.org by importing the file on the translation team user interface. Translations will either be attributed to you or "Multiple contributors" depending on which option you choose. ***"Multiple contributors" is a special account you can use if multiple people worked on the translations being imported and singling out one contributor for attribution would not be correct.***
> 4 votes

---
Tags: community-official-site
---


# Question
Title: Set All Day checkbox on date field programmatically
I am importing events from an iCal feed and have managed to get everything working great except for events that take place all day. Currently they are coming in and defaulting to a xx/xx/xxxx 7:00pm to xx/xx +1/xxxx 7:00pm date when they should fall on the same day without a time. I've tried hardcoding 00:00:00 as the time but that get's ignored. I've also made sure that there are no default time settings on the field.

There is a checkbox for All Day but nothing seems to mark it as checked while I'm trying to create the node and it doesn't appear to be saved in the node object anywhere so not sure how I am suppose to set the checkbox while I'm creating the node.

Current code I am using while looping through each of the events in the feed:

```
// Use the UID to look up existing events.
if(!in_array($uid, $uids)){

    if(strtotime($startDt->format ( 'm/d/Y h:ia' )) > strtotime("-1 month")){
        try {
            $node = new stdClass();
            $node->type = "calendar_event";
            $node->uid = 1;
            $node->language = 'en';
            $node->title = $eventName;
            $node->body['und'][0]['value'] = stripslashes($eventLocation);
            $node->body['und'][0]['format'] = 'full_html';
            $node->field_uid['und'][0]['value'] = $uid;
            $node->field_date['und'][0]['value'] = $startCom;
            $node->field_date['und'][0]['value2'] = $endCom;

            // this doesn't work
            $node->field_date['und'][0]['all_day'] = 1;

            $node->status = 1;
            node_save($node);

            $values = array(
                'entity_type' => 'node',
                'entity' => $node->nid,
                'state' => OG_STATE_ACTIVE,
                'membership_type' => OG_MEMBERSHIP_TYPE_DEFAULT,
                'field_name' => 'og_group_ref'
            );
            og_group('node', $groupID, $values);
            $newCount++;
        } catch (Exception $e) {
            watchdog_exception('school_calendar', $e);
        }
    }
} else { // uid existed, maybe we want to update if needed.
}

```

# Answer
> 0 votes
I found a "hacky" way of doing this. A couple things I noticed after investigating further is that the All Day single day events in Drupal are set to the same time on both the start and end dates. So first I changed the time of each date format to 05:00:00, just a random time but the same time for both.

This seemed to trigger the All Day checkbox which is great. But single day events were still showing as if they spanned over 2 days, not 1.

Upon further review of how iCal specifies formatting an all day single event, it wants the DTEND to actually be offset by 1 day, so I it comes in like this for a single all day event:

DTSTART 01/01/2018 DTEND 01/02/2018

So I added this to my DTEND handling:

```
if(isset($icsEvent['DTEND;VALUE=DATE'])){
    $end = $icsEvent['DTEND;VALUE=DATE'];
    $endDt = new DateTime ( $end );
    $difference = $startDt->diff($endDt);
    if($difference->days == 1){
        $endDt->modify('-1 day');
    }
    $endCom = $endDt->format ( 'Y-m-d 05:00:00');
}

```

This modifies the end date to offset -1 day, so it ends up being the same day as the start. This is seems work great now for single all day events.

It appears though that I need to also apply this to spans of all day events, like a winter recess break that last all week. Even though it's supposed to be Monday - Friday, because of the offset in iCal, it's stretches to Saturday.

So probably instead of the difference check, I should just offset the endDt all the time by -1 day.

---- Update to Answer ---

The above worked great but I was finding some events that were supposed to be all day, showing as starting at 1am. Not sure why, the timezone looked right but some events started showing as this.

But if I set the date field to "no timezone conversion" first, then do the following with my start and end dates.

```
// Start Date
if(isset($icsEvent['DTSTART;VALUE=DATE'])){
    $start = $icsEvent['DTSTART;VALUE=DATE'];
    $startDt = new DateTime ($start);
    $startCom = $startDt->format ( 'Y-m-d 00:00:00' );
} else {
    $start = $icsEvent['DTSTART'];
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone("America/New_York");
    $startDt = new DateTime ($start, $UTC );
    $startDt->setTimezone( $newTZ );
    $startCom = $startDt->format ( 'Y-m-d H:i:s' );
}

// End Date
if(isset($icsEvent['DTEND;VALUE=DATE'])){
    $end = $icsEvent['DTEND;VALUE=DATE'];
    $endDt = new DateTime ($end);
    $endDt->modify('-1 day');
    $endCom = $endDt->format ( 'Y-m-d 00:00:00');
} elseif(isset($icsEvent['DTEND'])) {
    $end = $icsEvent ['DTEND'];
    $UTC = new DateTimeZone("UTC");
    $newTZ = new DateTimeZone("America/New_York");
    $endDt = new DateTime ( $end, $UTC );
    $endDt->setTimezone( $newTZ );
    $endCom = $endDt->format ( 'Y-m-d H:i:s' );
}

```

Basically if there is no time set, and it's just an event that spans as All Day, set no timezone and default to midnight. If it has a time, set the new york time zone.

---
Tags: 7, nodes, datetime
---


# Question
Title: Add help text to radio button when it's disabled
I have two radio button groups that have a dependency.

When Button 1 is clicked, Buttons 4 and 5 should be disabled and vice versa. If Button 2 is clicked Button 4 and 5 are active and Button 3 is disabled.

How can I add help text to the disabled buttons that states the buttons are disabled because of your selection in Group A (Organization).

Here is the javascript that handles the buttons.

```
$(document).on('click', function () {
    // Organization and Data Classification dependency
    if($('#edit-field-organization-und-0').is(':checked')){

        $('#edit-field-data-classification-und-public').attr('disabled',false);
        $('#edit-field-data-classification-und-internal').attr('disabled',false);
        $('#edit-field-data-classification-und-confidential').attr('disabled',false);

        $('#edit-field-data-classification-und-btn1').attr('disabled',true);
        $('#edit-field-data-classification-und-btn1').removeAttr('checked');
        $('#edit-field-data-classification-und-btn2').attr('disabled',true);
        $('#edit-field-data-classification-und-btn2').removeAttr('checked');

    }
    else{
        $('#edit-field-data-classification-und-public').attr('disabled',true);
        $('#edit-field-data-classification-und-public').removeAttr('checked');
        $('#edit-field-data-classification-und-internal').attr('disabled',true);
        $('#edit-field-data-classification-und-internal').removeAttr('checked');
        $('#edit-field-data-classification-und-confidential').attr('disabled',true);
        $('#edit-field-data-classification-und-confidential').removeAttr('checked');

        $('#edit-field-data-classification-und-btn1').attr('disabled',false);
        $('#edit-field-data-classification-und-btn2').attr('disabled',false);

    }

```

}

```
enter code here

```

# Answer
I would suggest you might want to think about using the Conditional Fields module and having two separate fields for the change in Group B.

But for this specific question-- not knowing your HTML structure exactly -- you'd likely just be adjusting the HTML of the label. And that would then be more of a JS design question than a drupal one (unless you are building a modue around the idea) ... how to do that best depends on how re-usable you'd want it. In straight up JS: I'd likely store a hashed array of the label text, then have arrays of the option b input radio button ids -- one for option a1, the other for option a2. And then have a function that works on the appropriate array, passing in whether it should be enabled for not: foreach optionba1; change state, unselect anything checked, change text (return to original or add new text).
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: How can I add a taxonomy-based view to a page?
I created a taxonomy with a vocabulary called Series. The Series vocabulary contains a list of terms x, y, z.

I created a content type called Events, which has a field to tag the content with a term from the Series vocabulary.

I created a view to display the events on a page in ascending order beginning from today's date.

The view is set to display certain fields for each piece of Event content. One of the fields displayed is the Series term, which is set to be a link that goes to a page that contains a list of all events tagged with that term.

How can I make that resulting page into a view block that I can drop into a content panel?

# Answer
> 1 votes
Go edit the view that you created and hit add+ next to the view name and then block. By adding a block a new block will appear in the Structure-\> Blocks Section and then you can place it anywhere you like.

---
Tags: 7, views, taxonomy-terms
---


title: HTTP request status error

text:
# Question
Title: HTTP request status error
This is the error shown in reports/status.

> Your system or network configuration does not allow Drupal to access web pages, resulting in reduced functionality. This could be due to your webserver configuration or PHP settings, and should be resolved in order to download information about available updates, fetch aggregator feeds, sign in via OpenID, or use other network-dependent services. If you are certain that Drupal can access web pages but you are still seeing this message, you may add `$conf['drupal_http_request_fails'] = FALSE;` to the bottom of your settings.php file.

What do I need to configure to prevent this error?

My website works well, but this error causes some problems, for example with the Quicktab module.

As you can see *Tab Content* disappeared and *Tab Weight* is changed to the select list. What do I need to do to fix this?

Besides that, I have other sites on this server; none of them has reported this error.

# Answer
> 1 votes
Drupal cannot contact itself. The system module reports this error when a `system_check_http_request()`. Assuming this is the cause of the AJAX errors, you could try, as the error message suggests, to set `$conf['drupal_http_request_fails'] = FALSE;` in your **settings.php** file. This might fix the symptoms, but not the cause however.

The fix lies in figuring out why this check fails:

```
drupal_http_request(url('', array('absolute' => TRUE)), array('max_redirects' => 0));

```

It could be that `url()` is not returning your front page URL. If you have drush on your server, you can run the command `drush php-script my_test_script.php`. With **my\_test\_script.php** containing a simple test script:

```
<?php echo url('', array('absolute' => TRUE)), array('max_redirects' => 0); ?>

```

If it is returning the correct home page URL, another likely problem, since you're hosting multiple sites, is that your domain is not resolving the correct virtual host. You can test this with the server command:

```
wget -O- http://www.example.com/

```

If your site's home page HTML is output to the console that should tell you that the server can contact the resolve & connect to itself. If this is the case it might be something like a PHP config preventing retrieval of HTTP URL's.

# Answer
> 1 votes
Too late, but… You could write the real IP of frontend but not resolved IP by DNS into the /etc/hosts of backend (where php is working), e.g.

Real site IP: 32.32.32.32 Frontend's IP: 192.168.1.65 Backend's IP: 192.168.1.68

```
192.168.1.65      mysite.com

```

---
Tags: 7, blocks, ajax
---


# Question
Title: Downside of not rendering a region in twig template?
Suppose we want to use a different layout/blocks in front page. I know there is a page visibility restriction feature in block configuration, and also `Page Manager` and `Panels`modules exist, but what's the downside of this solution?

1. Define a specific region `content-front` in theme
2. Place some blocks in this this region
3. Render this region only in `page--front.html.twig` template

The above solution has some advantages: front-page blocks are listed separately from other blocks, no need to configure each block to be in `<front>` page (preventing a O(n) task), using native UI to arrange the blocks.

Edits:

* hooks like `hook_block_access` or `hook_preprocess_block` will not be called for a block not being rendered.

# Answer
> 1 votes
> Drupal won’t care and it won’t have any side effects other than the contents of a region not being rendered to a page whose template doesn’t render it

It's not quite that simple.

The problem with dynamically not rendering a region is that Drupal doesn't know about that. It will still load, check and prepare those blocks on every page, which means it is unecessary overhead compared to defining visibility rules to only have it shown on the frontpage. You can also do an empty check of the region in the template and as a result, only have it printed if there are blocks inside (this doesn't work reliably with blocks that might be shown but might be empty but it should work if they are configured to not be shown).

You could also implement a hook\_block\_access() implementation and deny view access for all blocks in a certain region, then you don't need to manually configure them all, but it does need to be in a module.

---
Tags: 8, theming
---


title: Output filename in views

text:
# Question
Title: Output filename in views
I have an uploaded file **my\_cat.jpg** Upon upload, the file-entity's name is by default populated with the file's filename.

Try one: In views, adding a field file:name to my view first looks like the correct answer. But that's the file-entity's name, which can, even after the upload, be changed to eg. **My cat**, while the filename on the disk will never change.

Try two: If i add a file:path field, i can decide if it should output the Download-URL or the internal Filestream-Adress. But no way to leave out the path completely... From the field's name, that's not a big surprise.

So, how can i get just the filesystem-filename **my\_cat.jpg**?

# Answer
> 1 votes
In Drupal 8: in Relationships, add a relationship to your image (mine looks like: Image, (field\_image:target\_id), Content, Appears in: image). In the next step select "Require this relationship". Now, in Fields, you have the filename field available.

---
Tags: views
---


title: Drupal 7 - Cors

text:
# Question
Title: Drupal 7 - Cors
I'm trying to get a hang of the CORS requests.

I'm logged in at the website, this is done manually from the website. Now I'm trying to fetch my own user data from another website.

I have the "fetch token" request up and running just fine.

But when I try to fetch the user data I always get the anonymous user data.

Here is my Drupal Code:

```
 if (isset($_SERVER['HTTP_ORIGIN'])) {
  drupal_add_http_header("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN'], TRUE);
  drupal_add_http_header("Access-Control-Allow-Credentials", "true", TRUE);
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
    drupal_add_http_header("Access-Control-Allow-Methods", "POST, OPTIONS", TRUE);

  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
    drupal_add_http_header(
      "Access-Control-Allow-Headers",
      $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'],
      TRUE
    );
  }
  drupal_exit();
  exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

  global $user;
  netpunkt_provider_remove_user_data($user);

  $return = new stdClass();
  $return->sessid = session_id();
  $return->session_name = session_name();
  $return->user = $user;

  drupal_json_output($return);
  drupal_exit();
  exit;
}

```

Here is my javascript code from the other website:

```
 var createCORSRequest = function(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
      // Most browsers.
      xhr.open(method, url, true);
    } else if (typeof XDomainRequest !== "undefined") {
      // IE8 & IE9
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      // CORS not supported.
      xhr = null;
    }
    xhr.withCredentials = true;
    return xhr;
  };

  function tokenButton() {

    var token = "";

    var url = 'http://******/cors_token';
    var method = 'POST';
    var xhr = createCORSRequest(method, url);

    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/json');

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        token = JSON.parse(xhr.responseText).token;
        document.getElementById("userButton").setAttribute("token", token);
        document.getElementById("tokenSpan").innerHTML = token;
      }
    };

    xhr.onerror = function(data) {
      alert('FEJL');
      console.log(data);
    };

    xhr.send();
  }

  function userButton() {

    var url = 'http://******/cors_check';
    var method = 'POST';
    var xhr = createCORSRequest(method, url);

    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.setRequestHeader(
        "X-CSRF-Token",
        document.getElementById("userButton").getAttribute("token")
    );

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText);
      }
    };

    xhr.onerror = function(data) {
      console.log(data);
    };

    xhr.send();
  }

  document.getElementById("tokenButton").addEventListener(
    "click", tokenButton
  );

  document.getElementById("userButton").addEventListener(
    "click", userButton
  );

```

What am I missing here?

# Answer
I figured out what the problem is...

My Firefox had "Accept third party cookies" set to "Never".

I changed this to "Always" - and Voila - the script now works.
> 0 votes

# Answer
The answer is in *\_drupal\_session\_read()*.

```
if (empty($sid) || !isset($_COOKIE[session_name()]) && !isset($_COOKIE[$insecure_session_name])) {
$user = drupal_anonymous_user();
return '';

```

Since the cors request runs on it's own request, there's no session info, hence you get the anonymous users data.
> 0 votes

---
Tags: 7, http-request
---


# Question
Title: Render the User creation form on another page
I have a Views page and I want to insert the user creation form as found in /admin/people/create into the Views page header. I know people frown upon the PHP filter, but I just need to output the user registration form, which is at most 2 lines of php code vs having to make a module just for that. Unless there is a better way?

I know `drupal_get_form()` has been replaced from the form builder in Drupal 8, and the Drupal 8 equivalent of `drupal_get_form()` is, for example, `$form = \Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class);`.

But how do I get the form name or ID? How do I put it in that example? Do I just inspect the form and grab the form ID?

I tried the following code, but I nothing gets returned. What could I be missing?

```
$form = \Drupal::formBuilder()->getForm(Drupal\user\Form\user_register_form::class);
drupal_render($form);

```

# Answer
You could use the Form Block module and place it before/above your view.

> Enables the presentation of **user registration**, site wide contact, or node creation **forms in blocks**. This is particularly useful for including forms on panels.
>
> Do I just inspect element the form and grab the form id again and replace it with the UserLoginForm section?

You just need the ID `user-register-form` which means your form ID is `user_register_form`

I see now that you're talking about the admin form, I believe you just have to modify the formblock.module file and comment out or remove this part

```
 // Don't display the form to logged in users or if registration is disabled
  if (!$user->uid && variable_get('user_register', 1)) {
    $block['content']['form'] = drupal_get_form('user_register_form');
    $block['subject'] = t('Create new account');
    return $block;
  }

```

So try:

```
$parameter = 'new';
$form = \Drupal::formBuilder()->getForm('user_register_form', $parameter);

```
> 3 votes

# Answer
Its a bit more complicated than render a login form... Here is the correct way to do this:

```
$entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity);
$form = \Drupal::formBuilder()->getForm($formObject);
$form_rendered = \Drupal::service('renderer')->render($form);

```

PS. Found this solition here: http://web-tricks.org/content/how-render-user-login-form-and-user-register-form-drupal-8
> 3 votes

# Answer
I still would like to know how to do it in PHP, but no one has a clear answer on how to render a drupal form in D8.

Instead of code, I just used this module that exposes form blocks in the blocks page: https://www.drupal.org/project/entityform\_block

Looks like this:
> 2 votes

# Answer
You are referring the wrong form class.

* `UserLoginForm` is the class handling the login form
* `user_register_form` is not an existing class, in Drupal 8

What you are looking for is the class for the registration form (i.e. `\Drupal\user\RegisterForm`). The annotation for the `User` entity class tells you which class handles that form.

```
"form" = {
  "default" = "Drupal\user\ProfileForm",
  "cancel" = "Drupal\user\Form\UserCancelForm",
  "register" = "Drupal\user\RegisterForm"
}

```

Notice that instead of using `\Drupal\user\RegisterForm::class`, you can simply use `'\Drupal\user\RegisterForm'`, since the method for building a form accepts also a string.
> 1 votes

# Answer
I had the same issue with this. There are two ways you can do this, but the first way doesn't send any notification emails; it simply registers the user. The second way registers users as normal. Choose the one you need based on your situation. Note that there's different syntax in both examples for doing the same things. Ideally you'd use dependency injection too, rather than loading services directly from the container.

First method (no emails, just saves the entity):

```
$user = User::create();
$form = \Drupal::entityTypeManager()
->getFormObject('user', 'default')
->setEntity($user);
return \Drupal::formBuilder()->getForm($form);

```

Second method (full registration):

```
$entity = \Drupal::entityTypeManager()
->getStorage('user')
->create(array());
$formObject = \Drupal::entityTypeManager()
  ->getFormObject('user', 'register')
  ->setEntity($entity);
return \Drupal::formBuilder()->getForm($formObject);

```
> 1 votes

---
Tags: forms, 8
---


# Question
Title: Entity Query Condition for the referenced entity's type
According to the documentation for the condition() function, you can append columns to a field name, but I haven't found a way to make a condition on the referenced entity's type.

```
// Something like this?
$query->andConditionGroup()->condition($referenceFieldName, $someId)
     ->condition("$fieldName.entity:type", ['character', 'movie'], 'IN')

```

Let's say with the above I am querying for `articles` that have a reference to the ID in `$someId` *and* that reference is to a content type of either `character` or `movie`. Is something like this possible with `entityQuery`?

**Background**: I'm using the Dynamic Entity Reference module, which allows me to make a reference field that can point to either a taxonomy term or a piece of content. I want to query for references to content in that field, but am concerned that there could be an ID overlap. That is, a taxonomy term and `character` for example that both have the ID 123. If I am searching for the ID 123, I would only want `articles` that have references to the `characters` or `movies` with the ID 123, not any taxonomy terms with the ID 123.

# Answer
> 1 votes
since the reference field is using DER, you can use $fieldName.target\_type for finding the referenced entity's type.

---
Tags: 8, entities, taxonomy-terms, database
---


title: single tpl.php file for two nodes?

text:
# Question
Title: single tpl.php file for two nodes?
In my Drupal7, I have same piece of code in tpl.php files for two different nodes. My tpl.php files are following:

```
page--node--9.tpl.php
page--node--11.tpl.php

```

Since code is same for both pages, it is possible to create a tpl.php file for both nodes? I mean something like

`page--node--9and11.tpl.php`

# Answer
You can use `template_proprecess_page` hook to achieve this as shown below:

```
function <THEME_NAME>_preprocess_page(&$vars) {
    if (arg(0) == 'node' && in_array(arg(1), array(9, 11))) {
        $vars['theme_hook_suggestion'][] = 'page__node__9and11'; //For page--node--9and11.tpl.php
    }
}

```

Add above code to `template.php` of your theme & clear cache.
> 2 votes

# Answer
I think isn't an elegant solution but it works for me:

* Create a tpl `page--node--11.tpl.php`.
* And put inside an include of the other template `<?php include( 'page--node--9.tpl.php' ); ?>`
> 0 votes

---
Tags: nodes
---


# Question
Title: Unable to render block in twig after updating Twig Tweak module
I update the Twig Tweak module to version 8.x-2.x. After this update I can't render my disabled blocks anymore?

Before I used `{{ drupal_block('myblockname') }}` to render my block in the twig template.

Now I try to use `{{ drupal_entity('block','myblockname', check_access=false) }}`. But I don't see my blocks in the frontend?

# Answer
It was a docker sync problem. Now with `{{ drupal_entity('block','myblockname', check_access=false) }}` the blocks are visible.
> 3 votes

---
Tags: theming, blocks
---


# Question
Title: search only on taxonomy and user autocomplete drupal 7
I would search only on **user and taxonomy** in autocomplete but not search in content. I try many modules :

1. Views Autocomplete
2. Filters Search Autocomplete
3. Custom Search
4. Term Search

But none complete that ! any clues would be good.

# Answer
Filters Search Autocomplete works great for that but there a bug with entity Reference

> We can achieve this by following these steps:
>
> Add the required node reference field as relationship. Add a title field in fields and give them the above relationship. Add the title in combine filters. It Worked for me :)

read more on drupal.org
> 0 votes

---
Tags: search
---


# Question
Title: Can I check a file's properties before saving it with system_retrieve_file?
My understanding of `system_retrieve_file` is that it saves the file temporarily first. Is it possible to check this file and if it passes, then save it?

I've only used this function like below.

```
$image = 'http://.jpg';
$file = system_retrieve_file($image, 'public://images/', TRUE, $replace = FILE_EXISTS_REPLACE);

```

Thanks

# Answer
> 0 votes
It depends on what the file "properties" you're wanting to check here.

The file contents? Sure. You can invoke `$result = drupal_http_request($url);`(7) or `\Drupal::httpClient()->get($url)->getBody();`(8) ahead of time to inspect the HTTP contents before calling `system_retrieve_file()`.

The file entity properties (or the temporary file created before moving to `$destination`)? No (without replicating/modifying some core functionality). There are no open hooks to that before `system_retrieve_file()` commits to saving that data to filesystem/DB.

---
Tags: files
---


# Question
Title: How to show the user badges in my tpl.php file?
This maybe a dumb question but what am I doing wrong?

From here: https://www.drupal.org/node/942014

It says I have to insert:

if (module\_exists('user\_badges')) { print user\_badges\_for\_uid($uid); }

When I insert that on the last line of my node.tpl.php it just shows as Text (like the whole code shows on the website). What am I doing wrong??

Can someone please help me?

# Answer
The first thing that you need to do is add the php tag to the code:

```
<?
if (module_exists('user_badges')) {
 print user_badges_for_uid($uid);
}
?>

```

But for to that this code works you need to pass the uid = User Id

This code should do the job:

```
<?
// Getting the actual user.
global $user;

if (module_exists('user_badges')) {
 print user_badges_for_uid($user->uid);
}
?>

```
> 1 votes

---
Tags: 7, theming, users
---


# Question
Title: How to use 'use-ajax' class with pages created by controller?
I'm trying to use 'use-ajax' class to load a page inside a modal box.

My Page is dynamically created using node id pass on my page controller

My link looks like this

Any idea on how can I achieve my goal?

# Answer
This is a render array that create a link that open a modal windows.

```
use Drupal\Core\Url;

public function build() {
$output = array();
$output['overlay_link'] = array(
  '#type' => 'link',
  '#title' => $this->t('Add an activity'),
  '#url' => Url::fromRoute('node.add', ['node_type' => 'event'], ['query' => ['destination' => $destination],
    'absolute' => TRUE,]),
  '#attributes' => [
    'class' => ['use-ajax', 'button', 'secondary'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => \Drupal\Component\Serialization\Json::encode(['title' => t('Add an activity'), 'width' => 800,]),
  ],
);
 return $output;
}

```
> 1 votes

---
Tags: 8, theming, ajax, page-controller
---


title: Preprocess function for body field?

text:
# Question
Title: Preprocess function for body field?
I have a client with a D8 site who wants curly quotes and apostrophes on all rendered content. I was able to do this for the page titles with this preprocess function:

```
function mytheme_preprocess_page_title(&$variables) {
// Load the node entity from the current route
if ($node = \Drupal::request()->get('node')) {

    // Get the title
    $title = $node->getTitle();

    // Replace left quotes
    $title = preg_replace('/"(?=\w)/', '“', $title);

    // Replace right quotes
    $title = preg_replace('/(?<=\w)"/', '”', $title);

    // Replace single quote/apostrophe
    $title = str_replace("'", '’', $title);

    // Return the title variable
    $variables['title'] = t($title);
}
}

```

Is there a way to do this for the body field as well? hook\_preprocess\_field isn't getting me anywhere.

# Answer
> 0 votes
Instead of using a preprocess function, you could accomplish the desired behavior using CSS.

Using the `::before` and `::after` selectors you can insert additional content. This content could be the textual " character (i.e., `content: '"';`) or you could display it as an (inline-)block, provide width, height, margin and padding and set a background image.

For example:

```
.field--name-body {
  padding-left: 1em;
  padding-right: 1em;
}

.field--name-body::before {
  content: '"';
  position: absolute;
  top: 0;
  left: 0;
}

.field--name-body::after {
  content: '"';
  position: absolute;
  right: 0;
  bottom: 0;
}

```

This creates some space around the body field and provides " characters at the top left and bottom right location.

---
Tags: theming
---


# Question
Title: How to have a separate image style for an image field for the 1st views row?
First I tried with views\_conditional (which was already installed on the site) to check for 1st row and output the specific image but it does not seem to work as per this issue

Ideally I want to do it without installing an extra module.

I tried with `THEMENAME_preprocess_views_view_field` but the image was already rendered at this stage. Have used the somewhat hackish str\_replace but it does not actually work.

```
function THEMENAME_preprocess_views_view_field(&$vars) {
  if($vars['view']->element['#name'] == "free_write"
      && $vars['field']->field == "field_main_image"
      && $vars['row']->index == 1
      ){
    $html = str_replace("teaser_media_small","teaser_media_medium",$vars["output"]->__toString());
    $vars["output"] = Drupal\Core\Render\Markup::create($html);
  }
}

```

what is the proper way to do this in a preprocess function or perhaps in a twig template ?

# Answer
> 4 votes
A solution can be Add an Attachment Display to the View, in the Attachment you can select to show only one element with a different style and you can give as position Before.

In the Page then you select to skip 1 element.

This will output something like this:

# Answer
> 3 votes
Another option, is to simply `add` your image field again and give it the other image style and only print this field in the first row via preprocess function.

If you want to use twig, you can add "count" as a field and use that to know which row you're on in your conditional.

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


title: Download all files attached on a site

text:
# Question
Title: Download all files attached on a site
I have researched a little bit and I haven't found a sound solution to downloading all attached files from all content types across an entire site in an single action. I have found a couple modules like Backup & Migrate, or its plugin Backup & Migrate Files that perform similar functions, but nothing to effect that I need. I am trying to archive all attached files for a schools site. The site is drupal7.

# Answer
If you want the entire `files` directory of uploaded files, you can do this with Drush:

```
drush rsync @source.target:%files/ @destination.target:%files

```

See: https://drushcommands.com/drush-8x/core/core-rsync/

This relies on having `%files` defined in your `path-alias` part of your alias definitions for drush.

Alternatively, you could ssh into the server, and tar/gzip the files directory, then scp it down to your machine (or sftp/ftp, I suppose).

Either of these methods will bring the entire files directory with it, which will have all uploaded files, any image derivatives (generated image style files) as well as cached css/js files. If you use the drush command with arguments, you can exclude directories you don't want.
> 0 votes

---
Tags: files
---


# Question
Title: Why I should use dependency injection in Drupal 8?
Why is this

```
__construct(MyService $my_service ) {
   $this->my_service = $my_service;
}

create (ContainerInterface $container) {
  return new static(
      $container->get('my.service'));
}

```

better than

```
__construct() {
    $this->my_service = new MyService();
}

```

?

# Answer
From Services and dependency injection in Drupal 8:

> ... is best practice to access any of the services provided by Drupal via the service container to ensure the decoupled nature of these systems is respected.

A clear example can be found in Drupal 8 Dependency Injection, Service Container And All That Jazz:

> Take the following simple class:
>
> ```
> class Car {
>
>   protected $engine;
>
>   public function __construct() {
>     $this->engine = new Engine();
>   }
>
>   /* ... */
>
> }
>
> ```
>
> When you instantiate a new class `Car` you go like this:
>
> ```
> $car = new Car();
>
> ```
>
> And now you have an object handler (`$car`) that has an `$engine` property containing the handler of another object. But what if this car class needs to work with another engine? You'd have to extend the class and overwrite its constructor for each new car with a different engine. Does that make sense? No.
>
> Now consider the following:
>
> ```
> class Car {
>
>   protected $engine;
>
>   public function __construct($engine) {
>     $this->engine = $engine;
>   }
>
>   /* ... */
>
> }
>
> ```
>
> To instantiate an object of this class, you go like this:
>
> ```
> $engine = new Engine();
> $car = new Car($engine);
>
> ```
>
> Much better. So now if you need to create another car using another engine, you can do so easily without caring about the Car class too much since it is supposedly equipped to work with all the engines in your application.
>
> ```
> $turbo = new TurboEngine();
> $car2 = new Car($turbo);
>
> ```
>
> And that is dependency injection. The `Car` class depends on an engine to run (dooh), so we inject one into its constructor which then does what it needs to do. Rather than hardcoding the engine into the Car class which would not make the engine swappable. Such constructor injections are the most common but you'll also find other types such as the setter injection by which we would pass in the engine through a setter method.
>
> So there you go. Dependency injection is a very simple concept that has to do with the practice of decoupling functionality between classes. By passing dependencies to objects we can isolate their purpose and easily swap them with others. Additionally, it make is much easier to unit test the classes individually by passing mock objects.
> 1 votes

---
Tags: 8, dependency-injection
---


title: Actions module - redirect to url

text:
# Question
Title: Actions module - redirect to url
I'm trying to learn about the functionality of this module, however I don't understand quite right what the *Redirect to URL* option means/does. Any hint in the right direction will be much appreciated.

# Answer
> 1 votes
"Redirect to URL" means that when the action is executed the user will be taken to the specified URL.

This action does exist in Drupal 7 and Drupal 6 as well.

---
Tags: 8, redirection, actions
---


title: Add JavaScript inside controller

text:
# Question
Title: Add JavaScript inside controller
How to add JavaScript inside controller? I don't want to call build form. I can call css or js in `src/Form/Form.php` but I want to call css or js inside Controller `src/Controller/Controller.php` This process I am using to call css and js in Form page

```
public function buildForm(array $form, FormStateInterface $form_state,$cid = NULL)
{

$form['#attached']['library'][] = 'cssjs/val_master';

}

```

Could anyone write some example to call css or js inside Controller

Thanks.

# Answer
The same you can use in Controller also:

```
<?php

   namespace Drupal\cssjs\Controller;

   use Drupal\Core\Controller\ControllerBase;

   class CssJs extends ControllerBase{
     public function css_js(){
       $build['#attached']['library'][] = 'cssjs/val_master';
       return $build;
     }

   }

```
> 3 votes

---
Tags: 8, javascript, page-controller
---


# Question
Title: Using #attached to attach js to form by a custom module
**My idea:**
I am trying to use a module to manage all the js and css with #attached method.
**`#attached` method I found from:**
\- Adding CSS and JS to form with attachments
\- https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

**My module folder containing:**
testing.info
testing.module
js/mask.js

**In testing.info**, it's including file testing.module
files\[\] = testing.module

**In testing.module**, I'm trying to use the #attached method to attach "jquery mask" to all form tags, including add/edit node, webform field.
Here is my code but it does not work. -\___-

```
function testing_init() {
  $build['#attached']['js']['https://cdn.testing.com/jquery.mask.min.js'] = array('type' => 'external');
  $form['#attached']['js'][] = drupal_get_path('module', 'testing') . '/js/mask.js';
}

```

**Question:**
Am I using the wrong method to attach js to form tag?
I don't want to load these files on all pages, what is the better way?

# Answer
> @NoSssweat is it possible only load for add/edit node and webform(not search form)? – CocoSkin

You can by utilizing hook\_form\_BASE\_FORM\_ID\_alter

For node's add/edit form:

```
/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}

```

For Webform:

```
/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_webform_client_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}

```
> 2 votes

---
Tags: 7, forms
---


title: Why aren't I allowed to log in?

text:
# Question
Title: Why aren't I allowed to log in?
I have a local setup for an online running Drupal 7 website on Ubuntu 14.04. I upgraded to Ubuntu 16.04 and I restored the local setup.

I can access the website on localhost, but it doesn't allow me to log in as administrator user nor as normal user, whereas everything is working fine on the production server.

What can the issue be?

# Answer
Oh my bad! after wasting days i come to know that the `rewrite` module was disabled. after enabling rewrite module all works thanks
> 0 votes

---
Tags: 7, users
---


title: Drupal compute field devel display

text:
# Question
Title: Drupal compute field devel display
I have created a compute field in Drupal 7 in which I want all the fields above to display through devel something like `dpm($all field);`.

# Answer
```
if ($node = menu_get_object()) { // check if you're on a node page & get node object.
  dpm($node); // dump the node object which contains all fields.
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Alter existing route to a different route for a specific content type node using RouteSubscriber
I want to modify node edit of a specific content type node to a different route .

Eg : suppose i have a node edit page route as `entity.node.edit_form` (core feature) . And now i want to change this route to `custom_module.edit_form` when taking the node to edit .

I refered This which explains altering the **`existing route to a different route`** . It only says to route to a different url . It may not work in my case as node edit form will contain **`node id`** as parameter . Its not mentioning how routes can be placed in **`$route->setPath()`** though .

For eg: In **`custom_module/src/Routing/RouteSubscriber.php`**

```
/**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/login' to '/login'.
    if ($route = $collection->get('user.login')) {
      $route->setPath('/login');
    }
    // Always deny access to '/user/logout'.
    // Note that the second parameter of setRequirement() is a string.
    if ($route = $collection->get('user.logout')) {
      $route->setRequirement('_access', 'FALSE');
    }
  }

```

How can i do this ?

# Answer
Hi i done this as follows : in **`RouteSubscriber.php`** :

```
<?php

namespace Drupal\module_name\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/node/edit' to custom controller action.
    if ($route = $collection->get('entity.node.edit_form')) {
        $route->setDefault('_controller', '\Drupal\module_name\Controller\MyController::alter_edit_route');
    }
  }
}

```

and in **`MyController.php`** :

```
/**
 * Function to redirect the edit route to custom route
 */
public function alter_edit_route(){
    $node_id = \Drupal::routeMatch()->getRawParameter('node');
    //get the content type using node id
    $entityObj  = entity_load('node',$node_id);
    $bundle = $entityObj->bundle();
    if($bundle=="custom_service_name"){
        //redirect to custom service list page
        $response = new RedirectResponse('/module_name/custom_service/'.$node_id);
        $response->send();
       return;
    }
    else return $this->redirect('entity.node.edit_form', ['node' => $node_id]);
}

```

**NB:-** A problem here is that its **`redirecting to the custom url for the specific content type`** . But when taking **`other content type nodes`** its **`hanging with the too many redirections.`**

Welcoming your insights on this . thanks .

# **UPDATE**

Okay , here its how i resolved the problem . For the custom content type node its using the redirectResponse to redirect to custom page . For other content type nodes its creating the specific content type form and load the values to it for the specific node id . So in **`MyController.php`**

```
  /**
     * Function to redirect the edit route to custom route
     */
    public function alter_edit_route(){
        $node_id = \Drupal::routeMatch()->getRawParameter('node');
        //get the content type using node id
        $entityObj  = entity_load('node',$node_id);
        $bundle = $entityObj->bundle();
        if($bundle=="custom_service_name"){
            //redirect to custom service list page
            $response = new RedirectResponse('/module_name/custom_service/'.$node_id);
            $response->send();
        }
        else {
            //programmatically load the node edit page with value
            $node = \Drupal::entityTypeManager()->getStorage('node')->load($node_id);
            $form = \Drupal::entityTypeManager()
              ->getFormObject('node', 'default')
              ->setEntity($node);
            return \Drupal::formBuilder()->getForm($form);
        }
    }

```
> 3 votes

# Answer
You need to change the \_controller for the route, check this code:

```
<?php

namespace Drupal\drush_help\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change the controller for the help page.
    if ($route = $collection->get('help.page')) {
      $route->setDefault('_controller', '\Drupal\drush_help\Controller\HelpController::helpPage');
    }
  }

}

```

In this case the route is altered to replace the Drupal help page for a custom controller.

If you want to see this in action go to check the code of the Drush Help module.

Disclosure: I'm the maintainer of the module Drush Help.
> 1 votes

---
Tags: 8, routes
---


title: False variation title is displayed

text:
# Question
Title: False variation title is displayed
On my Commerce Kickstart Page, I have each prodcut with 2 different variations. My problem is that I am unable to change the variation title for the product variations that have been added first on the product itself. It continuously overrides my changes with the original, auto-generated title for a couple of products, but not all of them. The second variation is always called "DVD - Product name" and works fine.

The first is set up like this:

When I now click on "Update product", it shows the correct values in the overview of the variations:

I now simply say "Save" on my edit product view and save the product. I click edit again and the old value is back as the variation title. But when I open the variation settings, it still shows me my changed title in the textfield:

I already took a look into the database, and the correct value (my changed title) is stored there. This made me think that this is a chaching problem, I played around with cache settings and stuff but that did not change anything.

It may also be noted that this problem does only occur for about 30% of my products, and also only for the first added products.

# Answer
This happens when you go into a product display and then edit the variations inline from there. To stop this happening go to the manage fields screen for your product display e.g. "Structure \> Content types \> Product display \> manage fields"

Then click edit on the "Product" field and you should see "Auto generate the product title" tick box. Untick that and it should stop the issue happening going forward
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Pop-Up E-mail subscription ( module) or appearing form?
Is it possible **with a certain module or anything of that nature** to have a pop with a subscription email-collector inside?

I'm on the final touch-ups of the site and have basically got this left and a few other things. But there is not really too much on this site that I can find that answers this question directly for a newbie.

# Answer
> 1 votes
You can try the Lightbox2 module

> The Lightbox2 module is a simple, unobtrusive script used to overlay images on the current page. It's a snap to setup and works on most modern browsers.

or the CTools Auto-modal module

> Provides automatic modal support for any hook\_menu() paths that have 'modal' =\> TRUE defined. This makes it easy to add optional modal support in any contrib module and helps reduce the burden on module developers to support modals.

# Answer
> 0 votes
For drupal 8 users, Check this module https://www.drupal.org/project/simple\_popup\_blocks.

**Description:** You can turn any blocks, views, forms or anything with CSS selectors into popup.

---
Tags: 7, forms, emails
---


title: Access trimmed description in module

text:
# Question
Title: Access trimmed description in module
I have a content type with a *Long text and summary* field. In the node view display, it is set to to show as *Summary or trimmed*.

I have a module that gets all the nodes of that content type.

How do I programmatically get the trimmed value of that field? Using `var_dump()`, I get the following output.

```
  ["field_description"]=>
  array(1) {
    ["und"]=>
    array(1) {
      [0]=>
      array(5) {
        ["value"]=>
        string(5763) "<p>Test user DescriptionTest</p>"
        ["summary"]=>
        string(0) ""
        ["format"]=>
        string(9) "full_html"
        ["safe_value"]=>
        string(5764) "<p>Test user Description</p>"
        ["safe_summary"]=>
        string(0) ""
      }
    }

```

# Answer
> 1 votes
The summary value will only be set if someone has actually filled out the summary textfield when editing the node. You'll need to do the trimming yourself in code. Drupal has functions such as https://api.drupal.org/api/drupal/modules%21field%21modules%21text%21text.module/function/text\_summary/7.x or views has https://api.drupal.org/api/views/views.module/function/views\_trim\_text/7.x-3.x

So you'll need to do a check to see if the summary value exists, if it doesnt use the main text and trim it with the functions or something similar above

---
Tags: 7, nodes
---


# Question
Title: Aggregated javascript contains binary data, breaks site
Today I noticed a site's javascript was broken. One of the aggregated javascript files contained a bunch a binary data that (obviously) caused a syntax error;

```
‹EAk1…ÿŠæ”°!«Ð–¢Á¶]¤µ'³³6â&K2ºÑßÞ,J{3ï½éWgÈzÇAn¤ç#„^)QVãR³ù¬X³ìzåÜaÛ{B¡¶H[#ùóÓ>
Ë

```

After deactivating the js aggregation the site works fine, and none of the javascript looks off.

# Answer
> 0 votes
Turns out the problem was caused by an external javascript file that had been added through `drupal_add_js` without specifiying it being `external`. In my case specifically the pinit module for Pinterest was the culprit.

The external server had recently enabled http gzip compression, so the end result was gzipped data being straight up being concatenated into the js aggregation.

---
Tags: 7, css-js-aggregation
---


# Question
Title: How to display fields of an entity reference field?
My content type have an "entity reference field" related to another content type.

The only option I have is to display a link to the entity.

How can I display other fields from this entity?

# Answer
You can choose `rendered entity` instead of `label`.

After that click the options button (cog wheel) and choose the `view mode` of the rendered entity.

You can go the referenced content type's `manage display` and modify the chosen `view mode` to display the fields that you want

**NOTE** you can enable more display modes from `manage display > Default > custom display settings`

and can also create your own `view mode` by pressing `manage view modes` on the bottom of the same screen
> 6 votes

---
Tags: 8, entities
---


title: Changing the sender of email

text:
# Question
Title: Changing the sender of email
I am using the Printer, email and PDF versions module, together with the PHPMailer module to send emails. It works perfectly, but only from the email in admin/config/system/site-information. How could I use `hook_mail_alter()` or similar hook in order to send from different accounts of the site depending on the situation?

Do I need to install another module, or can it be achieved by using a hook? `hook_mail_alter()` just have "from" but that is a dummy email address which can be even simulated.

# Answer
> 2 votes
After many unsuccesful tests, I have finally found the solution through Set the "from" header in the email to be in the format "Full Name" \<email@address.com\>.

In your module, you must use the following code, which can be customized via the ID of the email or other parameters which are contained in the variable $message (which is passed by reference, so can be modified by the hook):

```
function my_module_mail_alter(&$message){

    $from = "user-account@domain.name" ;

    $message['from'] = $from;
    $message['headers']['From'] = $from;
    $message['headers']['Sender'] = $from;
    $message['headers']['Return-Path'] = $from;

} // function

```

# Answer
> 2 votes
I used the code from @Cesar above but ran into some trouble. I wanted to specify the name of the sender as well but ran into encoding issues.

This was what I used in the end:

```
function custom_module_mail_alter(&$message) {
  $name = variable_get('site_name', 'My awsöme site');
  $mail = variable_get('site_mail', 'contact@myawsomesite.se');
  $message['from'] = mb_encode_mimeheader($name, 'UTF-8', 'Q') . ' <' . $mail . '>';
  $message['headers']['From'] = $message['headers']['Sender'] = $message['from'];
}

```

Setting the `Return-path` header caused the e-mail to be sent to the sender address (contact@myawsomesite.se) as well as the intended recipient.

# Answer
> 0 votes
if that could help someone , a snippet on D8 to send e-mails. The reply from Cesar with the headers also sorted me out

```
    //logic if i send or not and to who then
    if ($send) {
        $mailManager = \Drupal::service('plugin.manager.mail');
        $module = "mymodule";
        $key = 'state_changed_action';
        $to = $send_to;

        $langcode = \Drupal::currentUser()->getPreferredLangcode();

        $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

        if ($result['result'] !== TRUE) {
          drupal_set_message(t('There was a problem sending notifications.'), 'error');
        }
        else {
          drupal_set_message(t("A notification has been sent to $to"));
        }
      }
    }

    /**
     * Implements hook_mail().
     */
    function amu_dud_rules_mail($key, &$message, $params) {
      $options = [
        'langcode' => $message['langcode'],
      ];
      switch ($key) {
        case 'state_changed_action':
          //$message['from'] = \Drupal::config('system.site')->get('mail');
          $from='mysite-noreply@mydomain';

          $message['from'] = $from;
          $message['headers']['From'] = $from;
          $message['headers']['Sender'] = $from;
          $message['headers']['Return-Path'] = $from;
          $message['subject'] = t('@title', ['@title' => $params['node_title']], $options);
          $message['body'][] = $params['message'];
          break;
      }
    }

```

---
Tags: 7, emails
---


# Question
Title: Why table creation on module install doesn't work?
I need to create custom table for module, but after module install table is not created.

module.install file:

```
function bip_content_migration_schema() {

    $schema['bip_migrate'] = array(

            'description' => 'Storing content migration info from Joomla.',
            'fields' => array(

                    'id' => array(
                            'description' => 'id',
                            'type' => 'serial',
                    ),
                    'content_type' => array(
                            'description' => 'content type',
                            'type' => 'varchar',
                            'not null' => TRUE,
                            'length' => 255,
                    ),
                    'imported_count' => array(
                            'description' => 'imported count',
                            'type' => 'int',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'to_import_count' => array(
                            'description' => 'to import count',
                            'type' => 'int',
                            'not_null' => TRUE,
                    ),
                    'is_imported' => array(
                            'description' => 'is imported',
                            'type' => 'int',
                            'default' => 0,
                    ),
            ),
            'primary key' => array('id'),
            'indexes' => array(
                    'id' => array('id'),
            ),
    );
    return $schema;

}

```

What am I doing wrong?

**EDIT**

I added functions to my .install file (thought that I can ommit theme)

```
function bip_content_migration_install() {
    drupal_install_schema('bip_content_migration');
}

function bip_content_migration_uninstall() {
    drupal_uninstall_schema('bip_content_migration');
}

```

But again table is not created.

# Answer
In Drupal 7, it is not necessary to call `drupal_install_schema()`, or `drupal_uninstall_schema()`; that is automatically done from Drupal. It is enough to implement `hook_schema()`, and the database table is created. There are many modules for Drupal 7 implementing that hook, and their database tables are created.

I can think of two possible causes for the database table not being created:

* The short name of the module is not bip\_content\_migration
* You added the `hook_schema()` implementation on an already installed module

If you installed the module, disabled it, changed the code, and re-enabled it, the database table would not be created. Disabling a module is different from uninstalling it. Uninstalling is done when a module is disabled, and then uninstalled from the "Uninstall" tab in admin/modules.

I didn't considered the following two cases, as Drupal should have given you some errors:

* The schema is not correct
* Drupal is not able to connect to the database, while installing the module.

If there are more databases, be sure you are looking at the right database.
> 6 votes

# Answer
I know this is old but anyway. If you are trying to see changes on **re-enable** the module, first, you need to disable and uninstall the module. Use

> drush dre \[module\]

More info here hook\_schema is not creating database table
> 1 votes

# Answer
Disable the module. Search your module name in 'system' table name column(drupal database) and delete that particular column. Try again by enabling the module. your table will be created.
> 0 votes

---
Tags: 7, installation
---


# Question
Title: How to tell if the current revision is the original?
I want to display a different "Submitted by" message for content that has been updated, and thus has multiple revisions.

How can I tell if I'm on the original revision, or if there are multiple revisions?

# Answer
> 2 votes
`NodeStorage::revisionIds()` will let you retrieve all revisions of a node which will let you compare against the current node's version.

```
 // Retrieve all vids.
 $nid = 123;
 $node = Drupal\node\Entity\Node::load($nid);
 $vids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);

 // Does the original node's vid match the current node's vid?
 return (reset($vids) == $node->vid->getString());

```

---
Tags: 8, nodes
---


title: Create node from another node

text:
# Question
Title: Create node from another node
How do I create a node from an existing content type on front end? Let's say we have a article i need to associate tags with it in a fashion. For example a book of tags which a user can view . Either we can create a book or we can add tags to an already existing book. Those books are binded to a user also.

# Answer
Well if what I getting from you is right then you have to look into Taxonomy Vocabulary and terms.

So you can have a Vocabulary of Sports but under sports there are so many taxonomy terms - types of sports, like footbal,hockey,basketball etc

then for your content type you add a taxonomy field mapped to the sports vocabulary

now users can create content and add the various tags/terms to it.

if not then you may have to look at using books in drupal
> 0 votes

# Answer
This is not really a ready-to-use answer, but hopefully a nod in the right direction...

Have a look at the Flag module. In Drupal 7, you could build something like that with Flag and the Flag Lists modules. For Drupal 8 I'm not sure, but I guess it's worth giving it a try.
> 0 votes

---
Tags: 8, nodes, entities
---


# Question
Title: Front Page button to add new element in node
I'm completely new to drupal and actually building a charity community site on Drupal 8.

I have a content type "PROJECT" with a field "PROJECT MEMBERS" as entity reference to "USER".

Now I would like to have a button on the display of any project node "REGISTER ME FOR THIS PROJECT".

If an authenticated user clicks on that button his name should be added as new Project Member Element in my node.

Is there any way to do this ? Thank you so much !

Cheers, Tom

# Answer
> 0 votes
There are ways. Here is one:

You will have to programmatically add value to that entity reference field. Here is how you should do it Programmatically update an entity reference field (see the multiple values case)

To make your button work you will need to add a route with arguments (one argument of the content ID you are adding a current user into) see here https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

And in order to add a button you can just update/override a corresponding twig template to inject HTML code of a button there referring the path of the route above with the `nid` as a parameter.

---
Tags: nodes, entities
---


title: Where can I find my edit profile file

text:
# Question
Title: Where can I find my edit profile file
I'll try to make this as simple as possible.

I use Drupal Commons and want to add this code:

```
if (module_exists('user_badges')) {
    print user_badges_for_uid($uid);
}

```

to my profile user's profile page.

Does anyone know where I can find that?

What I want to do: https://www.drupal.org/node/942014

# Answer
> 2 votes
I've not used this particular distro, or module... there's not a block that already contains the user badges? There are several places you could add the code, there might be more:

---
Tags: theming
---


# Question
Title: Change the name of uploaded file based on content type and entity id
Consider this pattern :

> \[content type\]-\[entity ID\].\[file:ffp-extension-original\]

is there any hook so I can change the uploaded file name based on content type and node ID in drupal 8?

PS:

I used File(field) paths module but I couldn't find proper tokens to get it work right

# Answer
> 1 votes
As I needed to know some data about the node which the file is added to, none of hook\_file\_update, hook\_file\_presave or hooks like that was proper for my needs, while I was searching I found a drupal 7 solution, so I changed the code to get it to work.

Here is the module I wrote, this module works on any file and image field :

```
<?php
/**
 *@file
 * this module alters node forms and adds a submit handler which inside that it renames the uploaded files
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity;
use Drupal\Core\Entity\ContentEntityForm;

function file_name_converter_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $bundle = FALSE;
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof ContentEntityForm) {
    $bundle = $form_object->getEntity()->bundle();
    $form_state->set('#bundle_value', $bundle);
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'file_name_converter_node_form_submit';
      }
    }
  }

}

function file_name_converter_node_form_submit(&$form, FormStateInterface $form_state) {

  $values = $form_state->getValues();
  $bundle = $form_state->get('#bundle_value');

  $bundle_fields = \Drupal::entityManager()->getFieldDefinitions('node', $bundle);

  foreach ($bundle_fields as $field_name => $field_definition) {
    if (!empty($field_definition->getTargetBundle())) {
      $field_type = $field_definition->getType();
      if($field_type == 'image' || $field_type == 'file') {
        if(!empty($values[$field_name])) {
          foreach ($values[$field_name][0]['fids'] as $delta => $fid) {
            $file = file_load($fid);

            $uri = $file->getFileUri();
            $fname = $file->getFilename();
            $exp = explode('.', $fname);
            $extnsn = $exp[count($exp)-1];

            $new_name = 'MySite-' . $field_type . '-' . $bundle . '-' . $values['nid'] . '.' . $extnsn;

            $new_uri = str_replace($fname, $new_name, $uri);

            // And finally rename the file.
            file_move($file, $new_uri);
          }
        }
      }
    }
  }
}

```

# Answer
> 1 votes
You might be able to do this with hook\_ENTITY\_TYPE\_update(). Take a look at the D8 version of the upload\_replace module code for an example of changing filenames.

---
Tags: 8, nodes, entities, files
---


# Question
Title: How to handle password field for externally authenticated users (Oauth2)?
I'm working on an Oauth2 authentication implementation where I need to provide content access to external users authenticated against an Oauth2 server which provides me with user info. From my understanding of Drupal's user system, this requires me to create a local user populated with the information provided via the API. I've been looking at the user\_external\_login\_register function and it looks like one of the expected user fields is a password. In my case, since the users are authenticating against an external server, the only validation info I have for them is the auth token, and it would actually defeat the purpose for me to have their password. So, should I provide a dummy password?

# Answer
> 1 votes
It depends on how you want Oauth integration to work.

If the Oauth integration is a supplement, then you should let users define a password themselves, so they can either login with username/password or Oauth. If you don't want users to login directly on the Drupal site with credentials but only use Oauth, you can use `user_external_login_register`. This willassign a random password to the user, since the password property is required, a random password is generated on the fly:

```
...
$userinfo = array(
  'name' => $name,
  'pass' => user_password(),
  'init' => $name,
  'status' => 1,
  'access' => REQUEST_TIME,
);
$account = user_save(drupal_anonymous_user(), $userinfo);
...

```

---
Tags: users, authentication-authorization
---


# Question
Title: Varnish doesn't cache first hit at all, only second hit
I have Varnish 4 with Drupal 7. In Drupal `settings.php` I have:

```
// Tell Drupal it's behind a proxy.
$conf['reverse_proxy'] = TRUE;

// Tell Drupal what addresses the proxy server(s) use.
$conf['reverse_proxy_addresses'] = array('127.0.0.1');

// Bypass Drupal bootstrap for anonymous users so that
// Drupal sets max-age < 0.
$conf['page_cache_invoke_hooks'] = FALSE;

// Make sure that page cache is enabled.
$conf['cache'] = 1;
$conf['cache_lifetime'] = 0;
// Set page cache max-age to 600 secs (10 min)
// Change this to the highest time possible for your needs
// Drupal will set a Cache-Control: "max-age=600" header
$conf['page_cache_maximum_age'] = 21600;

$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');

$conf['cache_class_cache_page'] = 'VarnishCache';

```

In the varnish vcl file I have:

```
vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
    # Happens before we check if we have this in cache already.
    #
    # Typically you clean up the request here, removing cookies you don't need,
    # rewriting the request, etc.

 ## ADMIN PAGES ##

    # Here we filter out all URLs containing Drupal administrative sections
    if (req.url ~ "^/status\.php$" ||
        req.url ~ "^/update\.php$" ||
        req.url ~ "^/admin$" ||
        req.url ~ "^/admin/.*$" ||
        req.url ~ "^/user$" ||
        req.url ~ "^/user/.*$" ||
        req.url ~ "^/flag/.*$" ||
        req.url ~ "^.*/ajax/.*$" ||
        req.url ~ "^.*/ahah/.*$") {
           return (pass);
    }
}
sub vcl_backend_response {
    # Happens after we have read the response headers from the backend.
    #
    # Here you clean the response headers, removing silly Set-Cookie headers
    # and other mistakes your backend does.
if (bereq.url ~ "(?i)\.(css|js|jpg|jpeg|gif|png|ico)(\?.*)?$") {
        unset beresp.http.set-cookie;
    }
# Set cached objects to expire after 1 hour instead of the default 120 seconds.
    set beresp.ttl = 4h;
}

sub vcl_deliver {
    # Happens when we have all the pieces we need, and are about to send the
    # response to the client.
    #
    # You can do accounting or modifying the final object here.
if (obj.hits > 0) {
               set resp.http.X-Cache = "HIT";
        } else {
               set resp.http.X-Cache = "MISS";
        }
}

```

This is my header at isvarnishworking:

```
HTTP/1.1 200 OK
Date:   Fri, 02 Mar 2018 13:51:24 GMT
Content-Type:   text/html; charset=utf-8
Connection: keep-alive
Set-Cookie: __cfduid=dfac4e840061f192552b77dfd3430fcfc1519998683; expires=Sat, 02-Mar-19 13:51:23 GMT; path=/; domain=.mydomain.net; HttpOnly
X-Powered-By:   PHP/5.4.45
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control:  max-age=64800, public
X-Content-Type-Options: nosniff
Content-Language:   en
X-Frame-Options:    SAMEORIGIN
X-Generator:    Drupal 7 (http://drupal.org)
Vary:   Accept-Encoding,User-Agent
X-Varnish:  459087
Age:    0
Via:    1.1 varnish-v4
X-Cache:    MISS
Server: cloudflare
CF-RAY: 3f54567d343346ec-EWR
Content-Encoding:   gzip

```

I'm using Cloudflare, but I've already been try to shutdown Cloudflare for 2-3 days. Still, Varnish doesn't hit the first time, only the second time.

# Answer
> 2 votes
It looks like a normal behaviour :

* first url hit : Varnish puts the page in cache with some id
* only following hits will serve the *cached id* instead of querying the backend.

If you want anonymous users to be always served by varnish, you need to implement a **cache warmer** logic.

Setup a sitemap. Then create a cron task that will parse the sitemap with `curl` for instance, and run that cron task at a frequency synced with your cache expiry time...

---
Tags: 7, caching, proxies
---


# Question
Title: Images break with wrong href; clearing caches fixes!
Occasionally we will have graphics in various places on the site that are missing because of incorrect hrefs with unknown subdomains and are fixed when the caches are cleared. So an incorrect link

https://www.**xfdg**.oursite.com/sites/image.jpg

is only fixed after cache clear

(correct https://www.oursite.com/sites/image.jpg)

We are also seeing results in Google that have weird unknown subdomain URLs, in the same manner as the image URLs.

I had read in https://www.drupal.org/node/1992030 “Protecting against HTTP HOST Header attacks (prevent your site from thinking it is someone else)” that it could be spam or errors with Drupal’s cron could be responsible.

Any ideas or directions?

# Answer
> 0 votes
More than likely, your server is responding to multiple domain names, either by being the default or matching/wildcards for `ServerName` and `ServerAlias` (using Apache terminology here; nginx and IIS have similar concepts).

So, the problem is that you get a request to www.example.com, and Drupal serves that page up and uses that URL as the base. It will also respond to www.subdomain.example.com and use that as the URL base. The problem you see is that the subdomain request is the one being cached, and the hostname isn't part of the cache ID.

The general solution to this is to set up a canonical redirect in either the Apache config or the .htaccess file for your site (I prefer in server config). The rule would look something like this

```
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
  RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
</IfModule>

```

When you do that, Apache will redirect everything to https://www.example.com. Over time, Google will fix its indexes because of the 301 redirect, or you can try to submit manual delists.

---
Tags: caching
---


# Question
Title: How can I get Elysia Cron to run every 15 minutes?
I'm running drupal 7 on a shared host with cpanel and apache. I don't want to use regular cron because i want to run some tasks more regularly than others such as the search index. So i added Elysia Cron module. It doesn't run at the regular intervals I intend though. I'm hoping you all can give me some guidance. Here's how I set it up:

I added a cron job in my cpanel like so:

http://mysite/sites/all/modules/elysia\_cron/cron.php?cron\_key=key and set the frequency to \*****.

Then in Drupal I went to admin \> configure \> elysia cron and did the following:

Set search to run every 15 minutes and everything else either every hour or every day.

I also set the installation settings so that 'never/use external crontab' is selected for 'run cron on visitor's requests, every'.

But when I save these settings...cron doesn't run every 15 minutes for the search index as planned.

Any idea what else I might need to change?

# Answer
Given the explanation in your question about how you've set things up, at least one reason your external cron does not ping Elysia Cron is that you've got the key wrong, or that the key is missing.

You need to up look the right key. Navigate to *Elysia » Settings » Installation Settings » Cron key* and copy the key has *you find there* so that your Cpanel setup to looks like this:

```
http://example.com/sites/all/modules/elysia_cron/cron.php?cron_key=ZvMtg5HAaRzjz5NtkwoDs0F3jOWrbpIX5JVi3ACJl7Q

```

**Note:** Use the actual key you find on your site - not the dummy key I use as an example.
> 3 votes

# Answer
As described also in Configuring cron jobs using the cron command, what the Cron daemon wants is a command to execute. You cannot simply put the cron URL for the Drupal site.

If Wget is installed, you can use `/usr/bin/wget -O - -q -t 1 http://CRON_URL > /dev/null 2>&1`. If cURL is installed, the equivalent of that command is `/usr/bin/curl --silent --compressed http://CRON_URL > /dev/null 2>&1`. Replace */usr/bin/* with the directory containing the executable, and *CRON\_URL* with the right cron URL, which for the *Elysia Cron* module includes *sites/all/modules/elysia\_cron/cron.php*.

Keep also in mind that the *Elysia Cron* module, like Drupal Cron, requires *CRON\_URL* includes the cron key given in its administration form.
> 0 votes

---
Tags: 7, cron
---


# Question
Title: How to add a "?destination=URL" to the node links
I am trying to override node links by using `hook_node_view_alter()`, so my code looks like:

```
$cancel_link = 'admin/some_path/'.$found_id.'cancel';

$build['links']['node']['#links']['cancel'] = array(
        'title' => t('Cancel'),
        'href' => $cancel_link,
        'html' => TRUE,
        'attributes' => array(
          'title' => 'Cancel',
        ),
      );

```

and it works fine. But I also need to add "?destination=URL" to links and unfortunately, trying several different approaches didn't work for me. In particular:

I copied the whole Good Example code from https://www.drupal.org/docs/7/theming/overriding-themable-output/how-to-add-a-destinationurl-to-the-request-new-password and replaced my code with:

```
$build['links']['node']['#links']['cancel'] = l(t('Request new password'), 'user/password', array('query' => array('destination' => 'homepage', 'foo' => 'bar'), 'attributes' => array('title' => t('Request new password via e-mail.'))));

```

but the link didn't show up at all.

Example on https://www.zyxware.com/articles/5195/how-to-set-destination-as-the-link-value-in-the-l-in-case-of-urls-with-parameters didn't work.

Tried to adapt the accepted answer on use URL with query as URL destination as:

```
  $query_string = array('destination' => 'service/922');
  $url = url($cancel_link, array('query' => $query_string));
  $build['links']['node']['#links']['cancel'] = array(
    'title' => t('Cancel'),
    'href' => $url,
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Cancel',
    ),
  );

```

unfortunately, it is also giving `%3Fdestination%3Dservice/922` in the browser address bar. What I am doing wrong here?

Addition: Using dpm() I've figured out the above examples all output ready to use links like `<a href="/user/password?destination=homepage&foo=bar" title="Request new password via e-mail.">Request new password</a>`

However, if I dpm the link in my function it still gives raw array:

```
(Array, 4 elements)
title (String, 6 characters ) Cancel
href (String, 33 characters ) admin/some_path/id/cancel
html (Boolean) TRUE
attributes (Array, 1 element)
title (String, 6 characters ) Cancel

```

And I wonder is it possible to add destination at this stage at all or do I have to intercept the link at a later steps like for example while themeing?

# Answer
> 0 votes
You are doing it correctly but the `theme_links()` function is called after you create the link. That function calls the `l()` function, which in turn calls the `url()` function, which in turn calls `drupal_encode_path()`, and it's here your Url is getting encoded.

If you override the `theme_links()` function, you can undo the encoding. Copy the `theme_links()` function from `theme.inc` into the `template.php` of your theme. The function should be named `mytheme_links()` or, if you want it to apply only to nodes, you can name it `mytheme_links__node()`. The original `theme_links()` function has this:

```
if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

```

You can replace it with this to undo the encoding:

```
if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}

```

This is just a basic explanation. There are good reasons for encoding links, so you might want to restrict the links you decode.

---
Tags: 7, navigation
---


title: Change views exposed filter format

text:
# Question
Title: Change views exposed filter format
I am build a JSON export using a View in Drupal 8. Problem is that the parameters for retrieving the json doesn't seem to work as I would want.

In my View I need use two exposed filter criteria to select a date range. Both fields are Date and Time fields. When clicking on one of the criteria I have created it says:

> **Value type**
>
> A date in any machine readable format. CCYY-MM-DD HH:MM:SS is preferred.

I would like this url with this parameter values to work: `http://example.com/api/?start=20161101&end=20161102`

I thought it was working at first, but apparently not when I get my results.

This works:

```
http://example.com/api/?start=2016-12-08%2000%3A00%3A00&end=2016-12-21%2024%3A00%3A00

```

I am trying to have those clean parameters instead. How can I change the filter format to use the `YYYYMMDD` format? I don't want to change my field type because it is storing the time for my events. I want to get the data through only dates.

# Answer
> 1 votes
You need to: \- Set the filter granularity to "Day" \- Add a date format "Ymd" admin/config/regional/date-time/formats \- Add a date type to attach that to...admin/config/regional/date-time \- OR, just change whatever date type the view is using to use it

---
Tags: views, 8
---


# Question
Title: Move a taxonomy page field to a different region
I currently have taxonomy pages using a custom image field, **field\_icon**, which by default displays in my content region.

How would I go about moving this field display to a different region (in my case the **header** region)?

# Answer
> 0 votes
You can approach this in UI, Twig or PHP:

**UI**

You can create a View (show Taxonomy Terms) with display "block" and add "Term ID" as Context Filter, see this example for Users: How to move the user account/Profile 2 information from the content region to a sidebar region

**Twig**

Install Twig Tweak and place the field in a twig template:

```
{{ drupal_field('field_name', 'taxonomy_term') }}

```

**PHP**

Prepare the taxonomy term entity in a preprocess hook, see print custom image field for taxonomy page (page--taxonomy.html.twig) template

---
Tags: theming
---


title: How to remove Site Name from page title

text:
# Question
Title: How to remove Site Name from page title
I'm using Omega 7.3x to theme my site, and at current, all the page headers are

\[Page Title\] | \[Site Name\]

but I'm trying to bring back google analytics reports into the site so the admin can see a list of the most active pages etc, except all the reports have the same pattern, it makes reading the report more difficult

eg, the report looks like

* My Account | My Website
* Fixtures | My Website
* Events | My Website
* Contact | My Website

I want to either remove the Site name from the page title, or just so that Google Analytics doesn't pick it up, I assume the latter is better to do in terms of SEO etc, how do I do that?

# Answer
> 0 votes
Use https://www.drupal.org/project/metatag module to modify page titles (among other things) per content or content type.

To modify what google analytics displays as title is beyond the scope of this forums

---
Tags: 7, theming, google-analytics
---


# Question
Title: What settings are there for sending an email to the users who create accounts?
How can I send an email to users after registration, confirming they have been registered?

From user/register, when users enter the required data (name, username, email) as administrator I receive the account information, but the users don't get any message.

# Answer
In **configuration \> people \> account settings** or going to `config/people/accounts` you can set who gets what and even modify the text

## Register without admin approval

Check this setting

```
Who can register accounts? : visitors

```

and the user that registers will receive `Welcome (no approval required)` email which will include a one time link to complete registration. Upon clicking on the link and following the instructions he is a registered user.

## Register with admin approval

check the following setting

```
Who can register accounts? : Visitors, but administrator approval is required

```

The user will get `Admin (user awaiting approval)` email upon registering and if enabled on `Account activation` the setting `Notify user when account is activated` is enabled the user will get a 2nd email upon admin approval.
> 0 votes

---
Tags: users
---


# Question
Title: How can I inject a different service in an existing one, i.e. exchange one already injected service by an own one?
The basic authentication provider service uses the user.auth service:

```
basic_auth.authentication.basic_auth:
    class: Drupal\basic_auth\Authentication\Provider\BasicAuth
    arguments: ['@config.factory', '@user.auth', '@flood', '@entity.manager']
    tags:
      - { name: authentication_provider, provider_id: 'basic_auth', priority: 100 }

```

I wrote an own service my-user.auth (extending UserAuthInterface) and want my service to be injected into the basic authentication provider instead of the user.auth. How can I do this?

# Answer
> 4 votes
Create a ServiceProvider in your module. And then replace the argument using `Definition::replaceArguments` like so:

```
<?php

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the language manager service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('basic_auth.authentication.basic_auth');
    $definition->replaceArgument(1, 'NEW_SERVICE');
  }
}

```

Please note:

> Note that if you want this service alteration to be recognized automatically, the name of this class is required to be a CamelCase version of your module's machine name followed by ServiceProvider, it is required to be in your module's top-level namespace Drupal\your\_module\_name, and it must implement \Drupal\Core\DependencyInjection\ServiceModifierInterface (which ServiceProviderBase does).

Relevant article: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

---
Tags: 8, dependency-injection, symfony-services
---


# Question
Title: Views Dependent Filter showing when no controller value selected
I'm using Views Dependent Filters to have a filter show based on the value of a filter above it. It is working for the most part but it is showing the field by default (when no controller value is selected.)

When my multiple select filter being used as the controller, the dependent field shows even when no value is selected. For example:

Vehicle:

* Car (Set as controller)
* Boat
* Plane

Tire Size (Dependent Filter)

* Small
* Med
* Large

Tire size shows when "car" is selected but also shows when no value is selected. I believe this the module is not intended to function this way.

Is there a solution to this or a possible alternative?

# Answer
> 0 votes
This was a bug relating the default views multiple select filter. I used the Better Exposed Filters checkboxes and now the dependent filter works as intended.

---
Tags: 7, views
---


# Question
Title: How to create a Class that I can reuse in multiple modules?
I would like to create a class that has a set of methods that I want to reuse across the site in either mytheme.theme or secondmodule.module files.

How would I create this class and class methods so that they can be used in multiple areas? Would I have to create a custom module for this?

Here is what I was trying so far, but need assistance on next step.

```
<?php
namespace Drupal\CustomClass;

class MyClass {
  public static function processEntity($var1, $var2) {
    /* process the parameters */
    return value;
  }
}

```

If I wanted to use this in a mytheme.theme file I was thinking to do this

```
<?php

use Drupal\CustomClass\MyClass;

function _some_function() {
  /* processing logic here which results in $var1, $var2 */
  $results = MyClass::processEntity($var1, $var2);
}

```

# Answer
> 8 votes
Your use case is where Drupal 8 services come into play. When you'd like to create classes/methods that can be used across Drupal by other modules and your theme, create a custom module that provides this class as a service. You can then get an instance of this service class by either using the static service getter `\Drupal::service()` within `*.module` or `*.theme` files, or dependency injection in other classes/services.

# Answer
> 3 votes
Making a service of a class that only contains static methods wouldn't make any sense because it is not intended to be used as an instance.

To answer your question; Yes you need to put your class in a module. And then you would have to namespace it properly and put a line similar to the following one at the beginning of the file.

```
namespace Drupal\your_module;

```

The class would then be placed in the module's *src* folder of your module.

You would use that class by adding the following line on the top of the .theme file.

```
use Drupal\your_module\MyClass;

```

I would also recommend to explicitly add an dependency on the other modules that would use that module's class. Starting with Drupal 8.9, theme's can now declare modules as dependencies.

---
Tags: 8, hooks
---


title: How to install drush 8 properly?

text:
# Question
Title: How to install drush 8 properly?
I'm trying to install drush 8 via composer:

composer global require drush/drush:dev-master (source)

but it gives me drush version 7.0.0 which is without D8 integration... I'm using Linux Mint 17.

# Answer
> 3 votes
`composer require drush/drush:dev-master` gave me Drush 8 three days ago when I ran this tutorial to setup different versions of Drush on my system http://www.jpstacey.info/blog/2014-04-07/switching-between-drush-major-versions

Multiple versions of Drush can be useful if a site is no longer in development and for example custom drush commands were created for a specific version of Drush.

# Answer
> 6 votes
For Ubuntu

```
export PATH="$HOME/.composer/vendor/bin:$PATH"
source $HOME/.bashrc
composer global require drush/drush:8.x

```

# Answer
> 1 votes
I also find that `composer require drush/drush:dev-master` (n.b. deliberate removal of `global` option), ran in a directory without a composer.json file did in fact pull down the 'master' branch of Drush, which is Drush 8, just as the documentation says. As an experiment, you might want to try running the same command (without `global`) in an empty directory, and see if you get the right version of Drush in that instance.

If that is working for you, then perhaps you have an older version of Drush in your global vendor directory ($HOME/.composer/vendor/drush/drush). It is possible that Composer might become confused by this, as 'dev-master' did at one time refer to the 7.x branch. I did not attempt to reproduce this situation, and tend to think that in most cases you should still get the 'master' branch. However, if you are having trouble, you might try `composer global remove drush/drush`, and then re-install as you did before, and see if this fixes the problem. You might also try `composer self-update`, in case you have an old composer.

---
Tags: drush
---


# Question
Title: How can I print article author profile picture?
I have a blog where basic author information needs to be printed out.

Basically, I want to print author name and profile picture in my article teaser template.

I tried googling but none of the answers seemed to help.

Can I somehow access Author object?

# Answer
> 4 votes
Put this on top of your `node.html.twig` or similar template

```
{%
  set author_pic = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.uid.entity.user_picture.entity.uri.value,
    '#attributes': { class: 'authorImg' },
  }
%}

```

Use this anywhere in the same template you want to output the author image

```
{{ author_pic }}

```

---
Tags: theming, users
---


# Question
Title: How do I add an external JavaScript file using a custom module?
I am trying to add an external JavaScript file to my site using `hook_preprocess_page()`.

In Drupal 7, I used `drupal_add_js()`.

```
function mymodule_preprocess_page(&$vars) {
  $uuid = trim(variable_get('variable_id', ''));
  drupal_add_js('//cdn.cookielaw.org/consent/'.$uuid.'.js', array(
    'type' => 'external',
    'scope' => 'header',
    'group' => JS_THEME,
    'every_page' => TRUE,
    'weight' => -1,
  ));
}

```

What function/method should I use in Drupal 8?

# Answer
> 2 votes
Firstly drupal\_add\_js() removed in Drupal 8, check here.

So create library in your module folder as MODULE\_NAME.libraries.yml and in this file if you want to add external js add code like below.

```
external:
  version: 1.0
  header: true
  js:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js: {type: external, minified: true}

```

and in any of your module/Form/Controller you can call above library using **"#attached"**

```
  $build['#attached']['library'][] = 'MODULE_NAME/external';

```

---
Tags: javascript
---


# Question
Title: Get a list of available migration destination plugins
how can I get all available migration destination plugins? A way to ask with drupal console?

like listed on Migrate destination plugin examples

# Answer
* With **Drupal Console**:

```
$ drupal debug:plugin migrate.destination

```

Or short:

```
$ drupal dpl migrate.destination

```

gives:

```
------------------------------------------ ---------------------------------------------------------------------------------------
  Plugin ID                                  Plugin class
 ------------------------------------------ ---------------------------------------------------------------------------------------
  component_entity_display                   Drupal\migrate\Plugin\migrate\destination\PerComponentEntityDisplay
  component_entity_form_display              Drupal\migrate\Plugin\migrate\destination\PerComponentEntityFormDisplay
  config                                     Drupal\migrate\Plugin\migrate\destination\Config
  d7_theme_settings                          Drupal\system\Plugin\migrate\destination\d7\ThemeSettings
  entity:action                              Drupal\migrate\Plugin\migrate\destination\EntityConfigBase
  entity:base_field_override                 Drupal\migrate\Plugin\migrate\destination\EntityBaseFieldOverride
  entity:block                               Drupal\block\Plugin\migrate\destination\EntityBlock
  entity:block_content                       Drupal\migrate\Plugin\migrate\destination\EntityContentBase
  entity:block_content_type                  Drupal\migrate\Plugin\migrate\destination\EntityConfigBase
  entity:comment                             Drupal\comment\Plugin\migrate\destination\EntityComment
  ...

```
* With **drush**:

```
$ drush php
>>> array_keys(\Drupal::service('plugin.manager.migrate.destination')->getDefinitions());

```

gives:

```
=> [
 "entity:block",
 "entity:comment",
 "entity:comment_type",
 "d7_field_group",
 "field_group_entity_form_display",
 "field_group_entity_view_display",
 "entity:file",
 ...
]

```
> 8 votes

---
Tags: 8, migrations, console
---