# Question
Title: Statistic count not working with API call
There isn't much info around it, but when I'm using `Statistic module` to get the views per node it's only working when I'm visiting the page of the specific `node`. When I'm using an `API` call to a specific node, the statistic module doesn't increase with 1...

Is there a way to solve this?

# Answer
Node views are only counted when `node_view()` is invoked (i.e. when the node is actually viewed).

When retrieving a node via services you're not, conceptually, "viewing" it, so you shouldn't expect the view count to increase.

In order to get your desired workflow, you'll probably need to implement a custom services resource which updates the statistics manually when a node object is requested. See How to create a custom resource with Services-3.x for more info.
> 2 votes

# Answer
Another solution is Ajaxly update node counter , it not require custom module or custom resource service.

First, make sure you enable ajaxly update node counter in statistics settings (`admin/config/system/statistics` and check`Use Ajax to increment the counter`) and then

put this code in callback of your service ( replace yournid with your content nid).

```
$.ajax({
  type: "POST",
  cache: false,
  url: Drupal.settings.statistics.url,
  data: {"nid":yournid}
});

```

});

**update**
change

```
  url: Drupal.settings.statistics.url,

```

to

```
 url : 'http://yourdomain/modules/statistics/statistics.php',

```
> 1 votes

# Answer
You can try update node counter after your service resonse with

```
if (is_numeric($nid)) {
  db_merge('node_counter')
    ->key(array('nid' => $nid))
    ->fields(array(
      'daycount' => 1,
      'totalcount' => 1,
      'timestamp' => REQUEST_TIME,
    ))
    ->expression('daycount', 'daycount + 1')
    ->expression('totalcount', 'totalcount + 1')
    ->execute();
}

```

**This is back-end solution and in another answer Front-end solution Provided**
> 0 votes

---
Tags: nodes
---


title: Ubercart with Panels

text:
# Question
Title: Ubercart with Panels
I would like to know if anyone is experienced with ubercart with panels. I am making a website with these two modules, the ubercart is for the online store, the panels is for the layout. And the site headers and footers are within the mini panels of the panels module.

I would like to make the mini panels also appear on the ubercart checkout, cart pages but i dont know if it is possible, since the checkout , cart pages are generated by the ubercart modules and they are not nodes, views, and seems it is not possible to assign them info mini panels in panel module.

Is there any way to make a page generated by module appear as mini panels, and so that i can create a new page by using the mini panels. Thanks!

# Answer
You can use the Context module to conditionally show blocks in certain regions.

So, in your case, you can create a context that is activated on the /cart and /cart/checkout paths, and add the minipanels blocks that you want to the header and footer.
> 0 votes

---
Tags: panels, ubercart
---


title: Should all files be located publicly?

text:
# Question
Title: Should all files be located publicly?
Should all Drupal 8 files be located publicly, or should something like `sites` be the public document root?

```
[Michael@devserver drupal-8.1.1]$ ls -l
total 228
-rw-rw-r--.  1 Michael Michael    262 May  4 04:20 autoload.php
-rw-rw-r--.  1 Michael Michael   1437 May  4 04:20 composer.json
-rw-rw-r--.  1 Michael Michael 146226 May  4 04:20 composer.lock
drwxrwxr-x. 12 Michael Michael   4096 May  4 04:20 core
-rw-rw-r--.  1 Michael Michael   1272 May  4 04:20 example.gitignore
-rw-rw-r--.  1 Michael Michael    549 May  4 04:20 index.php
-rw-rw-r--.  1 Michael Michael  18092 Sep 23  2014 LICENSE.txt
drwxrwxr-x.  2 Michael Michael   4096 May  4 04:20 modules
drwxrwxr-x.  2 Michael Michael   4096 May  4 04:20 profiles
-rw-rw-r--.  1 Michael Michael   5889 May  4 04:20 README.txt
-rw-rw-r--.  1 Michael Michael   1596 May  4 04:20 robots.txt
drwxrwxr-x.  3 Michael Michael   4096 May  4 04:20 sites
drwxrwxr-x.  2 Michael Michael   4096 May  4 04:20 themes
-rw-rw-r--.  1 Michael Michael    554 May  4 04:20 update.php
drwxrwxr-x. 26 Michael Michael   4096 May  4 04:43 vendor
-rw-rw-r--.  1 Michael Michael   4006 May  4 04:20 web.config

```

# Answer
The doc root should be where index.php is; that's where all requests for non-existent files are rewritten to.

If you mean "should the application and the front end be separate, like in other frameworks?", then yeah, maybe they should. But they're not at the moment, if memory serves there was a declined issue about doing just that when D8 was first being planned.
> 2 votes

---
Tags: 8, installation
---


# Question
Title: How to add a local task tab to node view?
I'm trying to add an extra tab to the node 'view' and 'edit' tabs.

My module is enabled fine and I have cleared cache, but my new tab doesn't appear. What am I missing?

```
/**
* Implements hook_menu().
*/
function add_performance_menu() {
  $items = array();

  $items['node/%node/performance'] = array(
    'title' => 'Add a performance',
    'page callback' => 'add_performance_action',
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
* Page callback.
*/
function add_performance_action() {
  return t('Hello');
}

```

# Answer
> 1 votes
Your code looks good but Remember to clear your Drupal caches at admin/config/development/performance after every change to your hook\_menu above.

The alternative that comes to mind,would be to use hook\_menu\_local\_tasks\_alter, because the menu item we want to use may be already exists.

You can also try this i hope it will help you:

```
/**
* Implements hook_menu().
*/
function add_performance_menu() {
  $items = array();
  $items['node/%node/performance'] = array(
    'title' => 'Add a performance',
    'access callback' => 'your_module_access_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}
function your_module_access_check($node) {
  if ($node->type == 'page') {
    return TRUE;
  }
  return FALSE;
}

```

Thanks

# Answer
> 0 votes
When you change the hook\_menu you don't have to 'clear cache' but 'rebuild menus'.

---
Tags: 7, routes
---


# Question
Title: Can I use Apache 2.2.15 with mod_rewrite enabled?
I currently am running Centos 6 which only comes with Apache 2.2.15. Yeah, I know it is about time for me to upgrade... I get the following warning:

> The minimum version of Apache needed to run Drupal without mod\_rewrite enabled is 2.2.16. See the enabling clean URLs page for more information on mod\_rewrite.

I have mod\_rewrite enabled. Am I okay as is? I don't care about pretty URLs at the moment as I am just learning about Drupal, and will upgrade my OS someday soon.

