# Question
Title: Workaround for: Message rejected due to DMARC policy for yahoo.com
Using Drupal 7 on CentOS 6 with stock Postfix 2.6.6 and since recently any mails sent by Drupal on behalf of users with `@yahoo.com` mail addresses are bounced hard:

```
Diagnostic-Code: smtp; 550 5.7.1 Message rejected due to DMARC policy for
    yahoo.com

```

And also:

```
Message not accepted for policy reasons.  See
    http://postmaster.yahoo.com/errors/postmaster-28.html (in reply to end of
    DATA command)

```

I think this is result of Yahoo changing its mail policy, so that all other big mail providers participating in DMARC (like Gmail or Mail.ru or ...) only accept `@yahoo.com` senders from Yahoo mail servers (and thus not from my little Drupal website).

Has anyone affected by this change found a good workaround on the Drupal site for this problem?

**UPDATE:**

My Postfix installation works well and is not the problem.

The problem with Yahoo users should be solved in Drupal hook for sending contact and registration mails. I think (from reading Yahoo docs) the "From" header there should be replaced by "Reply-To" or something similar.

**Note**: My question affects Drupal and has to be solved with Drupal means (which is why IMO it belongs in this SE-site).

# Answer
> 5 votes
You are correct in your update that:

1. This is a Drupal problem, in that the script must change how it sends emails.
2. What Drupal uses in the "from" field should actually be in the "reply-to" field.
3. This can be fixed using a hook. (Specifically, hook\_mail\_alter().)

If you don't want to write any code, I suggest you use the Contact Reply To module by rfay.

Alternatively, I wrote a more general-use module that I described here.

I use my solution on all of my sites and have not had any trouble yet.

Some of the other suggestions are incorrect, in that hook\_mail() does not catch every email, and therefore is not appropriate, and you cannot use some of the other smtp solutions, because the "from" email address is not consistent (ie., it is provided by site visitors).

# Answer
> 0 votes
You should never send email on behalf of an @yahoo.com email address. Yahoo has made this crystal clear.

You should always send from a domain you have permission to send from.

To send mail on behalf of an @yahoo.com email address you will need to use your own domain in the "from" field, and use the @yahoo address in the 'reply-to' field.

In my experience, attempting to send from an @yahoo.com email address without having your message originate from an @yahoo.com mail server will ensure your message will be blocked.

# Answer
> 0 votes
This doesn't work with Yahoo emails, but for all other emails one solution on Drupal 7 is to go to: admin/config/content/webform

And tick:

Use Reply-To header Sends all e-mail from the domain of the default address above and sets the "Reply-To" header to the actual sender. Helps prevent e-mail from being flagged as spam.

---
Tags: 7, emails, advertising
---


# Question
Title: After any AJAX form event, all Entity Reference Fields are blank
After any AJAX event in the form (Upload image, add a new field collection row etc.) All Entity Reference fields go blank.

I have multiple entity reference fields, all using a view to get list options.

The issue is occurring on the node edit form.

On first page load, all entity form values are there, and you can edit and save them with no problems. However, If you edit any field that uses AJAX to update, then after ajax has run, all of the entity reference fields lose their options and only show "None" as the single option.

Can anyone think why this would be happening, and what steps I can take to either provide more info, or find a fix?

After using an AJAX field, and then trying to save the form, I get this error in watchdog,

```
TYPE    form
DATE    Tuesday, 21 June, 2016 - 08:47
USER    collins
LOCATION    http://couplespage.com/node/23/edit
REFERRER    http://couplespage.com/node/23/edit
MESSAGE Illegal choice 7 in Venue element.
SEVERITY    error

```

This obviously happens because the select lists are all empty, and illegal choices are detected.

http://tinypic.com/r/2pod2dy/9

**Update:** On further inspection, using dsm($form) to print krumo and check the results, after ajax, it takes over a minute to complete the page, but all of the values are still there in the array, just not in the actual select list. They are also still there in the page source. Something is making them not show. I will look into someway to rebuild the form after ajax, but Im grabbing at straws here. Any help really appreciated.

**Update 2:** On even further inspection. Values are only lost when it is a view Entity Reference display that is being used to populate the values. When reverting to a simple filter by bundle list, they show after ajax. Something is causing the view to lose its results after ajax.

# Answer
> 0 votes
**I finally solved this.**

There is a patch here... https://www.drupal.org/files/issues/entityreference-use-tokens-2010898-126.patch That allows you to use tokens in the Entity Reference Fields "Pass argument to view" field.

The problem was that after AJAX, the view I was using for the Entity Reference was losing its contextual filter argument. This patch, and the use of the token fixes the problem nicely.

---
Tags: 7, entities, ajax
---


# Question
Title: How can I get all related entities of a node programmatically?
I am writing some drush scripts and find myself needing to get related entities (nodes) of the current node. However I can only find info for constructing views that do this.

Can anyone tell me is there a programmatic way to pull all entities that relate to the current nid with a filter on the entity type?

Ultimately I need to get a list of node ids that relate to the current node id.

The relationship depend on the relation module.

# Answer
> 0 votes
Like this, you will get all the referenced items of the node being displayed.

```
  $current_path = explode('/', $_GET['q']);
  if ($current_path[0] == 'node' && is_numeric($nid = $current_path[1])) {
    $field = 'my_field';
    $bundle = 'my_bundle';
    $query = db_query("SELECT {$field}_target_id FROM field_data_{$field} WHERE entity_id = :nid AND bundle = :bundle",
      array(
        ':nid' => $nid,
        ':bundle' => $bundle,
      )
    );
    foreach($query as $row) {
      $target_ids[] = $row->{$field . "_target_id"};
    }
    $nodes = node_load_multiple($target_ids);
  }

```

If you have more entity reference fields, you have to expand the query (with more joins) according to your fields.

---
Tags: 7, entities
---


title: Invalidate block cache programmatically

text:
# Question
Title: Invalidate block cache programmatically
I have a block that is cached per page. However, I need a way to invalidate it's cache in code per page or node. (Or, if no way, all cache per block id).

# Answer
> 4 votes
The `SystemMenuBlock` of core is invalidated when its menu changes because this method:

```
public function getCacheTags() {
  // Even when the menu block renders to the empty string for a user, we want
  // the cache tag for this menu to be set: whenever the menu is changed, this
  // menu block must also be re-rendered for that user, because maybe a menu
  // link that is accessible for that user has been added.
  $cache_tags = parent::getCacheTags();
  $cache_tags[] = 'config:system.menu.' . $this->getDerivativeId();
  return $cache_tags;
}

```

I think you can solve your problem in the same way.

---
Tags: 8, caching
---


# Question
Title: Different prices in Shopping cart form and Shopping cart summary views in Commerce price table
I have a problem with price table module that I hope you can support me on this issue. As I have some products with different prices depending on item's quantity according to the commerce price table module, everything is ok except "Shopping cart summary view" that only show base price and don't show calculated prices according to quantities. Also I have found rule "Override price with price table" in admin\>configuration\>rules that it seems it doesn't any effect on "Shopping cart summary view" !! . If possible pls help me on this topic and thanks in advanced for your perfect module.

---

For ease of reference, pls find attached file that show the price difference in "Shopping cart form" with "Shopping cart summary".

# Answer
In the shopping cart summary view, are you using the `(Line items referenced by commerce_line_items) Commerce Line item: Unit price (Price)` field or `(Products referenced by commerce_product) Commerce Product: Price (Price)` field to output the unit price?

You should be using `Commerce Line item: Unit price`, this one is overridden by the `Override price with price table` rule
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Render database values using 'markup tags' other than 'table tags'
to keep things simple, I am trying to load a specific set of values from a database, which using the following code works:

```
foreach ( database::load() as $bdt) {
  $row[] = (array) $bdt;
}

$content['table'] = array(
  '#type' => 'table',
  '#rows' => $row,
  '#empty' => t('No entries available.'),
);

```

Which produces the following:

```
<table>
  <tbody>
          <tr>
                  <td>5.00 PM</td>
              </tr>
          <tr>
                  <td>1:00 PM</td>
              </tr>
          <tr>
                  <td>1:00 PM</td>
              </tr>
          <tr>
                  <td>3:00 PM</td>
              </tr>
          <tr>
                  <td>3:00 PM</td>
              </tr>
          <tr>
                  <td>5:00 PM</td>
              </tr>
      </tbody>
</table>

```

But I don't want to use table formats and I want to use other html markup tags, such as `"<p>" or "<div>"`. I have tried to change the '#type' =\> 'table' to '#markup' but it will not render anything.

```
$content['table'] = array('#markup => '<p><span class="blue">time</span> ' . $row '</p>',);

```

I have searched a few sites about it, but all point information back to using table format.

The working code was extracted from the "example modules" using the DBTNG example.

Please can anyone tell me how to go about it?

Many Thanks

# Answer
> 1 votes
As you do not like table.html.twig, I suggest to write your own table theme. As a reference, you can look how this is done for `field_ui_table` in core.

Or you use inline\_template:

```
$content['table'] = [
   '#type' => 'inline_template',
   '#template' => '{%- for row_value in row -%}<p><span class="blue"> time </span>{{ row_value }}</p>{%- endfor -%}',
   '#context' => ['row' => $row],
 ];

```

---
Tags: 8, database
---