# Answer
> 3 votes
Yes, you can go with Apache 2.2.15 as long as you have mod\_rewrite enabled (so you'll have pretty urls).

From Drupal issue Regression fix: allow Drupal 8 to work without Apache mod\_rewrite

> Apache 2.2.16 is only required if mod\_rewrite is NOT enabled

---
Tags: 8, installation
---


# Question
Title: How to get update status of multiple Drupal sites
I have several servers each with numerous Drupal sites on. Not all of them are developed by me.

How would you keep on top of the sites to make sure they are all up to date security wise. In an ideal world I would like them to report to a central location. From that one place I can be alerted.

Worse case I will write my own module to call a Web Service and send the status across. How ever if this has all ready been done will save some time.

# Answer
A search on drupal.org found Drupal Remote Dashboard

If that module doesn't work for you, I would suggest a thorough search of drupal.org before jumping into creating your own module.
> 2 votes

# Answer
You may want to look into Aegir for this:

> Ægir is a mature set of contributed modules for Drupal that aims to solve the problem of managing a large number of Drupal sites. It does this by providing you with a simple Drupal based hosting front end for your entire network of sites. To deploy a new site you simply have to create a new Site node. To backup or upgrade sites, you simply manage your site nodes as you would any other node.
> 0 votes

---
Tags: 7, security
---


title: How do I make parent taxonomy paths?

text:
# Question
Title: How do I make parent taxonomy paths?
I installed Pathauto, Tokens and Entity API module in Drupal 8 and I have been unable to create a pattern that would allow parent taxonomies and then the final node for content type pages. In Drupal 7 the entity API module would add the extra tokens I need but it does not seem to work for Drupal 8.

For Drupal 8 the token \[term:parents:join-path\] works but it is only usable for taxonomy type pages and not content type pages.

If anybody can help me,I would greatly appreciate it.

# Answer
> 1 votes
This is being worked on, see https://www.drupal.org/node/2493559 and https://www.drupal.org/node/2621598.

In the meantime, you need a bit of custom code to connect the dots. You need to implement `hook_token_info()`to define a token on nodes for your field with type term. You can also switch the type of the generated field token to term. The second part is a `hook_tokens()` implementation that forwards \[node:yourtokenname:...\].

It's similar to what node\_tokens() does with node:author:name for example, which forwards the part after author to the user token generation:

```
if ($term_tokens = $token_service->findWithPrefix($tokens, 'yourtokenname')) {
  $replacements += $token_service->generate('term', $term_tokens, array('term' => $node->field_yourfieldname->entity), $options, $bubbleable_metadata);
}

```

---
Tags: 8, entities, path-aliases, tokens
---


# Question
Title: How do I add module theme elements to drupalSettings
I have a module "flot\_d8" which is a wrapper for a javascript library. I would like to streamline the way this library is called from other modules (flot\_examples in this case). I currently call it like this from src/Controller/FlotExample.php

```
$data[] = [
  'data' => [
    [0, 12],
    [7, 12],
    NULL,
    [7, 2.5],
    [12, 2.5],
  ],
];
$div_id = 'placeholder';
$drupalsettings['flot_d8'][$div_id] = ['data' => $data];
$output[] = [
  '#attached' => [
    'drupalSettings' => $drupalsettings,
  ],
  '#theme' => 'flot_d8_my_template',
  '#data' => $series,
  '#options' => NULL,
  '#div_id' => $div_id,
];

```

Is there a way to force the flot\_d8 module to add the $data to drupalSettings instead of passing this task to the flot\_examples module in every single class function?

I tried this

```
function flot_d8_page_attachments_alter(&$page) {
//$div_id = $output["#div_id'];
//$data = $output['#data'];
//$options = $output['#options'];
  $page['#attached']['drupalSettings']['flot_d8'][$div_id] = ['data' => $data, 'options' => $options];
}

```

But I know this isn't the right way to access $div\_id, $data, and $options. Can I use the value in $output\['#div\_id'\] in hook\_page\_attachments\_alter()?

# Answer
> 1 votes
I created an Element within the parent module. This element includes code to add the data and options to drupalSettings. It also determines which libraries are needed and includes them.

---
Tags: 8
---


# Question
Title: Why do I get a "URL not found" error while the image is on the server?
I have a Drupal site which I have just migrated to a different Linux server for development. The site seems to be working more or less.

However, one problem persists: None of the images is shown. Instead, if I click on an image, it says: "Requested URL not found."

What is more, all of these images exist in the proper directories. I checked .htaccess for RewriteRules but did not find anything relevant. I have also played with permissions. Currently the entire root of the site is set to 755.

What can I do to make the images work?

# Answer
> 0 votes
If you have some sort of caching service like "Varnish" active you may want to try clearing it's cache.

This sometimes happens to me and I just need to clear my browser's cache.

---
Tags: media
---


# Question
Title: Display latest three news on a custom template
I'm building a **custom theme** and I would like to display last three inserted news (i.e. nodes with content type = *News*) ~~on the bottom of the home page~~ from inside the home page template.

Something like this:

```
+-------------------------------+
| +---------------------------+ |
| |                           | |
| |          Slides           | |
| |                           | |
| +---------------------------+ |
|                               |
| +---------------------------+ |
| |                           | |
| |           Page            | |
| |           Body            | |
| |                           | |
| |                           | |
| +---------------------------+ |
|                               |
| +-------+ +-------+ +-------+ |
| | Last  | |Second | | Third | |
| | News  | | Last  | | Last  | |
| |       | | News  | | News  | |
| +-------+ +-------+ +-------+ |
+-------------------------------+

```

I created a content type named *Home page*, with fields for manage slides and the page body, then I created a new content (a new node) of type *Home page*.

Inside my custom theme I created a template file named `node--home-page.html.twig` and inside it I can handle the *Home page*'s fields (slides and body) and how to render them inside the page.

After that I created another content type *News* and I added some content of such type.

Now I would like to display latest news inside the homepage template as in the figure above. What is the *better*/*simplest* way to do it?

I'm thinking to load latest news in some `hook_preprocess_HOOK` function (using the `EntityFieldQuery` object) then add them inside a variable for the Twig template. Inside the template I will perform a `for` loop rendering latest news at the page's bottom. Is this a good way to do it or I'm completely out of the way?

---

**EDIT**

*Correction*: I would like to display latest news between slides and body, in this way:

```
+-------------------------------+
| +---------------------------+ |
| |                           | |
| |          Slides           | |
| |                           | |
| +---------------------------+ |
|                               |
| +-------+ +-------+ +-------+ |
| | Last  | |Second | | Third | |
| | News  | | Last  | | Last  | |
| |       | | News  | | News  | |
| +-------+ +-------+ +-------+ |
|                               |
| +---------------------------+ |
| |                           | |
| |           Page            | |
| |           Body            | |
| |                           | |
| |                           | |
| +---------------------------+ |
+-------------------------------+

```

Where `slides` and `body` are two fields of the *Home page* content type.

# Answer
I used the Twig Tweak module and I embedded a custom view, showing latest news, inside my Twig template with:

```
{{ drupal_view('view_name') }}

```
> 1 votes

---
Tags: 8, theming
---


title: Remove html entities in forum topic

text:
# Question
Title: Remove html entities in forum topic
I am using drupal advanced forum, due to migration from phpbb to D7 forum I noticed there are some HTML entities shown in my forum topic. I need to handle this in the tpl file. Can you please let me know where to implement it.

# Answer
> 0 votes
This sounds like data transformation problem; the import didn't format the HTML entity title data on import. Instead of trying to code around the problem in your template, you should reformat your node titles.

Run a code snippet (e.g. `drush scr myscript.php`) that can fix the formatting on your nodes. Something like:

```
// @TODO: Retrieve your list of imported node nids in the $nids array
$nids = array(4, 5);
foreach ($nids as $nid) {
  $node = node_load($nid);
  $node->title = html_entity_decode($node->title);
  node_save($node);
}

```

---
Tags: 7, nodes
---


# Question
Title: How to disable one sort/direction combination from a combined Better Exposed Filters field?
Over at this previous question I figured out how to give a view a list of options that look like this:

> ## Sort by
>
> * Date - Newest
> * Date - Oldest
> * Price - Highest
> * Price - Lowest

Suppose there was a particular sort order combination of sort option and sort direction that didn't make any sense. For example, imagine an "Editor's Choice" sort, where staff apply a rating to products to give the best products a boost.

This makes sense:

> ## Sort by
>
> * Editor's choice
> * Date - Newest
> * Date - Oldest
> * Price - Highest
> * Price - Lowest

This is just a bit strange:

> ## Sort by
>
> * Editor's choice - most favoured
> * Editor's choice - not favoured
> * Date - Newest
> * Date - Oldest
> * Price - Highest
> * Price - Lowest

...not least because 50%+ of products will be equally at the bottom of the "not favoured" list. This sort might also give the misleading impression that the product at the top of the "not favoured" list has something wrong with it, when actually it's equally not-singled-out-for-praise with 50% or more of the shop.

What I'm currently doing, is the brute force approach - using CSS to set the option based on 'Editor's choice Ascending' to `display: none;`. I don't like this, because the wrappers mean I have to use first/nth child selectors which could mean the option gets hidden in future after a seemingly inconsequential update or views config change.

Is there a more stable way to properly remove this option from the form?

# Answer
> 1 votes
I can't find a way to do it through Views or Better Exposed Filters settings, but I have found a way through `hook_form_alter()` in the theme `template.php` file:

Something like this, specific array keys are based on using the BEF combine option and may vary:

```
function YOURTHEME_form_alter(&$form, $form_state, $form_id){
  switch ($form_id)
  case 'views_exposed_form':
    if($form['#id'] == 'views-exposed-form-VIEWID-DISPLAYID'){
      if( isset($form['sort_bef_combine']['#options']['field_FIELDNAME ASC']) ){
        $form['sort_bef_combine']['#hidden_options']['field_FIELDNAME ASC'] = $form['sort_bef_combine']['#options']['field_FIELDNAME ASC'];
        unset($form['sort_bef_combine']['#options']['field_FIELDNAME ASC']);
      }
    }
  break;
  }
}

```

---
Tags: views
---


# Question
Title: On feeds, how to access ORGANIZER source
I'm importing an iCal feed using iCal Parser. I've actually tried a few other parsers including Date API iCal parser, iCalCreator parser, but every one seems to have the same set of sources. How can I access all the other fields in the feed, specifically, the ORGANIZER: `ORGANIZER;CN=name@email.com:mailto:name@email.com`?

I've tried to hook into `hook_feeds_parser_sources_alter`, and setting up a new callback function. Like this:

```
/**
* Implements hook_feeds_parser_sources_alter().
*/
function my_hook_feeds_parser_sources_alter(&$sources, $content_type) {
$sources['field_importer_reference'] = array(
'name' => t('Organizer'),
'description' => t('The name of the organizer.'),
'callback' => 'my_hook_get_organizer',
);
}
function my_hook_get_organizer(FeedsSource $source) {
dpm($source->CN);// this doesn't do anything...
return $source->CN;
}

```

I get this message when I try to import: `Date iCal does not recognize the "Organizer" Mapping Source, and must skip it.`

# Answer
> 1 votes
In writing the question I came across the answer and want to share. I was using the wrong hook. Instead I used:

```
function my_hook_date_ical_mapping_sources_alter(&$sources) {
// Add the "ORGANIZER" iCal property to the mapping sources.
$sources['ORGANIZER'] = array(
'name' => t('Organizer'),
'description' => t('The ORGANIZER property.'),
'date_ical_parse_handler' => 'parseTextProperty',
);
// Add "ORGANIZER:CN" parameter to the mapping sources.
$sources['ORGANIZER:CN'] = array(
'name' => t('Organizer: CN'),
'description' => t("The CN parameter of the ORGANIZER property: the organizer's Common Name."),
'date_ical_parse_handler' => 'parsePropertyParameter',
);
}

```

Note that I'm pulling both the Contact's Name and the mailto field.

This is a hook provided by the `date_ical` module. I basically copied the example found there.

---
Tags: feeds
---


title: Keep node/user tabs in one language

text:
# Question
Title: Keep node/user tabs in one language
I have 3 languages in my site and also user with 'Webmaster' role.

Is it possible to keep all nodes/users tabs (view|edit|translate|devel etc.) in one preferred language for this role?

# Answer
> 1 votes
What you want, as I understand you, is to have a fixed interface language for a certain role.

You can adjust the user interface text language in *admin/config/regional/language/configure*. Unfortunately there's no method based on role. You can only use the user method, so users see the interface in their prefered langauge. This setting is for all users, not just for a role.

You may code a new language detection method based on role, but I don't know where you have to start (except checking the i18n module code).

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


# Question
Title: Ajax webform: refresh page on a successful submission
I am using the ajax webform, because I don't want the page to be reloaded when the user doesn't enter everything correctly because my form slides in and reloading just causes it to disappear and you would have to navigate back there. When I have ajax-mode enabled, the redirect part works differently, and since the site has only 1 page, it doesn't really do anything, the form doesn't close.

What I want to do it actually refresh the page when the form is submitted with ajax-mode on.

# Answer
> 0 votes
Thus topic has its own issue in the module's issue queue: Need to get the redirect message of successful webform submission via ajax with ajax\_disable\_redirect.module

There's a patch but nobody tested it. Maintainer is waitinig for some confirmation. If you need it go for it.

---
Tags: ajax, webforms
---


# Question
Title: Search multiple fields from one text box in a View
I have a database of articles with some taxonomies to classify each article. I also have a view that also contains a faceted search and uses filters to create dropdowns for the taxonomy fields using Views (see the image below). The search results will show facets in the sidebar and a user can click on them to further refine results (such as facets like Doc Year, Doc Author, etc.) The problem is that I really only need one text box to search a group of 3 text fields in this View.

For example, each article contains these three separate text fields:

* Article Title
* Article Title in French
* Article Body

I want one text box on the search form to search these three fields without having to create three fields, one for each database field. The rest of the dropdowns to search each taxonomy can exist in the form to appear like below.

Thank you to everyone helping think how to accomplish this. I am sure it has been done before many times.

# Answer
You achieve it by using `Global: combine field filter`. For details and get familiar with it take a look at

https://swsblog.stanford.edu/blog/views-exposed-filters-multiple-field-search
> 1 votes

---
Tags: views, search
---


# Question
Title: How to use Php code in Views page contextual filter with dynamic URL i.e using %?
I have a content type *App* with a term reference field called *App category*.

I'm creating a view page with path **app/%**. I don't want to use App ID or anything numeric in URL in place of **%**, so I'll be using **app/cooking-app** where **cooking-app** is URL Alias of *App Category*.

How can I display all the nodes whose value in *App Category* field is **cooking-app**? I can easily do this using PHP code but PHP code in contextual filters is not working.

# Answer
I'd highly recommend not using PHP code to do this; tying PHP code to configuration can be error-prone and it won't exist in Drupal 8's Views.

Rather, you can use the solution in Drupal 7 views contextual filters taxonomy name where you can use the **Validator**, *Taxonomy Term*, instead of *PHP Code*, with the *Term name converted to Term ID* filter.
> 2 votes

---
Tags: 7, views
---


title: How add query to EntityListBuilder

text:
# Question
Title: How add query to EntityListBuilder
I want to add a query to filter my entity list table.

```
class CommandesLignesEntityListBuilder extends EntityListBuilder {

  use LinkGeneratorTrait;

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['id'] = $this->t('ID');
    $header['produit'] = $this->t('Produit');
    $header['quantite'] = $this->t('Quantité');
    $header['prixHT'] = $this->t('Prix HT');
    $header['TVA'] = $this->t('TVA');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\boutique\Entity\CommandesLignesEntity */
    $row['id'] = $entity->id();
    $row['produit'] =$entity->getProduit();
    $row['quantite'] =$entity->getQTE();
    $row['prixHT'] =$entity->getPrixHT();
    $row['TVA'] =$entity->getTVA();

    return $row + parent::buildRow($entity);
  }

}