title: Filters dropdown based on a parameter

text:
# Question
Title: Filters dropdown based on a parameter
I have a taxonomy, say '**Unit**'. Besides the name of the Unit, there is a field called '**SubUnit**'. All users in my Drupal site have assigned a Unit.

On the node add forms (and on the Views, for filtering), I would like to get only the '**SubUnits**' corresponding to the assigned Unit per user. That is, only visualize on the dropdown list 'his' units.

I have seen around this answer, but it's from 2011, maybe there is an updated and easier way to do it? there is no way to create a filter based on the results of a view? (i can pass Únit as contextual filter and get its subunits)

# Answer
Try the Hierarchical Select module. This module integrates with Taxonomy.

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
>
> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 0 votes

---
Tags: 7, views
---


# Question
Title: How do Organic groups and virtual sites relate to each other?
I just want to know that a site which is built in Openscholar, a LMS for Drupal.

Therefore, how organic group is tied up with virtual sites? Also I want to know the the Views module's role in such circumstances.

# Answer
> 1 votes
I am not sure about openscholar but what organic modules can do about virtual sites-

* With help of organic group you can declare an entity as a "group" or call it context, an example could be a sports site with group as "cricket"
* With help of og you have permission granularity in context to group, so a user can have access to all post which comes under a "group" in our example "cricket" being totally unaware of other groups, can say "hockey"
* With in group you can have group specific roles, a user who can admin cricket group but still can not do anything on hockey group.

So each group can be seen as fully functional site in itself - virtual site

**Note: Domains have nothing to do with og, it's just a matter of context switching**

# Answer
> 1 votes
As a variation of what's explained in the prior answer, you could also use the Group module for this (instead of the Organic groups module). Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. So each group can be seen as fully functional site in itself, i.e. a virtual site.

It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. So since Group is entirely entity based, it has out-of-the-box integrations (= no extra modules needed) with other great modules such as Rules, the Views, etc.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources

---
Tags: organic-groups
---


title: Change default favicon programmatically

text:
# Question
Title: Change default favicon programmatically
I know I can load a favicon though the user interface, but is there a way of setting the default favicon for your theme, so that when someone enables the theme, the default icon is immediately used?

# Answer
You can place the `favicon.ico` in your theme folder (at the same level as your\_theme.info) and it will be used automatically.

Works for Drupal 6, 7 & 8.

Note: The favicon is *heavily* cached by some browsers, you may need to go to extra lengths to see the new one.
> 14 votes

# Answer
In Drupal 8, you can use the `settings.yml` file, located at `themes/YOURTHEME/config/install/YOURTHEME.settings.yml`

Here is an example for theme logo/favicon customization:

```
logo:
  use_default: false
  path: 'themes/YOURTHEME/logo.png'
favicon:
  use_default: false
  path: 'themes/YOURTHEME/favicon.png'

```

However, if you change these settings whereas your theme is already installed in Drupal administration, you will need to uninstall your theme and then reinstall it. Else, even if you clear all caches, Drupal will not take in consideration your changes.
> 9 votes

# Answer
```
<?php
function hook_page_alter(&$pages) {
  $favicon = "http://example.com/sites/default/files/favicon.ico";
  $type = theme_get_setting('favicon_mimetype');
  drupal_add_html_head_link(array('rel' => 'shortcut icon', 'href' => drupal_strip_dangerous_protocols($favicon), 'type' => $type));
}
?>

```
> 5 votes

# Answer
## Method 1 - via template.php

```
/**
 * Implements hook_html_head_alter().
 */
function MYTHEME_html_head_alter(&$head_elements) {

  // Remove existing favicon location
  global $base_url;
  $default_favicon_element = 'drupal_add_html_head_link:shortcut icon:' . $base_url . '/misc/favicon.ico';
  unset($head_elements[$default_favicon_element]);

  // Specify new favicon location
  $element = array(
    'rel' => 'shortcut icon',
    'href' => '/path-to-favicon/favicon.ico',
  );
  drupal_add_html_head_link($element);
}

```

## Method 2 - via custom module

```
/**
 * Implements hook_html_head_alter().
 */
  // Remove existing favicon location
 function MODULENAME_html_head_alter(&$head_elements) {
   global $base_url;
   $default_favicon_element = 'drupal_add_html_head_link:shortcut icon:' . $base_url . '/misc/favicon.ico';
   unset($head_elements[$default_favicon_element]);

  // Specify new favicon location
  $element = array(
    'rel' => 'shortcut icon',
    'href' => '/path-to-favicon/favicon.ico',
  );
  drupal_add_html_head_link($element);
 }

```

See hook\_html\_head\_alter for more info.

Note: It's not required to list the new favicon location in `hook_html_head_alter()`. I usually specify it in `THEMENAME_preprocess_html()` or `MODULENAME_init()`.
> 5 votes

# Answer
The following code (in a custom module) replaces the favicon, instead of adding an additional one.

```
/**
 * Implements hook_html_head_alter().
 *
 * Replaces the favicon.
 *
 * @param array $head_elements
 */
function MYMODULE_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if (1
      // The array key can vary, depending on the original favicon setting.
      && 0 === strpos($key, 'drupal_add_html_head_link:shortcut icon:')
      && !empty($element['#attributes']['href'])
      && 'shortcut icon' === $element['#attributes']['rel']
    ) {
      // Make sure to use a file that actually exists!
      $favicon_path = drupal_get_path('module', 'MYMODULE') . '/img/favicon_32.png';
      $favicon_url = file_create_url($favicon_path);
      // If the favicon path came from a user-provided setting, we would also need drupal_strip_dangerous_protocols().
      $element['#attributes']['href'] = $favicon_url;
      $element['#attributes']['type'] = 'image/png';
      $head_elements[$key] = $element;
    }
  }
}

```

For the favicon file location I would suggest either the module folder of MYMODULE, or sites/default/favicon.ico. The goal is to have the file in version control, and NOT in the public files folder. We don't want it to be web-writable.

I assume most people will use \*.ico instead of \*.png, in this case the 'type' can keep its original value.
> 2 votes

# Answer
In Drupal 8 you must set favicon to true in YOUR\_THEME.settings.yml (located at themes/YOUR\_THEME/config/install) and put your favicon file at your theme root directory with the name "favicon.ico"

```
features:
   favicon:true

```
> 0 votes

---
Tags: files
---


# Question
Title: How to switch 'standard' installation profile to 'minimal' in existing site?
I have built a druapl 8 site with 'Standard' installation profile.

How can I switch 'standard' installation profile to 'minimal' in existing site?

# Answer
Installation profiles contain code to set up a site during installation, that's all they do. They aren't useful to an installed site.

Trying to change the profile *after* installation could never conceptually do anything. The installation code has already run, and the purpose of the profile has been served at that point.
> 6 votes

# Answer
There is no way to switch you have two solution,

* install again
* remove standard modules.

lists the modules enabled by the Standard profile, as compared to the Minimal profile
> 4 votes

---
Tags: 8, installation-profiles
---


# Question
Title: Passing Information to Drupal Referenced Entities before Render
I have a content type called `basic_page`. This content type has a field called `field_elements` which is an entity reference field. The display settings for this field is set to 'Render Entity' - in other words, when a `basic_page` node is being rendered, it will also render the referenced entity. All good - no problem.

My question is, I would like to pass run-time information (based on `basic_page` node) to the referenced entity that should be used in `mytheme_preprocess_node` when the referenced entity is being 'pre-processed\`.

The problem is, by the time `hook_preprocess_node` is called for the referenced entity - I have no information of the `basic_page` node that 'contains' the referenced entity.

I was hoping that in `hook_preprocess_field` I could check if it is `field_element` and then set some value in the &$variables param I am getting in `hook_preprocess_field` that will persist to exist up to the point where `hook_preprocess_node` is called?

# Answer
This works as designed. The referenced node can have multiple parents, but is only processed once and then cached.

A slighly different approach would be to use the context to check inside the referenced node, which parent node is displayed as page content.

Load the basic node with a route match in preprocess of the referenced node. See this question from today on blocks, which can be used in the node preprocess hook in the same way:

How to access field values from a custom block

You would also have to adjust the cache settings of the referenced node, see the comment in the linked answer.
> 1 votes

---
Tags: 8, theming, entities
---


# Question
Title: How to place the language switch in the main menu bar?
The language switch appears on the bottom of the page.

How can I move it to the main menu?

# Answer
Check your **page.tpl file** and check where it is, OR, you can check the **list of blocks in your site** to see where it is placed and move it to your desire position
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Is there an easy way to define a "global" if isset condition on node.tpl.php?
I'm using some custom node.tpl.php files with lots of custom fields. For each field I have to write down `<?php if (isset($content['field_myfield'])):?> SOMETHING <?php endif; ?>`

*(It gives error if that field is not set without using if isset condition.)*

Is there anyway to define a 'global' `if (isset...):` instead of adding if condition to each field separately?

# Answer
No. Consider the case where one field is not set. Either the global if fails and nothing is printed or you are right back to those errors. This is one of the shortcomings of coding in the theme layer.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Images sent via AJAX, saved to database but not shown on the node
I've got this weird problem. I've been developing this phonegap app and it's in the testing phase now, and this is where the nightmare begins. I am able to successfully upload images encoded as base64 strings, retrieve their fid and save them to database. Please see the below screenshot. However, it's like the fid is not associated with the nid. EDIT: I've just looked again, and there is no trace of the fid in question in field\_data\_field\_name. UPDATE: The weird thing is, I have two image fields of which one works fine. EDIT: I and another fellow have the replicate of this website, and this works on the other server just fine.