```

This show me all lines. How can I filter this with a query? For example, how can I get only lines with price greater or equal to 100?

i would like a permanent query for this `EntityListBuilder` sub-class.

# Answer
If someone is looking for the same, this is how i use filter on my entityListBuilder :

I override the method getEntityIds for build my logic :

```
   protected function getEntityIds() {
        $query = $this->getStorage()->getQuery()
            ->sort($this->entityType->getKey('id'))
            ->condition('commandes_id',1,'=');

        if ($this->limit) {
            $query->pager($this->limit);
        }
        return $query->execute();
    }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {

    $header = array(
        'id' => array(
            'data' => $this->t('N° produit'),
            'class' => array(RESPONSIVE_PRIORITY_LOW),
        ),
        'nom' => array(
            'data' => $this->t('Nom'),
        ),

        'quantite' => array(
            'data' => $this->t('Quantité'),
        ),

        'prixHT' => array(
            'data' => $this->t('Prix HT'),
        ),

        'tva' => array(
            'data' => $this->t('TVA'),
        ),

    );

    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\boutique\Entity\CommandesLignesEntity */
    $row['id'] = $entity->id();
    $row['produit'] =$entity->getProduit();
    $row['quantite'] =$entity->getQTE();
    $row['prixHT'] =$entity->getPrixHT();
    $row['TVA'] =$entity->getTVA();

    return $row + parent::buildRow($entity);
  }

```
> 5 votes

# Answer
Although not exactly a duplicate of How to make EntityListBuilder sortable? it is essentially the same answer as Berdir wrote,

> You'd have to implement the query logic yourself.

For instance, BlockListBuilder overrides getEntityIds to add a condition on the `theme` key.

However as Berdir also notes,

> For content entities, I would strongly recommend to rely on the views integration instead. List builders are limited in functionality and mostly useful for config entities only.
> 4 votes

---
Tags: 8, entities
---


title: Field template for display mode

text:
# Question
Title: Field template for display mode
I have a template for my field: `field--field-category.html.twig`. Is there a way to override this for a specific Display Mode? A have a mode called `teaser block`. I tried `field--teaser-block--field-category.html.twig` as well as a couple of other formats.

I know I can modify how the field is output in `node--teaser-block.html.twig` but I'd like to do it at the field template level.

# Answer
> 15 votes
For the field template there is by default no suggestion with the specific display mode.

You can add this suggestion in a hook:

```
function MYTHEME_theme_suggestions_field_alter(&$suggestions, $variables) {
  $suggestions[] = 'field__' .
    $variables['element']['#field_name'] . '__' .
    $variables['element']['#view_mode'];
}

```

Put this into MYTHEME.theme in the theme directory.

---
Tags: theming, 8
---


title: Drupal 8 MVC: is there a Model?

text:
# Question
Title: Drupal 8 MVC: is there a Model?
Coming from a Drupal background, I am quite thrilled at the idea of working with drupal 8 and symfony proper OOP and MVC practice. Right now I I am building a module with a service and a controller and I am at a loss regarding where to put my data fetching logic (that should be used by both). Understanding MVC policy I should put it in some kind of "model" structure but I can't find anything about that in Drupal documentation (sadly a bit lacking at the moment). So what is the Drupal way for this?

# Answer
Your data-fetching logic should be in its own service(s).

Symfony and by extension Drupal are not traditional implementations of the MVC architecture as there's no separate Model layer, like for instance in CodeIgniter.

One of the most important features in Symfony and Drupal are services, which are (or should be :p ) independent and reusable implementations of various functionalities.

So if you want data-fetching logic, then you can create your own service that does that and use that service in your controller, instead of polluting it with the queries (entity queries or otherwise).

I'll leave with a comment from Fabien Potencier (the creator of Symfony):

"It's up to you to create your model by hand or use any other tool, like an ORM" \[...\]I don't like MVC because that's not how the web works. Symfony2 is an HTTP framework; it is a Request/Response framework."

This statement might be debatable, but what I want to show here is the intent behind the choice of leaving out a well defined Model layer.
> 5 votes

---
Tags: 8
---


# Question
Title: Which hook occurs last before rendering the exposed filter widgets?
I'm trying to edit the variables that go from Views into the form array editted by `hook_form_alter()` and the tpl file `views-exposed-form.tpl.php`. Specifically, I'm trying to use the contents of `$view->exposed_input` for form theming, without resorting to using `$view = views_get_current_view();`

I've tried working my way up the order of execution defined here:

> * hook\_views\_pre\_view
> * hook\_views\_pre\_build
> * hook\_views\_post\_build
> * hook\_views\_pre\_execute
> * hook\_views\_post\_execute
> * hook\_views\_pre\_render
> * hook\_views\_post\_render

...but I'm stuck. At `hook_views_pre_render()`, `$view->exposed_widgets` gives me already-rendered HTML, so it's clearly too late, but the earlier ones don't give me anything at all.

Based on How to choose between all the views hooks?, I've tried using a preprocess hook based on the tpl file name, like `hook_preprocess_views_exposed_form()`, but the view isn't in scope here, I'm looking for the last views hook before this where I can find data from the view to these variables.

What I want to do, is take the contents of `$view->exposed_input`, and pass it through to the exposed form `tpl` file so that I can add a facet-like summary of current filters to my view. Which is the Views hook where I can do this?

I'm using Better Exposed Filters module, so if there are any hooks or tricks specific to that,they'd be welcome.

# Answer
> 1 votes
You can do what you need by adding a custom property to your form array via form alter:

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

  // get the related view
  $view = $form_state['view'];

  // get the exposed_input and store it into a custom property
  $form['#exposed_input'] = $view->exposed_input;

}

```

The form array is directly available as a variable in your `views-exposed-form.tpl.php`, try adding the following to the end of that tpl file:

```
<pre><?php print_r($form['#exposed_input']); ?></pre>

```

Hope this helps!

---
Tags: 7, views
---


title: AngularJS implementation

text:
# Question
Title: AngularJS implementation
I'm trying to use AngularJS in Drupal 8 template. My objective is to get the power of drupal as a backend to do content query, and AngularJS as a front end to make a single one page application. I'm implementing AngularJS in drupal module with name `drupal_ng`. The complete code is in https://github.com/agungsuyono/drupal\_ng. However, I'm wondering whether my implementation is not correct. Because I didn't see the result as expected; it seemed `ng-controller` didn't work in the HTML template. The javascript controller that I wrote did not bind to the HTML template.

Here are some of the code of `drupal_ng` module. I really appreciate for any help.

`drupal_ng/drupal_ng.module`

```
    <?php
    /**
     * Implements hook_theme().
     */
    function drupal_ng_theme() {
      return array(
        'drupal_ng_view' => array(
          'template' => 'view',
          'variables' => array('title' => NULL),
        ),
      );
    }

```

`drupal_ng/drupal_ng.libraries.yml`

```
    angularjs:
      version: VERSION
      js:
        'https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js':  {type: external}

    drupal_ng:
      js:
        js/drupal_ng.js: {}
      dependencies:
        - drupal_ng/angularjs

```

`drupal_ng/src/Controller/DrupalNgController.php`

```
    <?php
    namespace Drupal\drupal_ng\Controller;

    use Drupal\Core\Controller\ControllerBase;

    class DrupalNgController extends ControllerBase {

      public function viewDrupalNg() {
        $title = t('Hello!');
        $build['myelement'] = array(
          '#theme' => 'drupal_ng_view',
          '#title' => $title,
        );
        $build['myelement']['#attached']['library'][] = 'drupal_ng/angularjs';
        $build['myelement']['#attached']['library'][] = 'drupal_ng/drupal_ng';
        return $build;
      }
    }

```

`drupal_ng/js/drupal_ng.js`

```
    var myApp = angular.module("myModule", []);

    myApp.controller("myController", function ($scope) {
      $scope.message = "This is AngularJS";
    });

```

The word "This is AngularJS" should appear in the HTML template below but it didn't.

`drupal_ng/templates/view.html.twig`

```
    <h2>{{  title }}</h2>

    <div ng-app="myModule">
      <div ng-controller="myController">
        {{ message }}
      </div>
    </div>

```

This is the screen shoot of the result in Chrome browser using AngularJS debugger. From the debugger, it seems that the message "This is AngularJS" is already there, but it didn't appear in the screen.

# Answer
> 1 votes
I would like to just comment on this, because my answer is not exactly a solution to your particular implementation, but I do not have enough reputation :/