UPDATE: My code:

```
  $.ajax({
    url:'http://www.rejicast.com/services/file.json',
    type:'post',
    dataType:'json',
    data:fileData,
    success:function(res) {
      var fid = '';
      $.each(fids, function(k,v) {
        fid += '&node[field_fotograflar][und]['+k+'][fid]='+v;
      });
      var cat = '';
      $('#oyuncuKategori input:checked').each(function(k,v) {
        cat += '&node[field_kategorisi][und]['+k+']='+$(this).attr('id');
      });
      $.ajax({
        url:'http://www.rejicast.com/services/node.json',
        type:'post',
        dataType:'json',
        data:'node[type]=oyuncu&node[field_oyuncu_fotografi][und][0][fid]='+res.fid+'&node[field_oyuncu_fotografi][und][0][cropbox_x]=0&node[field_oyuncu_fotografi][und][0][cropbox_y]=0&node[field_oyuncu_fotografi][und][0][cropbox_height]=800&node[field_oyuncu_fotografi][und][0][cropbox_width]=600&node[title]='+encodeURIComponent($("#name").val())+'&node[language]=und&node[field_tc_kimlik_no][und][0][value]='+encodeURIComponent($("#tckn").val())+'&node[field_sgk_durumu][und][value]='+encodeURIComponent($("#sgk option:selected").val())+'&node[field_telefon][und][0][value]='+encodeURIComponent($("#tel").val())+'&node[field_telefon_2][und][0][value]='+encodeURIComponent($("#tel2").val())+'&node[field_adres][und][0][value]='+encodeURIComponent($("#address").val())+'&node[field_yasadigi_sehir][und][value]='+encodeURIComponent($("#city option:selected").val())+'&node[field_e_posta][und][0][value]='+encodeURIComponent($("#email").val())+'&node[field_cinsiyet][und][value]='+encodeURIComponent($("#gender option:selected").val())+cat+'&node[field_gogus][und][value]='+$("#chest option:selected").val()+'&node[field_bel][und][value]='+$("#waist option:selected").val()+'&node[field_kalca][und][value]='+$("#thigh option:selected").val()+'&node[field_dogum_tarihi][und][0][value][date]='+finalDate+'&node[field_boy][und][value]='+encodeURIComponent($("#height option:checked").val())+'&node[field_kilo][und][value]='+encodeURIComponent($("#weight option:selected").val())+'&node[field_goz_rengi][und][value]='+encodeURIComponent($("#eyecolour option:selected").val())+'&node[field_ten_rengi][und][value]='+encodeURIComponent($("#skincolour option:selected").val())+'&node[field_ayak_no][und][value]='+encodeURIComponent($("#shoesize option:selected").val())+'&node[field_egitim_duzeyi][und][value]='+encodeURIComponent($("#education option:selected").val())+'&node[field_oyunculuk_egitimleri][und][0][value]='+encodeURIComponent($("#training").val())+'&node[field_diller][und][0][value]='+encodeURIComponent($("#languages").val())+'&node[field_beceriler][und][0][value]='+encodeURIComponent($("#skills").val())+'&node[field_kisisel][und][0][value]='+encodeURIComponent($("#personal").val())+fid+'&node[field_videolar][und][0][video_url]='+encodeURIComponent($(".videolink").val())+'&node[field_videolar][und][0][description]='+encodeURIComponent($(".videodesc").val())+'&node[field_okudum_anladim][und][value]='+encodeURIComponent($(".privacy").is(':selected')?1:0),
        success:function(data) {
          ActivityIndicator.hide();
          navigator.notification.alert("Kaydınız başarıyla yapıldı", function() {return;}, "Face in Cast", "Tamam");
          window.location.href = "received.html";
        },
        error:function(xhr,status,message) {
          ActivityIndicator.hide();

navigator.notification.alert("Eksik bırakılan alan var, lütfen doldurup tekrar deneyin.", function(){return;}, "Hata", "Tamam");
    }
  });
},
error:function(xhr,status,message) {
  console.log(xhr);
  console.log(status);
  console.log(message);
}
});

```

As you can see in the first screenshot, the fid is sent along with the node. The second one says the fid is there (dblog), but the third one says it's not (devel). Also, directly querying the database says it's not in the field\_data\_field\_name, but it is in file\_managed.

Sorry for the discrepancies in fids between images. This problem is too old and it recently started happening again.

# Answer
Kartagis: it is about your operational environments. You should focus on checking the environments' configurations. Try copy the configurations of working server and enhance the working server if it is not accepting large images ( for example in your php.ini play with settings).
> 0 votes

# Answer
There was a regression in Drupal 7.43 that caused problems with file uploads in some use cases. It was first noticed in Webform, and the fix to core was *not* included in the 7.44 release the other day.
> 0 votes

---
Tags: 7, ajax, media, javascript
---


# Question
Title: Multi-language menu's / menu-items setup
I might not understand Drupal 8 and the different Multilingual approach completely, but I'm bumping into all sorts of issues.

What I simply want, is a single Menu , containing links from 2 different languages.

To make this happen :

* I enabled the Language module, and set-up 1 additional language. Install was done in NL, and I added FR
* I enabled the Content Translation module
* I checked both 'Content' & 'Menu Link' under, so that I can translate both the Node & the menu title ( admin/config/regional/content-language )
* Set the language of the Main Menu to '- Not applicable'. I'm not sure if this is right, but the menu would contain links from 2 languages, so I thought this was best option ( admin/structure/menu/manage/main )

Issue #1 :

When I create a NL node & enable menu-link, all is fine on /nl , but on /fr the menu-link still pops up. This seems weird, as I have no translation or menu-link for FR.

Issue #2 :

When I click 'Translate' on the NL node, I get the FR edit form. I type my content, and I change the menu link title ( the field is visible & pre-filled with the NL menu link title ). I now have both a NL & FR version of my node, but my original NL menu link changed with it. I would assume that automatically , a FR version of my menu link would be created. However, that's not the case. I have to manually go to Structure \> Menus and click 'translate' on my NL menu link

Am I setting up the wrong way ? Should I go for a separate NL/FR menu ? Will I have to manually add functionality, to create a menu-item on the fly when I translate a node ?

Has someone done something similar and experienced the same issues? And perhaps have any solutions ?

# Answer
At the moment it is not possible to translate the menu items in the node form:

> Unfortunately the node form's menu widget was not made ready for menu item translations (yet), so if you provide the French menu item title there, it will be updated in the original item and not going to create a translation. Until that is fixed, use the menu item translation process as with the contact menu item.

Drupal 8 multilingual tidbits 20: combination use cases with content and menus

The solution presented by Gábor Hojtsy in the link is to translate the menu in the menu management or use different menus for every language.
> 4 votes

# Answer
I think this is working now. If you go to /admin/config/regional/content-language and choose "Custom Menu Link" (and then select it again below when it appears), it seems to work.
> 2 votes

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


# Question
Title: How to use the Rules module to unset all flags (set x days ago) without using Rules Scheduler
This is a follow-up to my question "How to use the Rules module to unset all flags (set x days ago) when cron runs?".

**Case**: users set flags on content using Flag module (flags are per user, not global).

**Requirement**: after a period of time (= x days) the system should automatically unset these flags using Rules module.

**Limitation**: the `Rules Scheduler` module cannot be used (for a solution using Rules Scheduler module please see the question linked to above).

# Answer
You could use an approach similar to what is shown in the video about Using VBO to load list of objects into Rules, starting from about 5:30, up to 11:30. Here is a summary of what is shown in this video (quote from the linked page):

> * You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
> * However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
> * You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
> * The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.

In your case you want to start from your VBO list of the nodes flagged by a user at least x days ago. And for each node in the list you want the rules action to be "unflag node" (instead of "remove sticky"). You'll have to pass the userid as a parameter also, similar to what is shown around 7:30 in that video also.

It should be possible to use the same Rules component as in Step 1 of my answer to "How to use the Rules module to unset all flags (set x days ago) when cron runs?". This Rules Component should then become the Rules Action to be performed by an additional rule that is triggered by an appropriate Rules Event. It appears to me that Rules Event "User has logged in" could be a good fit for your case (if not replace it by whatever other Rules Event that fits best). This is what differs from what is shown in the video, starting from 11:30 (in the video the Rules component is triggered daily, via the `Rules Scheduler`). Using this Rules Event also complies with your comment to my answer to your related question, ie "*... use user login as the event, fetch the set flags of the logged in user, check their creation time, if they are older than x day unset the flags...*".