I will just say that in my opinion your approach to the problem is wrong. Because you are loading Angular as a JS library from Drupal, you are adding lots of unnecessary overhead to your application, especially to the initial load of the page and you are defeating the purpose of using a Front-end framework.

In my experience, using a Front-end framework like Angular is a solution to completely decouple the Front-end from the Back-end. So my suggestions is just that:

Create a regular Angular application and inside that Angular app you create a sub-folder that will contain your Drupal application.

And from this point on you can use REST webservices for fetching the data from Drupal. The core Views module combined with the core REST module provides out of the box Drupal functionality for this, and in addition Symfony provides the JsonResponse class that you use for sending simple responses. ( I really recommend using the JsonResponse, because it just bypasses Drupal's entire rendering system)

This way, you have nice Back-end code that can be organized in different controllers, which will callbacks to routes exposed as REST endpoints and a completely decoupled Front-end layer that will only call a number of select REST methods on different routes.

PS: for more information on this topic, please search for the term Headless Drupal, and you will find lots of helpful info

---
Tags: 8, javascript
---


# Question
Title: Webform module issue - content type not displaying
By accident I deleted the Webform content type in my Drupal 7 installation. It was a complete accident and thought that I was deleting a different content type. I tried going through a couple of tutorials that I saw online but was unable to get the content type back. Does anyone have any ideas on how to do this?

I stumbled across this: http://www.drupalgardens.com/documentation/feature/webforms/recreate which was a small step forward, but it still doesnt work. Has this happened to anyone before? I have tried uninstalling the and re-installing the module, clearing my cashe, and running cron. Still nothing.

Can anyone provide any suggestions? I can't be the only one that this has happened to before and there has to be so sort of fix to this... Also, please note that I am a relatively new Drupal developer.

# Answer
Drupal can act funny when you start deleting things and then trying to reinstall them. Do you have access to your database?

If so uninstall webform and delete it - then head into your database and delete any webform tables that might still be hanging around.

Dont even try this without backing up your database first though incase you happen to delete anything important.

Then re-install webform.

This is a pretty drastic step and you will lose all data surrounding your webforms.

I have had to do this with other modules that have left tables behind when uninstalled and then they mess when reinstalling said modules.

Once again though if you take this route be careful what you delete.
> 1 votes

# Answer
For anyone looking, this exact same thing happened to me. It's easy to forget, but if you update a module to the latest version you need to update the DB. This is best achieved using Drush. For me, it was simply a case of running:

```
drush updb

```

All my webforms reappeared and started working correctly.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How do I alter the options in the add menu link checkbox in the node edit form?
I am hooking the node edit form with `hook_form_node_page_edit_form_alter()`. How can I alter the available options when adding a menu item for that node?

I need to only show menu items of given node ids:

```
if (isset($form['menu'])) {
  $node_ids = array(1,2,3);
  // only show those node's menu links in the options
}

```

# Answer
> 2 votes
`$form['menu']['link']['menu_parent']` is the form array select box for the menu selector widget. `$form['menu']['link']['menu_parent']['#options']` contains the key/value pairs for the menu select box.

In your given example, you can use `unset($form['menu']['link']['menu_parent']['#options']['my_uneeded_menu_id_option']);` to remove your unneeded menu items.

---
Tags: forms, 8, nodes
---


# Question
Title: Is it possible to run Drush 8 smoothly on WSL?
Can WSL be used to run Drush 8 smoothly? I am asking because Drush 8/master doesn't run smooth on a Windows machine.

Until now, I ran Drush 8/master on an Ubuntu virtual machine. I wonder if it's possible to run it on Windows 10 using WSL.

With my very basic knowledge of Operating Systems, I can't strictly determine if having Bash and Ubuntu binaries in Windows is actually enough to run Drush or if something extra which hasn't been released is needed.
I don't know also how to integrate WSL with WAMP/Xampp ,as well as with the *c:/drush* folder, or how to make some environment variable would be enough.

# Answer
> 4 votes
We haven't tried this yet. Please give it a spin, and report your results in the issue queue.

Note also that if you want the dev branch of Drush 8, you should use the `8.x` branch. The `master` branch is now Drush 9.

---
Tags: drush
---


title: View rest/page copycat

text:
# Question
Title: View rest/page copycat
In view, when I set the settings to field field1 in *Page*, the same settings apply to field1 in *Rest export*. How do I get rid of it?

I see that everything is copied. I deleted the field from *Rest export*, and it disappears also in *Page*.

# Answer
When you click on `add / remove / edit` a `field / filter / sort / contextual filter` etc.. at the very top, you need to change the **For** `All displays` to `This page (override)` so it does not affect all the other views. You only need to do this for the first time, it will remember your setting.

**Note:** `field / filter / sort / contextual filter` etc... each have individual settings.
> 2 votes

---
Tags: views, 8
---


# Question
Title: Custom template for specific vocabulary term
Hi guys i hope you can help me with this, i made a vocabulary called Colors and inside this i have the terms: red, green, blue.

I was wondering, how can i make custom templates for each term, for example, for mysite.com/colors/red i want a different template than for mysite.com/colors/blue

I saw that it's possible for nodes, but don't know if it's possible for taxonomies. How can i do this?

Edit: for Drupal 7

# Answer
> 1 votes
You can go with the following:

taxonomy-term--**\[term id\]**.tpl.php You can get the **term id number** when you hover the edit button.

---
Tags: 7, theming, taxonomy-terms
---


title: When does caching kick in?

text:
# Question
Title: When does caching kick in?
I'm trying to limit certain views on certain pages, like preventing certain articles from appearing on /node, and I'm using `hook_views_query_alter()` with `\Drupal::service('path.current')->getPath()` to figure out when to do that.

Is this going to work, or will view cache kick in before this hook can be used? How can I write my own rules into the view so that it will only cache after I've been able to add in my excludes?

# Answer
It might be a better idea to set a contextual filter on the path. You can still do some tweaking in hook\_views\_query\_alter(), if needed (you can do a lot of things with contextual filters in the ui), but at least views knows by doing that which cache contexts it has to set.
> 0 votes

---
Tags: 8, views
---


title: Leverage browser caching issue

text:
# Question
Title: Leverage browser caching issue
I added some lines in my .htaccess file, following Is it possible to leverage browser caching?, but Page speed tool still throws "Leverage browser caching error." for only images.

# Answer
> 5 votes
Read this article about Leverage Browser Caching for Images, CSS and JS.

Add these lines to your .htacess file.

```
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

```

Also you can try

```
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch>

```

---
Tags: caching, performance
---


# Question
Title: how to set default_value for list_boolean field equal to 1, not 0?
I'm using this code to add a `list_boolean` field to my user entities on D7.20. The field is added, but the default value shows up as *unchecked*, whereas I've tried to be careful with

> 'default\_value' =\> array(0 =\> array('value' =\> 1)),

to make it show up *checked*.

Can someone explain what I'm doing wrong here?

**Update**: Actually this seems fine, see explanation in answer.

```
function MYMODULE_create_user_field_binary($myField_name, $label, $desc) {
  $field = array(
   'field_name' => $myField_name,
   'module' => 'list',
  'type' => 'list_boolean',
     'settings' => array(
     'allowed_values' => array(
       0 => '0',
       1 => '1',
      ),
     'allowed_values_function' => ''
     ),
     );
  field_create_field($field);

  $field_instance = array(
      'field_name' => $myField_name,
      'entity_type' => 'user',
      'bundle' => 'user',
      'label' => t($label),
      'description' => t($desc),
      'default_value' => array(0 => array('value' => 1)),
      'widget' => array(
        'active' => 1,
        'module' => 'options',
        'settings' => array(
                'display_label' => 1,
                ),
        'type' => 'options_onoff',
       ),
      'settings' => array(
      'user_register_form' => 1,
    )
    );
  field_create_instance($field_instance);
}

```

# Answer
Actually, the behavior here is a bit weird. The box shows up *unchecked* when the field examining an existing user (e.g. when browsing `/user/1/edit` when logged in as admin), but it does show up as *checked* when browsing to `/user/register` when not logged in. So that was a little confusing.

Upon further investigation, the new field isn't populated at all for existing users, i.e. the database entries simply don't exist. So those will have to be created manually it seems -- at which point I can specify whatever value I want as the "default". In my case:

```
INSERT INTO field_data_MYFIELD
(entity_type, bundle, deleted, entity_id, revision_id,language,delta,MYFIELD_value)
SELECT 'user', 'user', 0, users.uid, users.uid, 'und', 0, 1 from users;

```
> 1 votes

# Answer
@Joe If you want the value is 1 by default, after you create your field successfully try to add this code after:

```
$query = db_select('users', 'u');
$query->fields('u', array('uid'));
$result = $query->execute();
while($record = $result->fetchAssoc()) {
   db_query("INSERT INTO {field_data_MYFIELD}
   (entity_type, bundle, deleted, entity_id, revision_id,language,delta, MYFIELD_value) VALUES('user', 'user', 0, :uid, :uid, 'und', 0, 1) ON DUPLICATE KEY UPDATE entity_type='user', bundle='user', deleted=0, entity_id=:uid, revision_id=:uid, language='und', delta=0, MYFIELD_value =1 ", array(':uid' => $record['uid']));
   $cid = 'field:user:' . $record['uid'];
   cache_clear_all($cid, 'cache_field');
}

```

Pay attention you should add {} for the table name in case there are prefix in tables, also I use `ON DUPLICATE KEY UPDATE` because if there is value before for the same user it will get updated and will not broke the code.

Also After update this value you should clear the user field cache so it will reflect in the user profile.

Last thing you should add this `hook_user_insert` to make the value 1 for the future user registrations:

```
function hook_user_insert(&$edit, $account, $category) {
  db_query("INSERT INTO {field_data_MYFIELD}
  (entity_type, bundle, deleted, entity_id, revision_id,language,delta,MYFIELD_value) VALUES('user', 'user', 0, :uid, :uid, 'und', 0, 1) ON DUPLICATE KEY UPDATE entity_type='user', bundle='user', deleted=0, entity_id=:uid, revision_id=:uid, language='und', delta=0, MYFIELD_value=1 ", array(':uid' => $account->uid));
  $cid = 'field:user:' . $account->uid;
  cache_clear_all($cid, 'cache_field');
}

```
> 0 votes

---
Tags: entities
---


# Question
Title: How to change the language of a node and all its fields and all related data?
On my multilingual site, I have a content type that is going to be user created. I want to keep it language neutral ('und').

But there already are a couple thousand nodes of that content type and they have English set as their language.

To make them language neutral, I want to write one time update function (hook\_update\_N) to change the language of the nodes **and all their fields** from 'en' to 'und'.

I am doing this by making changes directly to database (using db\_update) to the language column of `node` & related field tables. But I am afraid that I may miss something. Can I do this some other way to not miss anything.

I read somewhere that I can user `hook_node_presave` & `node_save` to do this but I am not sure how.

Also, how can I make any future nodes' language to be set default as 'und'?

# Answer
If this is just a one-time conversion, you should be able to do it with Views Bulk Operations (VBO).

Here's one way to do this that doesn't involve writing any code.

1. Install the VBO module.
2. Create a new view showing **Content** of whatever content types you need to convert. Use the **Fields** display method.
3. Add a field **Bulk operations: content**.
4. Check **Modify entity values** and select **Language**.
5. Choose **Apply**.
6. Save the view (add any other filters if necessary to limit the selection) and go to the created view page.
7. From the view page, choose the option to select all items on all pages and execute the **Modify entity values** action.
8. Choose the language and click next.

If you have an extremely large number of nodes, you may need to play around with the queuing settings so that not everything is executed at once, but I would try doing it in one pass first because hey, if it works, you're done (note: always test on a backup first!)

Source: How can I set the language of nodes in bulk to existing content when making a site multilingual? \- please upvote **that one** if you liked the solution above.

To force the default language to be undefined, in the `setting.php` file used by your site, add the following lines:

```
$conf['language_default'] = (object) array(
  'language' => 'und', 'name' => '', 'native' => '',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

```

This will force Drupal to use 'und' as the default language for all new content.
> 3 votes

# Answer
you can also use a SQL statement

```
UPDATE node SET language = 'en' WHERE language = 'und';

```
> 2 votes

---
Tags: 7, entities, i18n-l10n, nodes
---


# Question
Title: Downloads restrictions through direct URL
I am developing one feature in which user will get one pdf from my site, for this I have developed a process below,

1) user will click on the link and form open in popup