**Note**: I think rephrasing "*the `Rules Scheduler` module cannot be used ...*" in your question to something like "*Without using the `Rules Scheduler` module ...*" would improve your question (it is possible to use that module, but for this question you don't "*want to*" use it).
> 2 votes

# Answer
Create a page and use whatever content type you want for it, eg. "Article". And assign a path to that page also, e.g. on `\admin\dummypage`. It doesn't matter what the content of that page is.

Then create a rule (using Rules) and enable the Path Rules module also. With this combination you can trigger a rule when the page `\admin\dummypage` is visited.

The rule can do (= perform a Rules Action) what you want to do. Built a view and with the help of VBO you can apply the changes you want. See therefore the video mention in the next answer.

Then you have to make sure that the page is visited. You can do this by either of following ways:

1. Put a reminder in your calender that includes the URL of your special page, and click on the page.
2. Use a websites like http://www.montastic.com/ (they will retrieve this page regularly).
3. Schedule a cron job. In this cron job you do a `wget` statement to retrieve the page and send it to `null`.
> 2 votes

---
Tags: 7, rules, flags
---


title: I need to render just the submenu

text:
# Question
Title: I need to render just the submenu
I need to print the current nodes submenu somewhere on the page. Inside my `page.twig.html` file I have this markup:

```
<div id="children-menu">
  {{menu_children}}
</div>

```

Inside my `mytheme_preprocess_page()` function I have this which rendering all the submenus.

```
function mytheme_preprocess_page(&$vars) {
  if ($vars['node']->id()) {
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $subtree = $menu_tree->build($element->subtree);
        $output = drupal_render($subtree);
        array_push($subtrees, $output);
      }
    }
    //dpm($subtrees);
  }

}

```

I was looking into using manipulators, but that wasn't working. How can I render JUST the current nodes submenu using this function? Again, what I have now is rendering all the submenus and I need just the current one.

# Answer
I managed to grab just the child submenu of the current page. Each subtree has a `getRouteParameters()` fn that contains the node ID that it links to. I simply test if that route param node id == the current pages node id.

```
function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']) && is_numeric($vars['node']->id())) {
    $nid = $vars['node']->id();
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $routeId = $element->link->getRouteParameters()['node'];
        if ($routeId == $nid) {
          $vars['menu_children'] = $menu_tree->build($element->subtree);
        }
      }
    }
  }
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: Display driving distance between coordinates
I have working a site that needs mileage given between user coordinate and node coordinate. *using location module*. I thought it was returning wrong results, when I discovered it returns actual miles "as the crow flies" so to speak. I determined that when looking at what it plotted on a map. I need driving distance.

I am trying the store locator module (but it really doesn't let me do coordinates yet. But the mileage doesn't display there, and views doesn't let me do that, that I can tell.

Everything I have tried has failed. Anyone doing this?

# Answer
You can use The Google Distance Matrix API

If you want it to display in views there are a few ways you can implement it Either as a custom module, theme the view, or use the views php module.
> 1 votes

# Answer
If you intend to show the actual driving distance between two points then you can use below code :-

function MY\_MODULE\_views\_post\_execute(&$view) {

```
  if ($view->name == 'VIEW_NAME' ) {

    //sort by driving road distance
    $results = $view->result;
    $nids = array();
    foreach($results as $node){
        $nids[] = $node->nid;
    }

    $nodes = _get_geo_position_value($nids); //gets geofield value as view result doesnt have the value

    if(count($nodes) > 0){
        $http_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial';
        $origin_text = "&origins=".$_COOKIE['currentLat'].",".$_COOKIE['currentLong']; //current location of user
        $destination_origin = '&destinations=';
         foreach($nodes as $node){

             $lat = $node->field_gmap_position['und'][0]['lat'];
             $lon = $node->field_gmap_position['und'][0]['lon'];
             $str = $lat.','.$lon.'|';

             $destination_origin.=$str;
            // $destination_origin.= $destination_origin.$node->field_gmap_position['und'][0]['lat'].','.$node->field_gmap_position['und'][0]['lon'].'|';
         }

         $destination_origin = rtrim($destination_origin, "|"); //remove trailing |

         $URL = $http_url.$origin_text.$destination_origin;

         //  Initiate curl
        $ch = curl_init();
        // Disable SSL verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // Will return the response, if false it print the response
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Set the url
        curl_setopt($ch, CURLOPT_URL,$URL);
        // Execute
        $json_output=curl_exec($ch);
        // Closing
        curl_close($ch);

        // Will dump a beauty json :3
        $calc_dist = json_decode($json_output, true);

        for($i = 0; $i < count($results); $i++){
            $results[$i]->field_google_calc_dist = $calc_dist['rows'][0]['elements'][$i]['distance']['value'];
        }
        //sort by google calculated distance
        usort($results, function($a, $b)
            {

                if ($a->field_google_calc_dist == $b->field_google_calc_dist) {
                    return 0;
                }
                return ($a->field_google_calc_dist > $b->field_google_calc_dist) ? 1 : -1;
            });

    }

    $view->result = $results;

  }

```

}
> 0 votes

---
Tags: location
---


title: Image Gallery Has Blurry Images

text:
# Question
Title: Image Gallery Has Blurry Images
My image gallery is showing the images blurry. Its using Ligthbox2. When I click on the images, they show clear in the lightbox. Is this a lightbox setting?

# Answer
Setting my lightbox setting to Display: Single lightbox: large =\> large fixed the problem. thanks. :)
> 0 votes

---
Tags: media, javascript
---


title: Drupal commerce taxonomy

text:
# Question
Title: Drupal commerce taxonomy
I have made taxonomy categories for products, and block where is category link list, but how I can make target url for these categories and when user go to category link there is page and all products in that category is listed?

# Answer
> 0 votes
You create a link to the taxonomy display page. This page will show all the nodes (product display types) that are tagged with the taxonomy term (category). How you display the taxonomy page is up to you. There are many modules which can give you more flexibility to the taxonomy display pages.

---
Tags: nodes, commerce, taxonomy-terms
---


# Question
Title: How can I show an image in a view using the Search API Views integration?
I am using the Search API Views module; I have created an index of users, and on this site, there is an image field on the user profile with a single value (not a user picture, just a standard image field).

I am now making a view and trying to show the image from each user in a field of the view. I added the **Index User: Picture** field, but when I do so, I have three choices for the display:

* Show entity label (gives me the filename (image.jpg) with a link to the image)
* Show entity ID (gives me the number of the entity)
* Show complete entity (doesn't display anything)

I read this issue on images in Search API, which is marked as a duplicate of a fixed issue, but I don't understand how it is fixed or what I am supposed to display the image.

**I want to show the image as a thumbnail in the view. What's the easiest way to do this?** (Given the filename, I imagine I could write a custom views template to print the thumbnail image as suggested in this question on Apache Solr Views, but it seems like there is probably an easier way (the linked Search API issue was fixed four years ago).

# Answer
**Doing this in a views template**

Add the image field.

Set the value of **Display** to **Show entity ID**.

Use the theme information to look up the name for the relevant template file and make the file.

Put the following code into the template file (based on the answer here)

```
$file = file_load($output);
$image = image_load($file->uri);
$content = array(
  'file' => array(
    '#theme' => 'image_style',
    '#style_name' => 'CHANGE_TO_YOUR_IMAGE_STYLE',
    '#path' => $image->source,
    '#width' => $image->info['width'],
    '#height' => $image->info['height'],
  ),
);
echo drupal_render($content);

```

But I feel there must be a better way to do this...
> 0 votes

# Answer
You're on the right track. To achieve this in Views:

1. Add the indexed image field to the View Fields list
2. Set 'Display' to 'Show entity label'
3. Untick 'Link to entity' - this adds additional HTML in the token used below that will stuff things up
4. Select 'Rewrite output of this field', and use this code:

`<img src="/sites/default/files/[field_files_file]" />`

Check the token is right, under 'Replacement tokens', but this should allow you to render the image into the View output.

From here, you can specify any inline attributes you want, e.g. `width`, `height` and so on.

You could achieve a thumbnail look this way, or alternately you could use image styles to generate a thumbnail of the image your users upload, then index that field instead. Note that image styles will save your new image under a different directory, so `sites/default/files` won't work.
> 1 votes

---
Tags: search
---


title: Views getting wrong output?

text:
# Question
Title: Views getting wrong output?
I am in little situation while creating D8 views. My scenario:

I have two Content Types:

1. **Page**, with fields:

* title
    * teaser
2. **Article**, with fields:

* name
    * reference\_page (article have unlimited reference field for)

I want output in each ROW like:

`title` (from *Page*), `teaser` (from *Page*) and `name` of each *Article* where *Page* appears.

I am getting duplicate **Page** fields for each existence of page in **Article**.

Any suggestions?

# Answer
Sounds like this may be solved by using aggregation

Change the No to Yes.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Unable To See Admin Dashboard, How to Manually change the admin theme
I started developing a custom drupal theme from scratch(http://www.codexworld.com/create-drupal-custom-theme-from-scratch/).

In appearance menu below disabled themes, there was a drop-down menu for admin theme with theme names and a checkbox. As a curious person when I set admin theme to my custom theme(i am developing) I was unable to see Website pages & the Drupal admin dashboard because theme is empty/under developement. How to get back the default admin theme?

**Edit:** After Using acrosman's answer(adding `$conf['theme_default'] = 'bartik';` in `settings.php`) i can see pages but still unable to see admin panel because I am using that incomplete theme as admin theme

How to Manually change the admin theme in Drupal 7?

*What I Found:* drupal is a popular website cms but you can't change the admin theme very easily if you chosen a wrong theme as admin theme by mistake.

# Answer
> 2 votes
This is the easiest method to reset your admin theme in a Cpanel.

Update your `settings.php` to have:

```
// If your admin theme is Bartik.
$conf['admin_theme'] = 'bartik';

```

*Warning with using `$conf` as you cannot set the theme via `Appearance` page anymore*.

If you prefer SQL query method...

1. Access PHPMyAdmin.
2. Select the Drupal database and run this query.

`UPDATE variable SET value='s:7:"garland"' WHERE name = 'admin_theme';`

Where `7` is the total number of strings your theme has. Example, if your theme is `adminimal`. Then your query should be like this.

```
UPDATE variable SET value='s:9:"adminimal"' WHERE name = 'admin_theme';

```

Please see the documentation on Drupal.org.

Take note that if you are using `Context` module the `$conf` is not helpful as it will always respect the theme assigned via `Context`.

Hope this helps.

# Answer
> 1 votes
You can change the default theme on the command line with Drush:

```
drush vset theme_default theme_name

```

You can also override the default theme variable in settings.php by adding:

```
$conf['theme_default'] = 'bartik';

```

This will force the site to always use that theme until the line is removed from the settings file.

If everything has gone blank you may be having problems with your theme because you have a basic syntax error or other bug that's causing a white screen of death. That page has several suggestions about ways to make sure you're seeing your errors.

---
Tags: 7, theming
---


title: Rules event is not triggering

text:
# Question
Title: Rules event is not triggering
I've created a custom action to fire when the "checkout is complete" event occurs. The front end is a mobile application, where as the back end is Drupal. So I create an order using its API and update the status the of the order to "complete" manually. But the event is not triggering.

Do anyone know what I'm doing wrong? When I've changed the event to when an order is created, the action is performing.

# Answer
Change the status to "complete" manually may not trigger the rule. Instead, applying a payment for the order manually may work. See here
> 0 votes

---
Tags: commerce, rules, actions
---


# Question
Title: Field for if the current user is a member of the organic group
I am working with Services module to create an API. I have created a View that shows list of Organic groups.

Now I need to add a field which will show if the current user is member of the group or not. Can anyone please tell me how to do this?

# Answer
> 1 votes
There is no field or direct method to show "If the current user is member of the group or not". In your case I have found a solution here:

1. Create a view - showing list of all groups(you have already created).
2. Add new Relationship - **OG membership: OG membership from Node group**
3. Add new field - **(OG membership from node group) OG membership: Group ID (Group ID)**, you can exclude it from display.
4. Add new field - **Global: PHP** (you have to enable Views PHP module for this field) and put below code in this field:

```
<?php

global $user;
$account = user_load($user->uid);
$ugrpid = $account->og_user_node['und'][0]['target_id'];

if($row->gid == $ugrpid){
  echo "Already Subscribed.";
}else{
  echo "Not member of this Group.";
}

?>

```

This is how my view look like( Screenshot ).

---
Tags: organic-groups, services
---


# Question
Title: How to render entity referenced nodes field inside node.tpl.php?
I have 2 content types: book and author.

## This is the structure:

I want to use (print) **some** fields of author content type inside the `node-book-tpl.php`.

How can I do that? Is there a method to print referenced entity's fields like `<?php print render($content['field_author']); ?>` etc.?

*Note: I tried the Inline Entity Display module but because I want to do this with custom node-book.tpl.php it doesn't work for me.*

# Answer
If there is no compelling reason to render the fields from within the template, you could simply:

1. choose a certain view mode for your author content type, say: Token, and make it show only those fields you want to be visible in the book node;
2. set the display of the field referencing the author node from the book node to "Rendered entity" / "Rendered as Token".
> 1 votes

# Answer
As you say author is also a content type. Then you get author content node id on book content.if get node id then use node\_load($author\_nid); to load author node.print\_r() load node and print fields you want to show.
> 0 votes

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


# Question
Title: Don't print $title on certain content types
How would you go about not printing $title on only the 'article' content type? Do i do this through theme-settings.php or page.tpl.php?

Here's a start, but I don't think I'm going in the best direction with this in the theme file.

```
if ( !empty($node) && $node->type == 'article') { }
else {
  print $title;
}

```

# Answer
> 2 votes
There is also a module for this:

Exclude Node Title

> **Info**
>
> This module handles a very simple functionality, decide whatever to exclude a node title from full node page or node teasers.
>
> It provides a checkbox on node-edit pages for easier exclusion.
>
> Also provides the option to hide all titles of a certain Content type. From the administrative interface you can select a content type to hide title for.

And if you have Display Suite installed then this article explains how to do it with that module:

Hide “Page Title” quickly using Display Suite in Drupal 7

> This is something that is so simple to do, once you have figured out the steps to get to the right little click boxes to appear. I wish that it were more intuitive to find, but for all those who struggle with “hiding” the page titles, Display Suite makes it really easy to choose to hide the page title for a specific Content Type or for a particular Node.

# Answer
> 1 votes
`hook_preprocess_page()` and `hook_process_page()` have access to `$variables['node']`, which is set if the page is relative to a node. So you can use the following code.

```
function hook_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'article') {
    $variables['title'] = '';
  }
}

```

I would rather implement this in a module, but you can implement it in a theme too.

You need this code because `template_process_page()` contains the following one.

```
if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}

```

If you don't set `$variables['title']` in `hook_preprocess_page()`, `template_process_page()`, which runs after it, will set it to the default page.
It is enough you set the title to an empty string.

The default template file for pages don't need any change, since it normally checks the title has been set, and print it in the case it was.

Keep in mind that, passing to Drupal 8, you will need to change the code, since:

# Answer
> 0 votes
You can manage this using drupal\_set\_title().

```
 function yourtheme_preprocess_page(&$vars){
  if (isset($vars['node']) && $vars['node']->type == 'article'){
    drupal_set_title('');
  }

```

}

---
Tags: 7, theming
---


title: Display content based on URL

text:
# Question
Title: Display content based on URL
I am working on Drupal 8. I have a to display content from a content type on different pages. I am trying to use Views to achieve this.

In the content type I added a field to refer to Pages so that I can create relation between content of content type and Pages (another content type). Basically its like tagging content with page name.

I want to display content from content type created on those pages tagged in the content. I am not able to achieve using views.

Any ideas how this can be done? I have tried contextual filter and relationship but none works.

Thanks

# Answer
> 0 votes
You can use as an example the taxonomy term view, which is in the D8 standard installation:

```
admin/structure/views/view/taxonomy_term

```

Two steps are necessary. First define the parameter in the path. For the taxonomy term this is:

```
Path

taxonomy/term/%

This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term

```

Then add a contextual filter in the advanced section, which will process this parameter:

```
CONTEXTUAL FILTERS
Add contextual filters
Content: Has taxonomy term ID

```

For the details see the example in your drupal installation. In your case you would use the referenced Pages node id.

If you want to use the view as a block, you cannot define the parameter in the path setting of the page. Then you have to switch in the contextual filter to "Provide default parameter" and configure the parameter from URL.

---
Tags: views, 8
---


# Question
Title: How to display blogs related to particular taxonomy term name
I am creating blogs in my site. I have categorized the blogs by using taxonomy terms. I want to display these category names in right side view as a block, and when user clicks on the name, views should display related blogs to the user.

I tried by using contextual filter but its showing content title not the taxonomy term names, as you can see in the above image right side block. Below images shows the contextual filter settings i tried.

So please help me regarding this.

# Answer
> 0 votes
You **don't** need a contextual filter for this. The only thing you need is an **exposed filter** of the **taxonomy** you created. You can then use **Better Exposed Filters** to create links instead of a select list or checkboxes.

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


title: How do I render a <iframe> tag?

text:
# Question
Title: How do I render a <iframe> tag?
I am using the following code.

```
public function buildForm(array $form, FormStateInterface $form_state) {
 $appDir = take_control_app_dir();
 $extpath = take_control_fb_ext_client_path();

 $validationString = take_control_random_string(20);
 $fbpath = take_control_client_path(drupal_get_path('module', 'fb') . '/fb.html?extpath=' . $extpath);
 $form = [
   'example one' => [
     '#markup' => '<iframe src="www.google.com"></iframe>'
   ],
   'take_control' => [
     '#markup' => '<p>iframe</p>',
   ],
 ];

 return $form;
}

```

The `<iframe>` tag is not rendered.

Is there any way to make it render?

# Answer
> 19 votes
Probably iframe is filtered in `#markup`. Use an `inline_template` instead:

```
  'example one' => [
    '#type' => 'inline_template',
    '#template' => '<iframe src="{{ url }}"></iframe>',
    '#context' => [
      'url' => 'www.google.com',
    ],
  ],

```

---
Tags: 8
---


# Question
Title: Showing both original base price and calculated price (inc. taxes), when using two price fields and rules
Building a webshop for customer with Drupal 7 + commerce. I've defined **two price fields** for commerce product entity:
1) base price (excluding tax) that is wholesale price
2) retailer price (excluding tax)

There is a rule with a condition "current user has role reseller" and action that sets retailer price as base price. This works perfectly, showing different price for logged in resellers. Also, there's a rule for tax calculation.