2) after submitting the form one link will be sent to his email address

3) when user clicks on the link one small process of token check will be done and he will get the file

4) second time this link will not work

This whole process is working fine here my question is I want to restrict the user to get my files when user directly hit the URL link like `www.mysite.com/files/downloads/abc.pdf`

users can only be able to download it through that link which is in Email.

Thanks for advance.

# Answer
> 0 votes
Not sure if this will help you, as I have never used it, but worth checking out:

### Unique-download

> Onetime download link is useful to create one-time download link, similar to one time login. This will be helpful to send users one time download links for e-commerce or download entities such as books, mp3 etc etc. considering them as file attachment for initial development.

# Answer
> 0 votes
My suggestion is,Don't get access direct file Url to users, Register a menu (with `hook_menu`) something like `download/%` in menu callback check accessibility also you can check where is request source(`'HTTP_REFERER'`) and etc. you finally if it authorized passed file to him with **something like** ( because you told that you are a developer, I get you a clue How to achieve this job)

```
    $attachment_location = $_SERVER["DOCUMENT_ROOT"] . "/file.zip";
    if (file_exists($attachment_location)) {

        header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
        header("Cache-Control: public"); // needed for internet explorer
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length:".filesize($attachment_location));
        header("Content-Disposition: attachment; filename=file.zip");
        readfile($attachment_location);
        die();
    } else {
        die("Error: File not found.");
    }

```

---
Tags: files, uri
---


# Question
Title: How to retrieve image URL from Media Bundle field in Twig Template
I have created a custom media bundle using the Media Entity module. Here is a screen grab of the media bundle:

I have created a Twig template `media--image.twig.html`

I am able to retrieve all of the field values via the `content` variable in Twig but I'm having difficulty retrieving the `field_image` URL.

Here is a snapshot of the output from `{{ kint(content.field_image) }}`:

How do I extract the URL? I can see a target Id, so presumably I can load the entity in the preprocess function and pass through the variable but I would've expected the full target object to be available within the Twig template?

# Answer
> 2 votes
### Image URL Formatter

> This module adds a url formatter for image field. Then you can output image url directly.

Enable the module, edit your image field, change the formatter to url.

Now `{{ content.field_image }}` will print the url instead of rendering the image.

---
Tags: theming, 8, media
---


# Question
Title: Programmatically load the contents of a Product in a particular product type
I am developing an Ecommerce site and I am using Drupal-commerce module for it. I have an issue regarding loading the contents of a product which is: **How can I programmatically get the contents of all the products in a particular product type?**

# Answer
> 0 votes
This can be done with an EntityFieldQuery:

```
<?php
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->execute();
  $nodes = node_load_multiple(array_keys($result['node']));
?>

```

# Answer
> -1 votes
This code will help you.

```
$banner_query = db_select('node','n');
$banner_query->innerJoin('field_data_field_weight','w','w.entity_id = n.nid');  // join with another table
$banner_query->fields('n',array('nid'));
$banner_query->fields('w',array('field_weight_value'));
$banner_query->condition('n.status',1,'=');
$banner_query->condition('n.type','skin_and_hair_banners','=');
$banner_query->orderBy('w.field_weight_value','ASC');
$banner_res = $banner_query->execute();

while($banner_fetch = $banner_res->fetchObject()){
    $banner_load = node_load($banner_fetch->nid);
    echo "<pre>"; print_r($banner_load)
}

```

---
Tags: commerce
---


title: Display Today's Birthday in Block

text:
# Question
Title: Display Today's Birthday in Block
I have a Content Type 'Teams' which have name as Title field, Image field and Date of birth field using Date module.

I want to display Today's birthday in block. I've tried using views but could not achieve it.

Is it possible to display in drupal. Please Help

# Answer
> 0 votes
Working with Drupal 7 and Date module, if you enable Date Views sub-module, you may create a Views block with a filter criteria based on your Date field. There, you will just have to enter a relative date (now) and filter your nodes with your birthday's dates. (i.e. Date field value is equal to : now).

Hope this helps.

---
Tags: views, datetime
---


# Question
Title: Load CSS and JS using absolute paths on select pages
I've got a page (menu callback) which serves as a template for an external service. As the HTML of the page is consumed by the external service and rewritten then served from their server, all the CSS and JS paths must be absolute. Elsewhere on my site I use relative paths via AdvAgg, but here I need to rewrite all the link elements to be of the type `file`, rather than type `external`.

How can I do this? I have tried doing a `hook_css_alter` or `hook_js_alter` and changing type to `external` and prefixing the `data` value with my site's base URL but it doesn't seem to be making my AdvAgg aggregate files absolute, their paths stay relative.

Another idea I had was iterating through all the site's CSS files and unsetting the local entries and instead calling `drupal_add_js` or `drupal_add_css` but referencing the files as `external` with an absolute path, but I don't know where I would do this.

I'm using Drupal 7 with CSS and JS aggregation turned on and with the AdvAgg module enabled.

# Answer
> 2 votes
I had a look at how the web\_widgets module was making CSS/JS paths absolute and it looks like a valid solution is just to alter `$GLOBALS['base_path']` to add the URL of my site. An easy way to do this is with `url()`:

```
  $GLOBALS['base_path'] = url('', array(
    'absolute' => TRUE,
  ));

```

---
Tags: 7, javascript
---


# Question
Title: How to alter a form base on the users' request info?
I would like to customize a form base on the users' request info in a page callback. I use `drupal_get_form` (or `node_add` for node create form) to get the renderable array, but most changes to the array here have no effect.

I know that we usually use `hook_form_alter`, but it seems not suit here.

I would like to hide/set a field, change a field's title/options etc. based on the query parameters or page arguments.

Do we have any methods to get the "raw describing form" and then modify and render it?

# Answer
> 1 votes
You should definitely use `hook_form_alter()` for that - no need to go a different route, it'll just make things harder for no benefit. Doing things the standard way your code could be as simple as:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo_form' && isset($_GET['bar'])) {
    $form['baz']['#access'] = FALSE;
  }
}

```

---
Tags: 7, forms
---


# Question
Title: Filtering on node whose user ID is equal to the current user
In Drupal 6 you can have a filter `node.uid = current user`. How do you do this in Drupal 7?

# Answer
You need to add the filter as a "context" (Advanced) where you can supply a default argument. If you context is for a user, like the node author, then you can select stuff like id of logged in user.
> 27 votes

# Answer
You need to edit your view, go to the Advanced column (far right) and add a new relationship.

You will specifically need to add the "Content: Author" relationship.

Next, under "Filters" you will need to add the "User: Current" filter.

Now you should be able to filter content owned by the currently logged in user.
> 22 votes

# Answer
you can add simply

"User: Current" in "Filter" criteria.
> -2 votes

---
Tags: 7, views
---


# Question
Title: Please help for the moment no way to include chemistry in Mathjax
I'm using the Mathjax Module on drupal 7. All working pretty good but when i'm trying to add the chemistry js, it was not the same !! I tried to enable it without success. I have read a lot of documentation, i forget where but i read : if you use "\ce", mhchem will be loaded automaticly.

Apparently it's not the case :

My custom configuration :

```
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ['\\(','\\)'] ],
processEscapes: true
},
showProcessingMessages: false,
messageStyle: 'none'
});

```

Tring to change

```
extensions: ["tex2jax.js"],

```

to

```
extensions: ["tex2jax.js","mhchem.js"],

```

without success and a lot of other test.

No way to force the js to be loaded. May be there is a trick ?

thanks for helping

# Answer
> 2 votes
You need to add the mhchem.js extension to another part of your configuration, namely the TeX part.
Here is a configuration that worked correctly for me (a modification of the 'default' custom configuration on a clean Drupal7/MathJax environment:

```
MathJax.Hub.Config({
  extensions: ['tex2jax.js'],
  jax: ['input/TeX','output/HTML-CSS'],
  TeX: {
    extensions: ['mhchem.js'],
  },
  tex2jax: {
    inlineMath: [ ['$','$'], ['\\(','\\)'] ],
    processEscapes: true,
    processClass: 'tex2jax',
    ignoreClass: 'html'
  },
  showProcessingMessages: false,
  messageStyle: 'none'
});

```

My content looked like this:

```
$2 + 2 = 4$

$\ce{H2O}$

```

and gave me this as an output:

Hope this helps!

---
Tags: 7, javascript
---


# Question
Title: Send 'compare product' action to Google Analytics
I am having a products page in my site. In that I have a comparison functionality.

Now I want to send data to google analytics so that Admin can later on check which products were compared. I have captured the products I.E. on which products checkbox the user clicked and store that array of products in a jquery variable.

Now I want to send this variable in `ga` function but I am not able to do soo. Can anybody help me out with it or some other solution?

# Answer
You can use GA Push module

> GA Push offers an API to enqueue informations that are sent GA servers, and three submodules to track browser events (using jQuery), form validation errors and log exceptions.

So, you can use the API to send an event to Google Analytics when user adds a producto to the comparison.

For example, you can use the page view function and send virtual page views for each compared product:

```
$push = array(
  'location' => '/comparision/product/' . $nid,
  'page' => 'comparison',
  'title' => 'Product ' . $product_name . ' comparison',
);

ga_push_add_pageview($push);

```

This code should called when you detect that a product is being compared.

**Disclaimer**: I'm one of the developers of this module.
> 0 votes

---
Tags: javascript, google-analytics
---


# Question
Title: Default value to 'datetime' field in form loaded from the database
I want to display the datetime field on my Drupal 8 form with some date loaded from the database, but the front end always shows empty fields as if no data has been provided. I tried several combinations to default\_value field, but none of them are showing any thing.

The code I am using is the following.

```
$form['dateopening'] = array(
  '#type' => 'datetime',
  '#title' => t('Opening Date'),
  '#default_value'=> date('Y-m-d H:i:s', strtotime($dateFromDB)),
);

```

Why doesn't it set the default value as expected?

# Answer
The response is in this thread : on stackoverflow

```
$form['valid_dt'] = array(
    '#type' => 'datetime',
    '#default_value' => DrupalDateTime::createFromTimestamp($data->valid_dt),
    '#title' => $this->t('Valid'),
);

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to solve the strange behavior of content node in view
I found one strange behaviour in views. Like if I click on a node title of a view table, it will take me to node page. If I click edit and save the content will save faster.

But in the view, which has an edit field link, if I click on the edit link, and try to save the same node it takes several minutes to save.

Can anyone know why is this strange behaviour is happening and how to resolve it?

# Answer
Saving is perceived slower because after saving (with or without overlay) it automatically redirects you to the last page you were at. Since your view takes longer to load than a single node page, saving is perceived slower.

In conclusion, the actual saving takes the same amount of time, the difference is the view page load versus the node page load.
> 1 votes

# Answer
The problem in view was select list filter condition and i just removed it and it fixed my problem :)

Thanks for support @NoSssweat and @Neograph734
> 0 votes

---
Tags: views
---


# Question
Title: Authcache settings for blocks or views in panels
I am setting up Authcache ESI and Varnish on Drupal 7. My site has panel pages that incorporate personalized blocks and views. Authcache allows caching parameters to be specified for blocks or views, and also on panels.

What is the recommended approach in this case? For example if I am placing a view in a panel page, should I:

* Specify Authcache settings for the view only?
* Specify Authcache settings for the view panel within the panel page only?
* Specify Authcache settings for both the view and the panel -- and if I specify settings for both, which takes precedence?

# Answer
> 1 votes
Note that each fragment which is loaded from the server results in an additional request. Hence it is beneficial to minimize the amount of fragments and it follows that you should pack all your personalized panes into one request if possible.

Note also that you only can load panels/panes if you place them with page manager. Neither Panelizer nor Mini Panels are supported at the moment (see these issues)

You should not nest authcache fragments. If you do then, the outer most wins. Authcache will not add any fragment placeholders inside fragments loaded via Ajax/ESI.

---
Tags: 7, caching
---


title: CSRF token not working (access denied)

text:
# Question
Title: CSRF token not working (access denied)
I can get CSRF token to be generated on particular route by putting \_crsf\_token in a routing file, but on visiting that route , I keep getting an *Access Denied* error.

Removing CSRF token line from the routing file gives me back access to the access instantly.

What could be possibly wrong?

I have tried to make sense of Menu Callback and CSRF but don't think it is related to my problem.

# Answer
@Berdir Applying patch #14 on this page has solved the problem! Thank you very much!

Twig template variables containing result of Drupal::url() and Drupal:l:() don't bubble up their cacheability and attachment metadata (e.g. token placeholder)
> 1 votes

---
Tags: 8, csrf
---


# Question
Title: How do I add an extra css class to my Views rows?
I have created a view and it gives me lots of css classes for the rows of my unformatted list:

```
<div class="views-row views-row-1 views-row-odd views-row-first">

```

...but not enough...I need a class for the content type or field name also, something like:

```
<div class="views-row views-row-1 views-row-odd views-row-first views-row-article">

```

I can see in the style options for the page: '**Row class** The class to provide on each row. You may use field tokens...'.

Is this what I need? Do I have a 'field token' for content types? Thanks

# Answer
> 14 votes
1. Add the field "Content: Type"
2. Check "output machine name"
3. Check "exclude from display" for the type field
4. For the row class, enter \[type\]

# Answer
> 3 votes
Just another way on how to add classes to views rows.

```
/**
 * Implements template_preprocess_views_view_unformatted.
 */
function my_theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  if ($view->name == 'my_view' && $view->current_display == 'my_view_display')) {
    $classes_array = $vars['classes_array'];
    foreach($classes_array as $key => $classes) {
      $vars['classes_array'][$key] = $classes . ' my-class';
    }
  }
}

```

**Note** that the preprocess function indicates the View's selected format.

Preprocessors functions list for the basic Views' formats.

# Answer
> 1 votes
Yes, you could put it in there, and if you have included the content type in your row as a field, you could access it here via (most probably) `[type]`.

Just click on the little gear widget on a field in your View and then look at the rewriting section and it will give you all the "replacement patterns" you have to work with.

# Answer
> 1 votes
You need to add a class name for the row ... So you can give the name of the class where ever you are using the view.

For eg:- You want to add the view on to a page. then go to **structure** -\> **pages** -\> **select your page** -\> **edit it** -\> **now go to Content part of the page** -\> **go to the region where you want to put the view** -\> **go for ADD content** -\> **Select the view** -\> **now click on customise button of the view** -\> **select CSS properties**

There it will ask you for the **CSS ID** and **CSS class**.. Add the class that you wanna add and go on playing around with CSS stuff...

Cheers.....

# Answer
> 0 votes
Other way to add css to views row is to create the views template.

In my case I needed some class for bootstrap, (col-md-3, etc...).

In Views 3, go to "Advanced", Theme "Information", look at the name possibility and create a new template in you module folder with the recommended name. Just copy past from the current template, (in views press the template to view it).

Now you can add class for your needs.

---
Tags: views
---


# Question
Title: How to get the front page title in page.html.twig?
I'm trying to use the page title in my theme's `page.html.twig`. On normal pages, `{{ node.label }}` does the job, but that doesn't work on the front page. There, `node` is `NULL`, presumably because the font page is a view rather than a "real" page.

I have tried to dump all the available variables on `page.html.twig` using `kint`, but it seems that none of them contains the page title. Other questions discuss a similar matter, but either only for normal pages or for getting the title from PHP (and not from within a TWIG template).

I'm looking for an approach that works in any template, although `page.html.twig` is most important for me right now. It should also take a global title override into account. The ideal solution would also work on normal pages (i.e. not the front page).

TL;DR: I'm looking for a template variable/function `X` so that `{{ X }}` is the current page title, no matter whether I'm on the front page or on any other page.

# Answer
You should really try using the blocks for this, but here's how to do what you asked:

```
function YOUR_THEME_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
  $variables['current_page_title'] = $page_title;
}

```

This code should go in `YOUR_THEME.theme` file. You can use it then in `page.html.twig` this way:

```
{{ current_page_title }}

```

See this for more information.
> 12 votes

# Answer
```
{{ page['#title'] }}

```

It seems to work on view, node and term pages.
> 5 votes

---
Tags: 8
---


title: Field as Block column not showing

text:
# Question
Title: Field as Block column not showing
I installed the Field as Block plugin without problems, but when I go to Structure \> Content Types \> Basic Page \> Manage Display, I still don't see the "Display as block" checkbox.

I tried googling but did not find anything else that what was written on the plugin page. What am I doing wrong? This plugin would really help me.

# Answer
> 0 votes
After some more research, I found a post by nicholasThompson who was having the same problem and found out the solution:

> Ahh you have to place the "Content field" block and configure it!

This solved my issue.

---
Tags: entities, blocks, plugins
---


title: Alternative for hook_node_submit()

text:
# Question
Title: Alternative for hook_node_submit()
What is an alternative to `hook_node_submit()` for Drupal 8?

# Answer
> 1 votes
This is what the related change record has to say:

> Instead of the submit hook, an #entity\_builder callback should be used to map form values to an entity (or better; use a field with a widget). If the submit hook is not about mapping values to the entity, register a custom #submit callback on the submit button and put your logic there.

And here are the related code samples:

```
// Implements HOOK_form_BASE_FORM_ID_alter
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // For entity builders.
  $form['#entity_builders'][] = 'mymodule_node_builder';
  // For submit callbacks.
  $form['actions']['submit']['#submit'][] = 'mymodule_node_form_submit';
}

function mymodule_node_builder($entity_type, NodeInterface $node, &$form, FormStateInterface $form_state) {
  $parent = $form_state->getValue('menu', 'parent');
  if ($parent) {
    list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $parent);
  }
}

function mymodule_node_form_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  mymodule_do_something($node);
}

```

---
Tags: nodes, 8
---


# Question
Title: How to store Ajax Return value into variable after clicking the Submit button
I have created form with fields of State and City. After selecting the state appropriate city records will be loaded into city field till now working fine but after clicking the submit button I am not able to store city value into variable called $data1. Please guide me how to get it city value

```
function form_test_form($form,&$form_submit)
{
$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
  );

}

```

Ajax Function

```
 function _ajaxfunction($form, $form_state)

    {

$key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  foreach ($city_results as $city_record)
{
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
}

    $form['city_element_wrapper']['city']= array(
        '#type' => 'select',
        '#title' => t('District'),
        '#options' => $options_city,
        '#required' => TRUE,);

    return $form['city_element_wrapper'];
    }

```