Now, the problem comes when trying to **show both wholesale price and reseller price on the product pages including taxes**. Because prices are overwritten by rules, "original" base price is not available anymore. I've tried to figure out how to do this programmatically since "Commerce price savings formatter"-module does not work with this kind of price structure. (tested price savings formatter module with discount rules, we are also using and it works well)

I'm quite lost where this should be done, should I change it in product node template (or template.php with some hook)? I can find the the original price without tax by going really deep in the content array. But I would need the tax too, at least the percent so I can do the calculations.

Any help, even tiny hints are much appreciated!

EDIT:
The working rule that sets the retailer price is defined as follows:

EVENT:
* Calculating the sell price of a product

CONDITIONS:
* User has role (=retailer)

ACTIONS:
* "Product has special price"-component
* Parameter:\[commerce-line-item\] (named as "product line item")

Then I have custom component "Product has special price"-component

CONDITIONS:
* Data comparison: \[product-line-item:type\] = Product

ACTIONS:
* Set the unit price to a specific amount
* Parameter: \[product-line-item\]
* Amount: \[product-line-item:commerce-product:field-retailer-price:amount\]

# Answer
I have been thinking of this, but can you delay the setting of the price?

I suppose you are currently overwriting the price when the user is viewing the node? Can't you set the correct price when the product is added to the cart? That would allow you to show both prices next to eachother.

Optionally if you don't want regular users to see the wholesale price, use a module like Field Permissions to prevent certain roles from viewing certain fields.
> 0 votes

# Answer
Finally found a solution. The problem was in the original price rule settings.

The action "*Sets the unit price to a specific amount*" had a wrong **\[price component type\]**, it was "**Base price**" and it should have been "**Discount**" of course. That is why the original base price was not available any more on product pages.

Also, the price savings module works now, so no need to make any customizations there.
> 0 votes

---
Tags: 7, commerce, rules
---


# Question
Title: How to exclude all blocks on a specific page?
I have a website that uses themekey to display a different theme for one page. I use the context module to display blocks across the site (\*). I tried to exclude the page I don't wish to display blocks on using `~`, but it didn't work.

Essentially I followed this answer for my path setup: Exclude a block from specific parts of the website with the Context module

So in my path setting I have

```
*
~my-page-to-exclude-all-blocks

```

That did not work as all the blocks listed in the context are still present. I even went so far as to create a second context with no blocks added for the path in question, but that didn't work either.

Edit: I also tried `~/my-page-to-exclude-all-blocks`, but that didn't work either.

# Answer
> 1 votes
You could use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is not shown on that page on which you want to hide that block).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_exclude_a_page" : {
    "LABEL" : "Hide block for a specific page",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "my-page-to-exclude-all-blocks"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

Adapt the value of `my-page-to-exclude-all-blocks` to fit your needs. Obviously, you can reuse the same Rules Component for all blocks you want to hide on that specific page.

Should you want to further enhance the above Rules Component (to make it more generic), just replace the Rules condition in it with something using an appropriate regular expression (related to the current path also).

**Note**: yes this requires (at least) 1 more module (Rules block visibility, and Rules which it depends on). I also always try to avoid ***modulitis*** (= way too much modules) in any Drupal site. However adding Rules to any site seems to me like a no-brainer, because you can avoid/eliminate dozens of other modules that do only 1 thing. And by using the (tiny) Rules block visibility module, you can potentially replace modules such as the Context module and/or reduce the need for custom modules and/or using the (dangerous) PHP filter.

---
Tags: 7, blocks
---


# Question
Title: Active menu trail for multiple menu item with the same path
It is possible to have menu items that point to the same node and have the active state dynamic?

If I click the link 'List item A1' I would like to become active the link 'List item A'.

If I click the link 'List item B1' I would like to become active the link 'List item B'.

```
 - List item A (node/1)
 --  List item A1 (node/2)

 - List item B (node/3)
 --  List item B1 (node/2)

```

# Answer
You can use the module menu-position for this. When you add a new rule, just choose the option *Mark the rule's parent menu item as being "active"* on the settings page. You probably have to create a css rule for your theme, too.
> -1 votes

---
Tags: hooks
---


title: Get taxonomy terms value in views

text:
# Question
Title: Get taxonomy terms value in views
I have two content types

1. Program
2. Registration

and one taxonomy

1. Program type

Program content type having term reference with program type taxonomy and registration having node reference with a program.

I am using views to list out all registrations.

How can I get the program type terms value in registration content type list?

# Answer
Considering entity reference fields in the following manner:

1. Program having an entity reference field pointing to the terms of program type vocabulary.
2. Registration having an entity reference field pointing to nodes of type Program.

To achieve what you want:

1. Create a view of content. Of type "Registration". Add required fields from registration content type
2. Add a relationship of type "Entity reference: referring entity" with field from #2 above.
3. This will enable you to add attributes/fields from the "Program" content type.
4. Add a relationship of "Entity reference: referring entity" with the field from #1 above (pointing to terms). **Important:** Use the earlier relationship in this new relationship (i.e. nested relationship).
5. This will let you add attributes/fields from the taxonomy terms.
> 1 votes

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


# Question
Title: How to check if entity id exists or valid?
I have created a *content entity type*. When I save form, I got id in routing url, like:

```
entityform/1

entityform/2

```

But if I directly access some *non-existing id* like `entityform/999`, **page dies.**

In **watchdog**, it is showing error,

> Error: Call to a member function get() on null in Drupal...

I can not call function get() on the fields of entity, if entity doesn't exists.

```
$content_type = $entity->get('ctype')->value;

```

How to apply this check, whether entity actually created or not?

# Answer
You can check if the entity object `isset()` or is not `NULL`, and use `get()` only if the condition passes.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: How to check order exist or not in commerce order?
I am using Drupal 7.31 and the Commerce Kickstart distribution. I added an order using CSV file in commerce\_payment\_transaction table.

I want to check the condition below:

```
if (isset($_POST['submit'])) {
  $handle = fopen($_FILES['filename']['tmp_name'], "r");

  $i = 1;
  $f_status = FALSE;
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      if($i > 2){

        $o_id = $data[1]; // I am fetch order_id from csv. I wont to check which order_id is coming from csv is present on commerce_order or not?
        $remote_id = $data[2];
        $created = strtotime($data[7]);
        $changed = strtotime($data[11]);
        $amount = $data[8] * 100;

        $db_query = db_select('commerce_payment_transaction','cpt');
        $db_query->fields('cpt');
        $db_query->condition('cpt.order_id',$o_id,'=');
        $db_res = $db_query->execute();
        $row_count = $db_res->rowCount();

        if($row_count == 0){
            $o_load = commerce_order_load($o_id);
        }
    }
  }
}else{
   $output = "Upload new csv by browsing to file and clicking on Upload<br />\n";
   $output .= "<form enctype='multipart/form-data' method='post'>";
   $output .= "File name to import:<br />\n";
   $output .= "<input size='50' type='file' name='filename'><br />\n";
   $output .= "<input type='submit' name='submit' value='Upload CSV'></form>";
   return $output;
 }
 $i++;
}

```

How can I do so?

# Answer
> 1 votes
You can check this using `commerce_order_load()`

```
if(commerce_order_load($order_id)){
    //Do something
}
else{
   //Do something
}

```

Hope this will help you

---
Tags: commerce, hooks, 7
---


# Question
Title: Cookie not being created (not a schoolboy error, I hope)
I'm building a deeplink system into a very complex website which needs cookies and other context set-up before the deeplink will work (otherwise the page gets redirected back to the home page - not much use).

So I've added a module which provides the deeplink entry point through hook\_menu:

```
deeplink/<deeplink-parameters>

```

The callback builds the context, adds the cookies and then redirects to the actual required page.

So much for the theory. It doesn't work and I can't figure out why not.

In order to replicate a completely "virgin" request I've been using incognito windows, restarting the server and clearing caches before each test. In the test version I'm not redirecting to a new page, just outputting a line of text to display the page.

But even attempting to generate a simple test cookie with a long life (REQUEST\_TIME + 999999) fails. No cookie created. The setcookie() function is returning TRUE (cookie created), which implies there is no problem.

The only cookies I can see are the ones created by JavaScript on the page itself, and a couple created by the Zeus wrapper (there are no Zeus rules to delete cookies on standard Drupal pages).

Just in case the cookie isn't visible on the first page I am also then moving to another page but still no cookie. Seems like it just isn't being created despite what the function says.

Additional data: There is also no PHP Session ID cookie.

Any thoughts as to why the cookies are not appearing?

EDIT: Looking at this further, I moved the setcookie() function into index.php (before the Drupal bootstrap), and it still wasn't creating the cookie.

So rather than issuing the deeplink command as above I simply went to the home page. And it's *still* not creating the cookie (as an anonymous user, with everything cleared before we start).

Only when I moved away and into the more complex part of the site did the test cookie appear. At the same time that the PHP Session ID cookie appeared. Is this a hidden dependency? No cookies can be created through PHP unless there's a PHP session ID?

# Answer
The world has not turned upside-down.

It turned out that Zeus was indeed eating cookies of anonymous accesses, I had to go through every Zeus rule (we have a lot) until I found it.

Testing with Zeus bypassed demonstrated the cookies were created correctly.

*Bloody Greek Gods, wandering in uninvited and eating all the cookies...*
> 0 votes

---
Tags: 7, cookies
---