Now I am trying to store the value of what I have selected in City into $data1 variable but I am not able to store it, Please guide me how to store

```
function form_test_custom_form_submit($form, $form_state){
    $data1 = $form_state['values']['city_element_wrapper']['city'];
}

```

# Answer
> 0 votes
You need to move the `$form['city']` form input creation into your `form_test_form` function otherwise it's considered tampering with the form, so the values will get taken out.

```
function form_test_form($form,&$form_submit) {
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
    ),
  );

  $form['city_element_wrapper'] = array(
    '#prefix' => '<div id="divaroundseconddropdown">',
    '#suffix' => '</div>',
  );

  // If there's a "State" value set, then we create the City dropdown
  if (isset($form_state['values']['state1']) && !empty($form_state['values']['state1'])) {
    $form['city_element_wrapper']['city'] = array(
      '#type' => 'select',
      '#title' => t('District'),
      '#options' => $options_city,
      '#required' => TRUE,
    );
  }

  return $form;
}

```

Now the callback becomes a simple return of the relevant element:

```
function _ajaxfunction($form, $form_state) {
  return $form['city_element_wrapper'];
}

```

Finally check the values of $form\_state\['values'\] in your submit handler:

```
function form_test_custom_form_submit($form, $form_state){
  var_dump($form_state['values']);
  die();
}

```

---
Tags: forms
---


# Question
Title: how do I make JavaScript run after the page is loaded
With Drupal 8, I am adding JavaScript to my theme in the libraries.yml so that I can put lift segments into the data layer. But it is running before the body is loaded, and the data layer is being overwritten.

How can I make this script run after the body load?

# Answer
> 11 votes
Did you use `$(document).ready` or better `Drupal.behaviors`?

This is from drupal docs:

> When using jQuery it is standard for a large majority of situations to wrap almost all code inside the $(document).ready() function, like this:
>
> ```
> $(document).ready(function () {
>   // Do some fancy stuff.
> });
>
> ```
>
> This ensures that our code will only run after the DOM has loaded and all elements are available. However with Drupal there is an alternate better method; using the functionality of Drupal.behaviors and once(). If used properly this will ensure that your code runs both on normal page loads and when data is loaded by AJAX. The Drupal.behaviors object is itself a property of the Drupal object, and when we want our module/theme to add new jQuery behaviors, the best method is to simply extend this object.
>
> A really basic example:
>
> ```
> Drupal.behaviors.myBehavior = {
>   attach: function (context, settings) {
>     // Using once() to apply the myCustomBehaviour effect when you want to do just run one function.
>     $(context).find('input.myCustomBehavior').once('myCustomBehavior').addClass('processed');
>     // ... left out the more complex examples
>   }
> };
>
> ```

Quote from JavaScript API in Drupal 8

---
Tags: 8, javascript
---


# Question
Title: Unable to access Admin panel of Drupal site at Localhost, migrated from server
There is one my online website in Drupal. I did a Setup on Localhost for Testing Purpose. But unable to get it working correctly.

* Using WAMP
* Used Migrate tool.

### I tried:

1. Deleted .htaccess file.
2. Base URL set.
3. Tried to access all possible Admin URL, sitename.com/admin .
4. Clean URL disabled on localhost.

### Problem:

1. All pages working fine that means FRONT END IS FINE. But while accessing BACKEND for user or admin is just not working. It says PAGE NOT FOUND.
2. When I use admin URL as following: sitename.com/?q=admin = It redirects to `https://localhost/sitename/?q=toboggan/denied&destination=admin`

I'm not sure how it is adding `https`. Page says: unable to connect If I use `sitename.com/admin` it says: "*Page not found*".

Please suggest the solution.

# Answer
This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing `?q=user` or `?q=admin`. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

```
RewriteRule . index.php [L]

```

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that browser you are able to login, then it's probably a cookie problem (in your original browser).

If http redirects to https you might have a module that does this or it might be a rule in .htaccess see if you can comment out the rule in htaccess or disable any relevant module with `drush dis MODULENAME`.

If none of these suggestions help, then re-edit your question by adding more details about which modifications to your '.htaccess file, httpd.conf, etc' you already tried (and didn't work).
> 1 votes

---
Tags: 7
---


# Question
Title: How do i create an item list where the item has a mixture of links and text
If I add the following to my controller, the first item in the list displays correctly, but once I concatinate in text, the links are all escaped.

```
 $basic_items[] = \Drupal::l('Basic example',Url::fromRoute('flot_examples.basic_usage'));
$basic_items[] = \Drupal::l('Different graph types', Url::fromRoute('flot_examples.series_types')) .
" and " .
\Drupal::l('simple categories/textual data', Url::fromRoute('flot_examples.categories'));

$output['basic'] = [
  '#title' => 'Basic Usage',
  '#theme' => 'item_list',
  '#items' => $basic_items,
];

```

I know the `l()` function in deprecated, and I should be using:

```
$basic_items[] = ['#type' => 'link', '#title' => 'Basic Example', '#url' => Url::fromRoute('flot_examples.basic_usage')];

```

instead, but I can't figure out how to get that to work either.

# Answer
> 1 votes
A simpler method is to use the t() function:

```
$basic_items[] = \Drupal::l('Basic example', Url::fromRoute('flot_examples.basic_usage'));
$string = '<a href=":options_page">Setting various options</a> and <a href=":annotating_page">annotating a chart</a>';
$options = [
  ':options_page' => Url::fromRoute('flot_examples.basic_options')->toString(),
  ':annotating_page' => Url::fromRoute('flot_examples.annotating')->toString(),
];
$basic_items[] = t($string, $options);

$output['basic'] = [
  '#title' => 'Basic Usage',
  '#theme' => 'item_list',
  '#items' => $basic_items
];

```

# Answer
> 0 votes
You can have multiple render arrays in each item.

```
$basic_items[] = \Drupal::l('Basic example', Url::fromRoute('flot_examples.basic_usage'));

$basic_items[] = [
  'graph' => \Drupal::l('Different graph types', Url::fromRoute('flot_examples.series_types')),
  'separate' => " and ",
  'data' => \Drupal::l('simple categories/textual data', Url::fromRoute('flot_examples.categories'))
];

$output['basic'] = [
  '#title' => 'Basic Usage',
  '#theme' => 'item_list',
  '#items' => $basic_items
];

```

P.S. You can use the \Drupal\Core\Link class to create links instead of the l function.

# Answer
> 0 votes
Maybe there's a better way, but what I did was to change the twig template for the default item\_list to include the case where the item is an array.

```
<li{{ item.attributes }}>{% if item.value is iterable %}{% for snip in item.value %}{{ snip }}{% endfor %}{% else %}{{ item.value }}{% endif %}</li>

```

---
Tags: 8
---


# Question
Title: How to implement a reputation based system with badges in Drupal similar to StackExchange sites?
Earning badges on StackExchange is, well, fun. But aside from that it promotes quality interaction from users and helps weed out spam (I have never seen a spam post on the site).

I have a community website with about 500 active users, but the spammers are starting to become more prolific.

I would like a way to make the site more engaging while promoting the same quality of interactivity.

How would you recommend to put in a good **reputation** system, as well as a **goal achievement** system?

# Answer
> 17 votes
There's the User Points module and the User Badges module, though the 7.x version of User Badges is not suitable for production yet (as of June 4, 2012).

Thankfully, User Points integrates with the Rules module, which allows you to greatly customize the ways users gain (or possibly lose) points.

There's also a collection of contributed modules for userpoints of varying stability. You can certainly set up some amazing stuff with these modules, but make sure to carefully test your implementation-- though the modules are well written and fairly stable, there's still a lot that can go wrong so make sure to verify everything works properly.

# Answer
> 11 votes
For the badges, there is the Achievements module.

> The Achievements module offers the ability to create achievements and badges similar to systems seen on Xbox 360, Playstation 3, Foursquare, Gowalla, GetGlue, and more. For a Drupal site, this could mean commenting a certain number of times, starting a forum topic, visiting the site every day of the week, or anything else that can be tracked and coded.

# Answer
> 2 votes
Your question really consists of 2 parts, i.e. about how to implement:

* a **reputation system**, which is like an evaluation by multiple users about a specific user.
* a **goals achievement system**, which is like rewarding a user after completing various tasks, challenges, etc.

Read on for more details about how to implement each of both systems.

# Goals achievement system

There are typically 2 modules you can choose from for such kind of system, i.e:

1. The Achievements module, as suggested in another answer already. This module relies heavily on ***custom coding*** to handle many of the functions.
2. The Goals module (Disclosure: I'm the maintainer of it), which can be used to incentivize anything on your site, such as voting, sharing content, creating relationships, etc.

**Goals** and **Tasks** are implemented using fieldable entities. Some examples of tasks to be completed could be:

* Log in to the site once per day for three consecutive days.
    * Post a number of nodes of selected content types.
    * Make a Friend connection on the site.
    * Etc.

You can customize Goals via "Manage Fields" and/or "Manage display". Everything can be done with ***site building*** features only (no custom code involved), though hooks are available to integrate it in custom coding also. So the Goals module is built around using the admin interface configuration. Plus, goals and tasks within the Goals module are fieldable entities, so you have the flexibility to add additional fields and incorporate these entities into Views. Using the `Goals Extras` sub-module it integrates with the User Points module also.

Head over to the Goals video which includes:

* a general introduction to the module.
    * a demonstration to install, configure and use it.
    * samples of how it uses the Rules modules to do its magic (i.e. to track the progress of a user to achieve the various goals).

# Reputation system

By using the Answers module (Disclosure: I'm a (co-)maintainer of it) you can "*put in a good reputation system*" (as in your question). Here are some details about it (from its project page):

> Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details. Visit its demo site for a demonstration (in read only mode for anonymous users) of Views based lists of:

The ***"core" Answers*** module enables the content types **Question** and **Answer**, whereas Answers are displayed below the Question they relate to. These 2 content types are fiedable, you can manage their displays, etc.

Use its sub-modules to enable selected functionality (based on a site's requirements), i.e.:

* ***Answers Best Answer***, which allows for marking any of the answers to a specific question as the best (accepted) answer (to display the blue check marks to the left of each answer, and which is replaced by a green checkmark when an answer is marked as the best answer).
* ***Answers Theme***, which transforms the (rather boring) vanilla display of a *Question* (and its related *Answers* below it), into a way more attractive look-and-feel. Such as the orange bubble that is added around the question (to better highlight it).
* ***Answers Notification***, to allow logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
* ***Answers Voting***, to implement a system to upvote or downvote either Questions and/or Answers (which uses the Rate module).
* ***Answers Userpoints***, to increase or decrease "*reputation points*" (which uses the Userpoints module) on events such as up- or down-voting on a question or answer, or marking an Answer as the "*Best Answer*".

Quite a lot of its "business logic" is implemented via all sorts of configurable rules (using the Rules module). As an example, if you don't agree with the out-of-the-box rules about how much "userpoints" are granted to an upvoted (or downvoted) question (or answer), you just use the Rules UI to tune the amount of such points to your requirements. E.g.: should downvoting questions really be free (i.e: Should the downvoter loose any points in doing so?).

For the sake of completeness, below is a rule (in Rules export format), which is used to grant '+15' points to the author of an *Answer*, together with '+2' points for the user who marks that answer as accepted (= the author of the *Question*), whereas marking it as such is done by flagging that Answer as 'Best answer' (using the Flag module):

```
{ "rules_flag_answers_best_answer" : {
    "LABEL" : "flag_answers_best_answer",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "userpoints_rules", "flag" ],
    "ON" : { "flag_flagged_best_answer" : [] },
    "IF" : [
      { "NOT data_is" : { "data" : [ "flagging-user" ], "value" : [ "flagged-node:author" ] } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "flagged-node:author" ],
          "points" : "15",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "addPoints",
          "display" : 1,
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "flagging-user" ],
          "points" : "2",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "addPoints",
          "display" : 1,
          "moderate" : "default"
        }
      }
    ]
  }
}

```

---
Tags: 7
---


# Question
Title: How can add Contact-Us-form in custom place of page.html.twig file?
I need to add contact-us form in the custom place of page.html.twig file in my themplate, I want to add some code like belove:

```
<div class="Contact-Us">
    <p>Contact Us</p>
    <form action="#" method="post">
        <input type="text" name="email" placeholder="Email" />
        <textarea name="message" placeholder="Message"></textarea>
        <button>Send</button>
    </form>
</div>

```

# Answer
You can do this in four steps:

1. Build a contact form.
2. Put this contact form in a block with Contact Block.
3. In block layout put the block in a region -\> `myregion`.
4. Place the region in page.html.twig -\> `{{ page.myregion }}`
> 1 votes

---
Tags: theming, forms, 8, emails
---


# Question
Title: Community website - User rating based on votes in Node + Statistics
I am planning to build a community based website where users would be able to rate the content uploaded by others. I have gone through many blog posts and Stack Exchange questions too, but what I want could not be answered in any of it.

What I got:

* User Points module: To associate points to author of a node (content) if the node (content) is up-voted or downn-voted - This, as I understand, can be done using Rules.
* Rate module or Fivestar module \- To provide rating mechanism for a particular node (content) provided by the author.

I would want to extract statistics like:

* Highest rated article for a period of time - Like 1 month or between 'from' and 'to' date etc.
* User who has accumulated highest points within a period of time
* Etc.

This basically lets me evaluate and find out the most 'liked' or 'popular' user or most 'liked' or 'popular' article within a period of time to award them some goodies.

So, how can I achieve this?

I have done some homework, stumbled upon some threads but could not find what exactly I needed:

# Answer
> 1 votes
I haven't used **User Points Module** but for **fivestar module** or module based on **Voting api** you can create a view of content and add a relationship with **vote results** and you will get the aggregation you need **i.e average/total number/total score** for that node then you can add a `Vote results :Timestamp` filter to get the results in between dates. You can add sort and limit to display the way you want.

# Answer
> 1 votes
If you're looking for a working module example with user voting, ratings and statistics, you may want to have a look at the Answers module (which enables the content types **Question** and **Answer**, whereas Answers are displayed below the Question they relate to). Together with (at least) 2 of its submodules, i.e.:

* ***Answers Voting***, to implement a system to upvote or downvote either Questions and/or Answers (which uses the Rate module).
* ***Answers Userpoints***, to increase or decrease "*reputation points*" (which uses the Userpoints module) on events such as up- or down-voting on a question or answer, or marking an Answer as the "*Best Answer*".

Head over to its project page for more details.

To extract nodes related statistics, just use the Views module, similar to what is shown on the Answers demo site (in read only mode for anonymous users). It includes Views based lists of:

Refer to my answer to "How to get the node ids of answers for a question in Drupal Services (REST)?" for more details about these views.

Quite a lot of the "business logic" of the Answers module is implemented via all sorts of configurable rules (using the Rules module). As an example, if you don't agree with the out-of-the-box rules about how much "userpoints" are granted to an upvoted (or downvoted) question (or answer), you just use the Rules UI to tune the amount of such points to your requirements.

Disclosure: I'm a (co-)maintainer of the Answers module.

---
Tags: 7, nodes, rating
---


# Question
Title: Change icon class in "Add to cart" button
I am using Drupal 7, Ubercart, and Bootstrap. The default ***Add to cart*** button looks like this:

```
<button id="edit-submit-270" class="node-add-to-cart btn btn-success form-submit" value="Add to cart" name="op" type="submit">
  <span class="icon glyphicon glyphicon-plus" aria-hidden="true"></span>
  Add to cart
</button>

```

How can I change the `<span>` class from glyphicon-plus to glyphicon-shopping-cart?

# Answer
Simple Solution is achieving it with simple Jquery line

```
$('span.icon.glyphicon.glyphicon-plus').removeClass('glyphicon-plus').addClass('glyphicon-shopping-cart');

```
> 0 votes

# Answer
Give it another class in your template.php file, and CSS does the rest

```
/**
 * @param $variables
*/
function yourtheme_preprocess_button(&$variables) {
  $variables['element']['#attributes']['class'] = array();
  $variables['element']['#attributes']['class'][] = 'btn';
  if (stristr($variables['element']['#value'], 'Add to cart') !== FALSE) {
    $variables['element']['#attributes']['class'][] = 'btn-cart';
  }
}

```
> 0 votes

---
Tags: theming
---


title: Use View as root homepage handler

text:
# Question
Title: Use View as root homepage handler
In Drupal 7 I'm trying to accomplish the following:

`1) www.domain.com = ViewA (All posts)
3) www.domain.com/muffins = ViewA (Posts tagged with "Muffin" taxonomy)
4) www.domain.com/cookies = ViewA (Posts tagged with "Cookie" taxonomy)
5) www.domain.com/... = ViewA (Posts tagged with ... taxonomy)`

I have a view, listing posts, with only one contextual Filter of "Category" (my vocabulary containing the required taxonomy), which works when tested in views.

I can set `ViewA` as the homepage, satisfying `1)` but subsequent pages `2),3),4)` are **not** handled by `ViewA`. Instead they return `page not found` as Drupal isn't aware that `ViewA` can handle the requests.

I know I can create a second page view `ViewB` with an additional url path segment like this:

`www.domain.com/recipe/muffins = ViewB (Posts tagged with "Muffin" taxonomy)`

But then all of my content has to live one "level" down under `/recipe` — which is not ideal.

Also, since the taxonomy grows as more recipes are added, hard-coding menu paths in a module is no a solution... or is it?

Any suggestions would be helpful.

# Answer
I don't think this is possible without modification to Drupal core's routing. When you specify a Views page as the frontpage (e.g. **/frontpage** when you override the default Frontpage view), you're telling Drupal to route all www.example.com requests to that path (e.g. **www.example.com/frontpage**).

If you mandate that a required contextual filter (e.g. **/frontpage/%**), that path component isn't "copied over" (e.g. **www.example.com/cookies** doesn't route to **www.example.com/fronpage/cookies**). Nor can you add a views page with the root path **/**. If this was possible, you'd then have to deal with the problem of overlapping paths (e.g. should **/admin** be handled by `system_admin_menu_block_page()` or by your view?).

Instead of trying to fight Drupal's routing system, you'd be better off trying to hook into the alias system. For example, a module invocating `hook_taxonomy_term_insert()`/`hook_taxonomy_term_update()` could add a new alias for each term item you wish to shortcut to your view (e.g. aliasing **/cookies** to **/frontpage/cookies**).
> 0 votes

---
Tags: views, uri
---


# Question
Title: Is it normal and expected that I cannot use the weight text fields to set weight?
I am attempting to use the weight text fields in Drupal taxonomy to set weights. My expectation is that I can use the weight field to set the weight. My question, therefore is, is it normal and expected that I cannot use the weight text fields to set weight? If this is the normal, expected behavior, then I would proposition that this does not smoothly align with the user experience.

I have recorded the issue here to clearly demonstrate what the problem is.

PS: I am fairly new to Drupal, so I am not sure if this is a bug, but it does seem fairly illogical. If this is a bug, where and how do I report it?

# Answer
> 1 votes
> The issue summary is: Drupal seems unable to save changes to taxonomy weight.

Taxonomy weights are saved according to the taxonomy hierarchy rules as pointed out by @RaisinBranCrunch and @IvanJaros. However based on comments in those answers, the real issue seems to be

> Drupal does not give immediate feedback when changing taxonomy weight of children to non-valid values when using visible weights.

This is probably a behavioral bug or feature request that you could post on drupal.org as part of the Drupal project. It would most likely go under either the taxonomy component/module. Although the weight UI system is used in various other places in Drupal core.

It is not a major or critical bug because it does not cause data loss, render the system inoperable, is a security issue, or have significant repercussions (documented here https://www.drupal.org/core/issue-priority).

Whether the bug is accepted or not is another matter. It could be more valuable or important to not kick the user back based on an user input mistake of understanding weight ordering and children.

It may be better to classify this as a feature request because the intent is to change the behavior of the user interface for a different user experience. It is also possible to alter this user experience using Drupal's form alter hook to provide such validation and require explicit knowledge of weight ordering when not using drag and drop.

For more information about how to report an issue to Drupal core, read How to create a good issue and start at the Drupal core issue queue.

# Answer
> 1 votes
Animal and Fruit are on the same hierarchical level, so they are sorted like so:

Animal (7) Fruit (11)

Fruits are sorted like so:

Apple (0) Orange (1) Banana (2)

You can't tell Drupal to ignore Hierarchy. Fruit is the parent of Apple, so it will always be listed above it to represent that it is the parent taxonomy.

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