# Question
Title: Disable coupons field from checkout page when order total amout is less than $500
I am working on `Drupal commerce` site. Using `commerce_discount_extra` and `commerce_discount` for discount and coupon code.

I just want to display Coupon apply filed into checkout page while the total amount of order will be \>=$500. Below $500 the coupons field will not display into checkout page.

So can anyone please tell me how can I disable the Coupons fields from checkout page when the order amount will be less than $500?

Thanks in advance.

# Answer
> 2 votes
Hope it works.

```
function module_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {

  if ($form_state['order']->commerce_order_total['und'][0]['amount'] < 500) {
    unset($form['commerce_coupon']); // enter coupon form name
  }
}

```

---
Tags: commerce
---


# Question
Title: How to show a block on pages with a path like '/member/*' but not 'member/*/likes'?
I want to show a block on a member's profile page (`member/*`) but not on `member/*/likes`.

It doesn't seem I can do this without PHP in the block settings, does it?

# Answer
> 2 votes
Try restricting visibility to this URI:

```
member/*/

```

(trailing slash!)

Alternatively, you can download the Context module and position the block using a new context, and negate the `member/*/likes` path in your context configuration.

# Answer
> 0 votes
There **is a way** to answer your question ***without PHP in the block settings*** (as in your question): you can use the Rules block visibility module for this (assuming your question is about D7). Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the block is only shown on your pages with a path that **starts with** "`members/`", but not on those pages that have a path **ending with** "`/likes`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_block_visibility_show_on_selected_member_pages" : {
    "LABEL" : "Show block on selected member pages",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "members\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "\/likes",
              "operation" : "ends"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

Also, if you'd replace the 2nd Rules Condition in the above Rules Component with something using an appropriate regular expression, you could even further refine it, to check for something like "`members/uid/likes`", whereas `uid` corresponds with some user's uid, and so that the block would be shown anyway on pages with a path like "`members/with/lots/of/likes`".

---
Tags: blocks
---


title: How Drupal handles nodes 404 requests?

text:
# Question
Title: How Drupal handles nodes 404 requests?
I'm curious about how Drupal 8 handles nodes 404 requests. I think there might be a route of 404 and then an internal check - if node id doesn't exists, it simply calls 404 route path.

If this scenario is right, how can I achieve the same for custom entity?

I have a content entity type, but want a 404 redirection if someone access wrong entity id directly similar to any node page which doesn't exists.

# Answer
Ah, seeing that this is a follow-up to How to check if entity id exists or valid?, I think I know what the problem is.

If you ensure upcasting through the route, then Drupal throws a not found exception automatically and shows the 404 page.

So, you need to define your route as /entityform/{your\_entity\_type\_id} and in the controller, type hint the argument YourEntityTypeId $your\_entity\_type\_id. Then Drupal automatically loads the object, gives it to you and returns a 404 page if not found.
> 4 votes

---
Tags: 8, entities
---


# Question
Title: Access field data from entity in block plugin
I'm attempting to render certain fields within a block plugin but I'm not sure where to start as far as accessing the fields so I can render them.

I'm able to get the node ids after I perform the query using the following code.

```
    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post');
    $nids = $query->execute();

```

This retrieves the ids that I need based on the query but I don't know how to access custom fields like blog\_summary.

I looked into some functions like getFieldDefinitions(). But I'm not sure how to make use of it. I attempted some things using getStorage but I assumed I wouldn't want to go that route since I'm not attempting to make any changes to the nodes I only want to access their fields.

# Answer
> 2 votes
Try this:

```
public function build() {
  $query = \Drupal::entityQuery('node')
    ->condition('type', 'blog_post');
  $nids = $query->execute();

  $build = [];
  foreach ($nids as $nid) {
    $node = Node::load($nid);
    $build[] = $node->blog_summary->view();
  }
  return $build;
}

```

# Answer
> 1 votes
It depends on what type of fields you want to render. For strings and ints you may just use

```
$node = Node::load($nid);
$build[] = $node->field_name->value;

```

---
Tags: 8, entities
---


# Question
Title: Restrict node list in entity reference field based on node field
My "Article" nodes have a "domain" field that links to a taxonomy term. My "Article" nodes also have a repeatable "entity reference" field "more like this" that links to other "article" nodes.

How can i restrict the list in the "more like this" field to show only the nodes that have the same "taxonomy term" that the node i am currently editing ?

Thanks a lot !

# Answer
For the PHP solution you have to provide an EntityReferenceSelection Plugin. I give you an example from my "proreos" project:

```
namespace Drupal\proreos\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection
...

/**
 * Plugin implementation of the 'selection' entity_reference.
 *
 * @EntityReferenceSelection(
    *   id = "default:proreos",
    *   label = @Translation("proreos selection"),
    *   entity_types = {"address_entity", "anwalt_entity", "library_entity"},
    *   group = "default",
    *   weight = 1
    * )
    */
class OwnEntitiesSelection extends DefaultSelection {

  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
      $query = parent::buildEntityQuery($match, $match_operator);
      ... your code here to modify the query ...
      ... (I do $query->condition('user_id', $currentUid);) ...
      return $query;
   }}

```

You may also need to override validateReferenceableNewEntities(). Look for more examples in the core modules.
> 2 votes

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


# Question
Title: Looking to change the header from a color to an image
I am using the NewsCenter theme for my Drupal site, and we have had a new logo/banner designed for our website that I want to implement -- but it's not as simple as just uploading it and replacing the old logo.

1. This is the header of our site as it stands currently:
2. This is what I want to get to:

Also, with the final option, I still need to have users be able to click in the banner and get directed 'Home' -- I presume that to do this I would still upload a logo.png, but that it would just be a large transparent rectangle.

Thanks!

# Answer
> 0 votes
Add this CSS:

```
<style>
  #header {
    background: url('critic-banner-image.png');
  }
  #logo {
    margin: 0 15px 5px 15px;
  }
</style>

```

Add this background image (use better ones that your client provides)

Replace your old logo with this:

(use better ones that your client provides)

---
Tags: media
---


# Question
Title: How to call drupal_bootstrap from custom file in subfolder?
I'm trying to call `drupal_bootstrap` from 'temp.php' in a subfolder called 'custom' my code as follow:

```
chdir('../');
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Once I call the temp.php I get Drupal homepage.

I also tried an explicit physical path but with no use, code as follow:

```
define('DRUPAL_ROOT', '/var/htdocs/drupal7');
require_once '../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

temp.php located under the following folder structure:

```
- var
-- htdocs
--- drupal7
---- custom
----- temp.php

```

# Answer
> 6 votes
I wrote a short post on this here: http://www.csdesignco.com/content/using-drupal-data-functions-and-session-variables-external-php-script

Basically, you only need to do what `index.php` does, but you can elevate the bootstrap to whatever level you need:

```
<?php
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
?>

```

So, for instance, if you just wanted to get something form the database (security aside, this is just an example):

```
<?php
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']); // Define the DRUPAL_ROOT constant which is used in many places.
$base_url = 'http://'.$_SERVER['HTTP_HOST']; // Again, this is used in many places.
require_once DRUPAL_ROOT . '/includes/bootstrap.inc'; // Include the boostrap file.
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); // Start things up to whatever level you need.

print db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => $_GET['nid']))->fetchColumn();
?>

```

you could hit `example.com/my-file.php?nid=123` to see the node title for node 123.

I also wrote a tiny function which you can find in this issue (http://drupal.org/node/1922406) where I needed to get the current user's session but didn't want to elevate Drupal's bootstrap to DRUPAL\_BOOTSTRAP\_SESSION as the page load goes from ~ 20 milliseconds to over 1,000 milliseconds:

```
function _mymodule_js_session_user() {
  $session_name = session_name();
  if (!empty($session_name)) {
    if ($uid = db_query("SELECT uid FROM {sessions} WHERE sid = :sid", array(':sid' => $_COOKIE[$session_name]))->fetchColumn()) {
      $account = new stdClass();
      $account->uid = $uid;
      $account->roles = array();
      $account->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
      $account->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $account->uid))->fetchAllKeyed(0, 1);
      return $account;
    }
  }
  return FALSE;
}

```

# Answer
> 5 votes
take a look at http://drupal.org/project/js they implemented a custom js.php that bootstraps drupal.

```
/**
 * @file
 * Callback page that serves custom JavaScript requests on a Drupal installation.
 */

/**
 * @var The Drupal root
 */
define('DRUPAL_ROOT', getcwd());

/**
 * @} End of "Required core files".
 */

/**
 * @name Required core files
 * @{
 * The minimal core files required to be able to run a js request
 */
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '/includes/common.inc';
require_once DRUPAL_ROOT . '/includes/module.inc';
require_once DRUPAL_ROOT . '/includes/unicode.inc';
require_once DRUPAL_ROOT . '/includes/file.inc';
/**
 * @} End of "Required core files".
 */

// Do basic bootstrap to make sure the database can be accessed
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

```

# Answer
> 0 votes
Basically, this should be enough (or at least, it was enough for me to run Drupal (7.44 version) functions from `test.php` file **located in the site root folder**):

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

---
Tags: 7, bootstrapping
---


# Question
Title: What is the difference between using drupal_goto('$path') and header('Location: $path')?
I've been struggling a lot with a `drupal_goto()` not redirecting from a view to correct path in all displays.

This is the snippet code.

```
/**
 * Implements hook_views_pre_render().
 */
function HOOK_views_pre_render(&$view) {
  //if only on node matches, redirects to that node
  if ( $view->name == 'FOO' && $view->current_display == 'BAR' && count($view->result)==1 ){
    if(is_numeric($view->result[0]->nid)){
      drupal_goto('node/' . $view->result[0]->nid);
    }
  }
}

```

Instead, `header('Location:node/' . $view->result[0]->nid);` is working in any case. Why doesn't `drupal_goto()` work, sometimes?

# Answer
I had an exposed filter with identifier named *destination*. Since `drupal_goto()` takes care of the *destination* parameter sent in URL with the following code, it was overwriting my code.

```
  // A destination in $_GET always overrides the function arguments.
  // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }

```
> 1 votes

---
Tags: 7, redirection, views
---


# Question
Title: How to show blocks by url, when nodes have multiple paths?
I know that having multiple path aliases to a single node is discouraged, but it is a situation I have to deal with.

My node is accessible via `/news/node-1`, `/baseball/news/node-1` and `/basketball/news/node-1`. It's the same node, just three different aliases.

I have a 3 menu blocks, only 1 of which should be shown at any given time. I've configured the Page restrictions on the blocks so that they are restricted to certain url path patterns.

The "baseball" menu is restricted to `baseball/*`, the "basketball" menu is restricted to `basketball/*` and the 3rd menu is everything else, so I've set it to show on all pages except for `baseball/*` and `basketball/*`.

However, my problem is that when I'm browsing to `baseball/news/node-1`, the 3rd "everything else" menu is the one being shown. My -guess- is that Drupal is looking behind the scenes and seeing that the node is also considered to be `/news/node-1` and therefore the path being used to choose my menu block is choosing the 3rd "everything else" menu.

a) Is there a way to see what path Drupal is using when determining which blocks to show based on path?

b) Is there a hook I could implement so that I can directly control which block to show on each request?

c) Any other ideas how I can make sure the correct block is shown?

# Answer
> 2 votes
Try setting the baseball menu to show on `baseball/*` and `baseball/*/*`. Likewise for the basketball menu, then set the Everything Else menu not to show on all four paths.

# Answer
> 1 votes
Sure there is a way to answer your question, and ***without PHP in the block settings*** (as suggested in of the comments), and without the need for any hooks (custom code): you can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the appropriate menu block is shown on the appropriate pages).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by the variations below to make it match your specific question.

### For your 1st menu block (baseball):

Within the block visibility settings of this block, use this Rules Component:

```
{ "rules_block_visibility_show_menu1" : {
    "LABEL" : "Show block containing menu 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "baseball\/",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

### For your 2nd menu block (basketball):

Within the block visibility settings of this block, use this Rules Component:

```
{ "rules_block_visibility_show_menu2" : {
    "LABEL" : "Show block containing menu 2",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "basketball\/",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

### For your 3rd menu block (everything else):

Within the block visibility settings of this block, use this Rules Component:

```
{ "rules_block_visibility_show_menu3" : {
    "LABEL" : "Show block containing menu 3",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "AND" : [
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "baseball\/",
              "operation" : "starts"
            }
          },
          { "NOT text_matches" : {
              "text" : [ "site:current-page:path" ],
              "match" : "basketball\/",
              "operation" : "starts"
            }
          }
        ]
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

---
Tags: 7, routes, hooks, blocks
---


# Question
Title: Image styles with $settings['file_public_base_url']?
I deep dive in the `settings.php` file of Drupal 8.1 and try to configure `$settings['file_public_base_url']`and `$settings['file_public_path']`.

All media links are correctly rewritten, that works with static files, but styles fails with 404 errors as there is no php support and rewriting rules are not implemented.

How can you get styles to work with `$settings['file_public_base_url']` ? Is it related with Image cache external ?

# Answer
> 2 votes
Finally got it working. It seems that currently there is a bug in the `image` core module that prevents the use of absolute paths in the `$settings['file_public_path']`.

For those interested, you can follow the issue where you can find the patch attached.

Note, that you must also set some rewrite rules on your static files server to get it working. I provided a docker example on how to configure this on GitHub, but mainly here are the main config:

## Vhost configuration of the static file server

Configuration example provided for Nginx:

```
server {
    listen 80  default_server;
    root /files/domain.fr/public;

    index index.html index.htm;

    location @rewrite {
        rewrite ^/(.*)$ http://DRUPAL.SERVER.IP/files/domain.fr/public/$1;
    }

    location ~ ^/styles {
       try_files $uri @rewrite;
    }

    location ~ ^/core {
        rewrite ^/(.*)$ http://DRUPAL.SERVER.IP/$1;
    }
}

```

## Drupal settings file

Add this to your `settings.php` file:

```
$settings['file_public_base_url'] = 'http://STATIC.WEB.SERVER';
$settings['file_public_path'] = '/files/domain.fr/public';

```

---
Tags: media, configuration
---


# Question
Title: How do I tweak the HTML markup of an image?
I want to edit the `alt` tag for several images on my Drupal site.

But Drupal just lets me upload and place the images.

How do I access the html for the images?

# Answer
Go to **Structure \> Content type \> Your content type \> Manage Fields \> Your image fields \> Edit**. There are the **Enable Alt field** and **Enable Title field** checkboxes; select them, and you will have access to the meta data in your node/add form.
> 1 votes

---
Tags: media
---


# Question
Title: Use content field as data attribute in Views html
I have a piece of content with an 'Asset Type' field value of Vidyard. I am using the Views module to render this content on another page. I have added those fields to the View, but is it possible to add them as a data-attribute to the HTML. For example, the Views module outputs:

```
<li class="views-row views-row-2 views-row-even views-row-last">
    etc.
</li>

```

How can I add my "Asset Type" field as a data-attribute to the list item. Making my output:

```
<li class="views-row views-row-2 views-row-even views-row-last" data-asset="vidyard">

```

Is there a way to do this without altering the template?

# Answer
> 1 votes
There are some limitations if you can't change the output templates for the view (and I'd assume if that's the case a views pre render is also out of scope). If you can accept them within the `<li>` (instead of on the `<li>`) you can rewrite the field to use a token. Make sure the field that is just data is listed before the field it will be attached to, enabled rewriting on the field, and use the field tokens to attach the value as an attribute. You'll most likely want to suppress the field from output and do some data cleaning to make sure invalid characters don't end up in the token (like `"`).

You can attach classes based on the row value to the `li` by using the same token you would use on the rewrite. Drupal will ensure it's safe for output, but then your data is a class and not the attribute you are seeking.

You'll have more control over the output, and you'll be able to build more elegant solutions if you use `hook_views_pre_render()` to modify the output more directly.

---
Tags: views, theming
---


# Question
Title: Access the field class from within FieldItemList (D8)
When I would like to get the values inserted in a form, I use:

```
$form_state->getValue('myfield');

```

If I would like to have some information on the field definition, I use:

```
$form_state->getFormObject()->getEntity()->myfield->getfieldDefinition();

```

Every time I check the class resulting from the following statement:

```
$form_state->getFormObject()->getEntity()->myfield

```

It is of the type `Drupal\\Core\\Field\\FieldItemList` which is fine for getting/setting the values

Suppose that "myfield" is of the type "language\_field" defined in `\Drupal\languagefield\Plugin\Field\FieldType\LanguageItem`.

This class have a public function

```
public function getNativeName()

```

To get the full name of the language.

But My question is: how to access this function fromwithin the FieldItemList object? (Same problem arise with many other field type)

Added info:

With the help of @Eyal, I could access my object method:

```
$form_state->getFormObject()->getEntity()->myfield->get($delta)->getNativeName();

```

But this is valid only if the entity is already saved.

In the case of a new (or edited) item, the entity doesn't store the new value. Here is the code for what I am trying to explain:

The 2 variables will have the same value if I open and save the form without change, but this will not be the case if I update the item at delta=1.

```
function my_validate($form, FormStateInterface $form_state) {
  $val_by_entity=$form_state->getFormObject()->getEntity()->myfield->get(1)->value;
  $val_by_form_state_value=$form_state->getValue(['myfield', 1, 'value']);
}

```

# Answer
You first need to understand that the entity object in question does not have a property called myfield.

Drupal uses something called magic properties to mask the get method required for retrieving the field item list. See FieldableEntityInterface::get() for more information.

The second thing you should know, is that drupal treats all fields as multi value. That means that a field that is defined to have a single value would still be represented a list with a single item.

Finally, to answer your question, you can either use the FieldItemListInterface::get() method to get the field item object, it you can access it as though it was an array.

`$entity->get('myfield')->get(0);`

*OR*

`$entity->myfield[0];`
> 1 votes

---
Tags: forms, 8
---


# Question
Title: How to add custom predefined content panes?
I've seen in a few tutorials and videos online that the following Content Panes are available:

Those that say Add links, add file, etc. For example this video also shows one called 'add page banner'. However, I don't fine how to install those content panes!

I've installed the Panels module, In-Place Editor, CTools and Custom Content Panes among others, but those are not available. How can install them? (using Drupal 7) Thanks.

# Answer
You need to a Drupal distribution called Panolopy. You may also want to review this page.
> 0 votes

---
Tags: 7, panels
---