title: PDO Exception error

text:
# Question
Title: PDO Exception error
I am not sure why this started to show last few days. It only happens when i try to edit content type (admin/structure/types/content\_type\_name) or when i want to add new content type.

Going back in browser and clearing cache moves the error away and i am able to edit or create content but the error still shows on the bottom of the page.
I can work for few minutes without interuption but then again it starts showing.

Website is live, but i have not noticed that it happens to users (anonymous or loged in), or that it breaks any part the website except adding/editing content type. (manage fields, manage display always work without errors, its just the edit content page).

> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 148926721856f8ef83caa1a9.09501995 ) in lock\_release\_all() (line 269 of /var/www/html/includes/lock.inc).

# Answer
> 1 votes
All you need to increase to max allowed packet. You are using CentOS, which need to configure as below within command line.

```
nano /etc/my.cnf
max_allowed_packet = 32M
service mysqld restart

```

# Answer
> 0 votes
Drupal doesn't connect to MySQL until the first query is sent. A request almost never takes more than a second, and usually less than half a second. If your MySQL server is timing out in that amount of time it means MySQL is misconfigured.

Please verify that you have a reasonable wait\_timeout. I suspect simply increasing that will solve the problem.

This has to do with maximum allowed packet size in MySQL. To solve, this edit my.cnf: max\_allowed\_packet=100M and restart MySQL.

---
Tags: 7
---


# Question
Title: How do I remove a validation handler from a form?
I am using the *Invite by e-mail* module, which has its own `hook_form_alter()` with a validation handler. I wish to remove its validation handler and use my own validation handler.

# Answer
Use hook\_form\_alter() to change the `$form['#validate']` to be your custom validate handler.

```
function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
   $form['#validate'] = array();
   $form['#validate'][] = 'my_custom_validation';
  }
}

```
> 1 votes

# Answer
Use hook\_form\_alter() to change the $form\['#validate'\] to be your custom validate handler. But if you don't want to run module's validate and submit handler then first unset that specific function from $form\['#validate'\] and $form\['#submit'\] array.

```
function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    unset($form['#submit'][array_search('module_submit_handler',$form['#submit'])]);
    unset($form['#submit'][array_search('module_validate_handler',$form['#validate'])]);
    $form['#validate'][] = 'my_custom_validation';
    $form['#submit'][] = 'my_custom_submit';
  }

```

}

One more thing to remember please set your custom module weight higher so that your form alter will run after the contrib module.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to calculate the user's average rating on all his/her nodes with Fivestar?
On my website, users can rate each other's nodes via a Fivestar field called *Stars* in a comment. I'd now like to calculate the overall average score of a user. That means, I'd like to display the user's average score for all his/her nodes.

For example. Let's say a user created 2 nodes: *Node 1* and *Node 2*. Some people rated his content:

* Scores of *Node 1*: 4/5, 5/5, 3/5
* Scores of *Node 2*: 4/5, 4/5

The overall average would then be (4+5+3+4+4)/5=4.

Preferably, this result should also be displayed as stars.

How can I do that?

---

**Edit 1:** Working with the Computed Field module seems to be a general idea to solve this matter. It looks fine to me and I think it's best to store the users' average score in a user field, in order to make it easily accessable. (Working with a view is also fine.) I'm planning to display the average score on their profile page, but perhaps I'm going to use it elsewhere on the website in the future too.

Can you please help me with (a scetch) of the code I'm supposed to use?

---

**Edit 2:** I created a user field called *Gemiddelde* and pasted @Thomas4019's code in my custom module *hiderating* (the module's title refers to an earlier question), but it gave me the following error:

> * Warning: Missing argument 5 for computed\_field\_field\_gemiddelde\_display(), called in C:\wamp\www\mysite\sites\all\modules\computed\_field\computed\_field.module on line 341 and defined in computed\_field\_field\_gemiddelde\_display()(line 24 of
> C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).
> * Notice: Undefined variable: entity in computed\_field\_field\_gemiddelde\_display() (line 30 of C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).
> * Notice: Trying to get property of non-object in computed\_field\_field\_gemiddelde\_display() (line 30 of C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).

The *Gemiddelde* field in the view on my profile page has the following value:

```
<div class="fivestar-basic"><div class="fivestar-widget-static fivestar-widget-static-vote fivestar-widget-static-5 clearfix"><div class="star star-1 star-odd star-first"><span class="off">0</span></div><div class="star star-2 star-even"><span class="off"></span></div><div class="star star-3 star-odd"><span class="off"></span></div><div class="star star-4 star-even"><span class="off"></span></div><div class="star star-5 star-odd star-last"><span class="off"></span></div></div></div><div class="fivestar-summary fivestar-summary-average-count"><span class="empty">No votes yet</span></div>

```

---

**Edit 3:** After reinstalling the Computed Field module and clearing caches, the error messages are gone, but the *Gemiddelde* field in my view still displays the following CSS code:

```
<div class="fivestar-basic"><div class="fivestar-widget-static fivestar-widget-static-vote fivestar-widget-static-5 clearfix"><div class="star star-1 star-odd star-first"><span class="on">3</span></div><div class="star star-2 star-even"><span class="on"></span></div><div class="star star-3 star-odd"><span class="on"></span></div><div class="star star-4 star-even"><span class="off"></span></div><div class="star star-5 star-odd star-last"><span class="off"></span></div></div></div><div class="fivestar-summary fivestar-summary-average-count"><span class="average-rating">Average: <span >3</span></span> <span class="total-votes">(<span>1</span> vote)</span></div>

```

What went wrong?

# Answer
I know that something like this can be done with computed field. It will require some PHP code though. See some discussion here

Here's what you need to do:

1. Install Computed Field and Fivestar
2. Go to **admin/config/people/accounts/fields** and create a computed field on the user entity type. In my case I named it "field\_computed\_rating". On the settings form for the field make sure the checkbox "Store value in the database" is **unchecked**.
3. Click on "Manage Display" for the content type you created the field on. Then make sure the format for that field is set to "Unsanitized".
4. (if you already have a custom module you can skip this step) In your code base within sites/all/modules, create a new folder titled **fivestar\_user\_aggregate**. Within that folder you will need to create fivestar\_user\_aggregate.info with the following contents.

```
name = Fivestar User Aggregate
description = Assign users an aggregate rating based on all their nodes
core = 7.x
package = Custom

```
5. Add this custom php function to your module file or create fivestar\_user\_aggregate.module within fivestar\_user\_aggregate with the following contents. If you named your field differently then you will need to modify the function name accordingly.

```
<?php

function computed_field_field_computed_rating_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
    $result = db_query("SELECT n.uid, n.nid, vote1.value AS count, vote2.value AS average FROM {node} n
INNER JOIN {votingapi_cache} vote1 ON n.nid = vote1.entity_id
AND vote1.function =  'COUNT'
INNER JOIN {votingapi_cache} vote2 ON n.nid = vote2.entity_id
AND vote2.function =  'average'
WHERE n.uid = :uid", array(':uid' => $entity->uid));

    $rating_count = 0;
    $rating_total = 0;

    $nodes = $result->fetchAll();
    foreach ($nodes as $node) {
        $rating_count += $node->count;
        $rating_total += $node->average * $node->count;
    }

    if ($rating_total == 0) {
        $weighted = 0;
    } else {
        $weighted = $rating_total / $rating_count;
    }

    $variables = array(
        "rating" => $weighted,
        "average_rating" => $weighted,
        "votes"  => $rating_count,
        "stars" => 5
    );
    $variables["widget"]["name"] = "basic";
    $variables["widget"]["css"] = "sites/all/modules/fivestar/widgets/basic/basic.css";
    drupal_add_css(drupal_get_path('module', 'fivestar') .'/css/fivestar.css');
    return theme('fivestar_static', $variables) . theme('fivestar_summary', $variables);
}

```
6. Enjoy! You should now see a weighted average of all a user's node's ratings on their page.
> 9 votes

# Answer
Jeroen,

Firstly, where do you want this info to show up? If this is a user page, go ahead with Computed Field, else, if this is something like a listing page, or a view, then you can use Views PHP. In both cases, you will have to code to fetch the results. You will have to fetch the nodes of the user, sum up all the ratings on all the nodes, and then take an average. This would be your result.
> 2 votes

# Answer
Did you try Views Aggregation ? I think with a little work it can do what you need.
> 0 votes

# Answer
Yet another approach, as per the "Working with a view is also fine" in the question:

1. Create some view that contains the relevant data, filters, sorting, etc.
2. Use the Views\_calc module to have the average displayed below the views result.

Here is a typical screenprint of such table:

Refer to my answer to the question about "How can I show average votes of fivestar nodes?" for more details on this.

Disclosure: I'm a **co**-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

# Answer
I have recently stumbled upon this problem again and I solved it with Views Aggregation myself in a couple of minutes without thinking about this old question. I would like to add my solution as an alternative answer for people who are not (yet) into programming. The View is set as follows:

* Create a new unsorted View that displays comments.
* Check that there is already a relation to the content, i.e. the node that received the comment, in the advanced settings.
* Add a contextual filter to the author uid of the content. In my case, I display the View on the user pages, so I set the default value to the uid in the URL.
* Next, enable Aggregation in the *Other* section of the advanced settings.
* Add the field *Stars*, display the value as stars and change the aggregation settings to average (type) and rating (group).
* Add additional filters if necessary. For example, I filtered on approved comments with a non-zero vote on published nodes of a specific type.

Done! If you are reading this as a Drupal beginner, you can interpret this story as a kind of reassurance: don't give up and you will make enormous progressions, even if you don't believe it yet.
> 0 votes

---
Tags: 7, rating
---


title: TB Mega Menu Problem Reordering Columns

text:
# Question
Title: TB Mega Menu Problem Reordering Columns
I have a site using tb mega menu. The only problem I have with it is it will not allow me to place a column to the left of another column. It just groups the two with the one I want to move always at the bottom. This wouldn't be much a problem if I could reorder the structure menu and see it affected on tb mega menu pages. The only solution I found was deleting the database row of that menu and starting over.

# Answer
I had this problem and it was due to weights I had on the menu links as well as the actual ordering in the menu admin page. I re-ordered them in the normal menu settings page, and then I was able to order them properly in the TB Mega Menu settings page.
> 1 votes

---
Tags: routes
---


# Question
Title: unable to migrate site from one server to another
I have to migrate as site from one server to another. I exported the databaseusing MySqladmin which I also used to import the db on the new server, I copied all files over but I keep getting errors like:
**Fatal error: require\_once(): Failed opening required '/home/quaaout/public\_html/drupal-7.43/sites/all/modules/rules/modules/events.inc' (include\_path='.:/usr/lib/php:/usr/local/lib/php') in /home/quaaout/public\_html/drupal-7.43/sites/all/modules/rules/rules.module on line 9**

so I tried loading the latest drupal 7 core 7.43 but I get exactly the same. I then tried to erase that one module `rules` but I got the error for the next, I deleted and the same error would popup for modules `rules`, `apps`, `contentanalysis`,`kwresearch` (which I deleted one after the other) but after the last one I stopped and thought there must be another way to get rid of this error, but how? Please advise! Thanks!

**EDIT1**

And then since I updated my db version, I tried to call `update.php` but that won't work i.e. the server returns nothing, I get an empty page in firefox and Chrome says: **The page isn’t working**

**EDIT2**

What I also tried is: **wget --ftp-user=USER --ftp-password=PASS -r ftp://ftp.myolddomain.com/ .** to download the complete site the new host but I still get
**Fatal error: require\_once(): Failed opening required '/home/quaaout/public\_html/ftp.quaaoutlodge.com/sites/all/modules/rules/modules/events.inc' (include\_path='.:/usr/lib/php:/usr/local/lib/php') in /home/quaaout/public\_html/ftp.quaaoutlodge.com/sites/all/modules/rules/rules.module on line 9** when trying to access the page through the new domain...

**EDIT 3**

Okay, seems like the initial `wget` command didn not catch all the files and I had to re-copy the `sites/all/modules/` and `sites/all/themes`. Seems like I've caught everything now. I'm not sure why this would not have worked initially. *Manoj Bisht, please return and add your comment as answer to get the credit you deserve, after all, I only started checking for the files within the modules & themes directories after you told me to...*

# Answer
> 0 votes
Have you tried backup migrate?

http://drupal.org/project/backup\_migrate

Make sure you have a vanilla drupal install working perfectly, then copy the sites/all folder from your first server, enable backup migrate and then restore the backup from the first server.

Basically, it will be a lot easier to troubleshoot if you're on a vanilla install and backup migrate is perfect for this.

---
Tags: 7, migrations
---


# Question
Title: Using Bootstrap theme and anonymous user, ajax form submit results in "call to undefined function bootstrap_form_process"
**Context**

We have a subtheme based on the Bootstrap theme and we're rendering a form inside of a modal. The submit button uses an ajax callback to handle form submission.

**Problem**

When logged in as an admin in Chrome, the form submits perfectly.

When logged out (accessing the site as an anonymous user) in Chrome, submitting the form results in a 500 Server error.

The server logs are reporting "Call to undefined function bootstrap\_form\_process()".

**Research**

It seems that this might be related (https://www.drupal.org/node/2156371) but I'm not sure what to do to fix it.

I have a hard time following issue discussions on drupal.org. I have a decent amount of Drupal knowledge, but still struggle to figure out what they are saying.

**Things I've Tried**

Some people in the thread linked above got around the issue by setting max\_input\_vars to 2000, so I gave that a shot. It didn't help.

I thought maybe I needed to increase it even more, so I set it to 5000, but still no change. I then switched it back to the default 1000.

I also tried adding "drupal\_static\_reset('element\_info');" to my theme's template.php file, but it didn't seem to do anything.

# Answer
> 0 votes
This is similar to https://www.drupal.org/node/2369635, i.e. you need to include `/path/to/bootstrap/includes/process.inc` in your codebase. The easiest way IMHO is in a `hook_init()` somewhere.

---
Tags: 7, forms, ajax, theming
---


# Question
Title: Why is THEME_preprocess_node called twice?
I have an extremely simple test case a template.php file for the THEME theme, which contains the following:

```
THEME_preprocess_node( &$variable ) {
    msg( "Preprocess Node " . $variables[ 'vid' ] );
}

```

The `msg` function simples writes to a file (I was trying to abstract away all possible influence from other factors to sort out this issue).

If I clear the `msg` log and refresh a page, I always get two entries:

```
Preprocess Node 32
Preprocess Node 2 // <-- The front page

```

I have tried changing the front page through configuration and the log always reflects this. So if I change the front page to 3, I will get 3 in the log along with the actual node number.

It seems that `THEME_preprocess_node` is getting called twice, once for the actual node and once for the front page node.

Any reason why this would be happening?

# Answer
hook\_preprocess\_node is called for each and every rendered node
> 1 votes

# Answer
hook\_preprocess\_node will be called every time a render($content) method is invoked for a given node (say, in node.tpl.php). Based on the symptom above, my guess is there is a block or reference to the front page node, that is being output each page. I expect that it would be the "teaser" mode of the front page as well, but that's not clear from this debug. I ran into a similar issue today where preprocess\_node was **not** being called at all, and it ended up being due to the fact that there was a custom page TPL in place that was not using any render() methods, but was instead using custom code to generate output.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Drush and Composer installed but I'm getting errors
Trying to use any drush command I get an error saying autoload.php won't load. It's in the vendor folder which is in the web root where I'm pretty sure it's supposed to be. It also has chmod +x permissions. If I put in php composer.phar I get the version and all that so yes it is there. If I run composer drupal-update (which composer manager would like for me to do) bash says composer: command not found. Is composer the only way to do this library thing in drupal 8? It seems a lot more problematic and less user friendly than just putting a library directory in the sites folder.

# Answer
If you are getting the error *-bash: composer: command not found*, that means Composer is not in the `PATH` Bash is using.

To use the *Composer Manager* module, you don't necessarily need Drush. I use it without Drush, but I run the following commands after I install the module.

```
cd <root directory of Drupal 8>
php modules/composer_manager/scripts/init.php

```

If all works fine, you will see the following output:

> Composer Manager has been successfully initialized.

In this way, the *Composer Manager* module adds a new command inside the composer.json file used by Drupal. In fact, after running those command, you will notice the following lines inside the composer.json file.

```
"drupal-rebuild": "Drupal\\composer_manager\\Composer\\Command::rebuild",
"drupal-update": "Drupal\\composer_manager\\Composer\\Command::update"

```

In the case you didn't execute those commands, or they failed for any reason, running `composer drupal-update` would return the following error:

> \[Symfony\Component\Console\Exception\CommandNotFoundException\]
> Command "drupal-update" is not defined.

If you are downloading modules using Drush, just do as you normally do. The *Composer Manager* module will hook into Drush and do its task when a new module is downloaded.
> 1 votes

---
Tags: 8, drush, composer
---


title: Multi-Step Registration Profile2

text:
# Question
Title: Multi-Step Registration Profile2
Drupal 7
Modules: Profile2 Registration Path, Multi-Step Registration, Profile2, Logintoboggan.

I have a Drupal 7 site that has three roles. User, Advertiser, Auctioneer, each with their own Profile2 fields. Currently when a user clicks register ALL the profile2 types show up on the page. The functionality I'm after is, depending on which role they select after filling out username, password and role, the appropriate profile2 type is shown to the user to finish before finishing the user account creation OR something similar. Is this possible?

Thanks for any guidance.

# Answer
The Profile2 Registration Path module allows you to create different registration forms to register users using different roles and different profile types.
> 1 votes

---
Tags: users
---


# Question
Title: How do I programmatically export all webform submissions into a single csv? (multiple webforms)
I have hundreds of webforms created from a single webform template. How do I programmatically export all webform submissions into a single csv? Note that this is not possible via views out of the box. One would have to create \[webform\_mysql\_views.\] (Combine Webforms to export multiple form results in a single CSV) This doesn't seem efficient.

# Answer
As per your comment that you are interested in "an alternative to creating such CSV file programmatically": have a look at the Forena module (without using Views. Forena can do exactly what you're asking for (so no need for "programmatically").

As an example, create a custom "data block" (which is just an SQL statement) that fits your needs, to retrieve the webform data that you're interested in. Here is a (basic) example that I sometimes use for some testing:

```
SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

```

Then create a Forena "report" that uses this data block, and make sure that within "document types" you enable the "CSV" option. Here is the (basic) layout of such report to illustrate the idea:

```
<body>
<div id="webform_submissions_data_block" class="FrxTable" frx:block="drupal_cust/webform_submissions_data">
    <table>
      <thead>
        <tr>
          <th>node</th>
          <th>submission</th>
          <th>component</th>
          <th>fieldvalue</th>
        </tr>
      </thead>
      <tbody>
        <tr id="webform_submissions_data" frx:foreach="*">
          <td>{node}</td>
          <td>{submission}</td>
          <td>{component}</td>
          <td>{fieldvalue}</td></tr>
      </tbody>
    </table>
  </div>
</body>

```

After you saved the report and browse it, you'll have a "CSV"-hyperlink (upper right of the report). Just use that link and ... voilà, there is your CSV file (in this case with 4 columns, since that is what in my (basic) report I asked for.

If this makes sense, head of to the Community documentation of Forena to get you going (which includes pointers to video tutorials). Or use the documentation that comes with Forena.

Of course, building the appropriate SQL statement to perfectly fit your needs is going to be crucial. But apart from that, it's just basic usage of Forena.

Disclosure: I'm a co-maintainer of Forena.
> 1 votes

---
Tags: webforms, importing-exporting
---


# Question
Title: Display Nested Content Type References In D8
I would like to know how best to manage a content type having 1:n parent-child relations in Drupal 8.

I need to display a view of the relationships. Although in theory unlimited I anticipate the depth will not exceed 4 generations.

As shown in my diagram below, C is a child of B. D & E are children of C etc:

```
-instanceA
-instanceB
--instanceC
---instanceD
---instanceE
----instanceF
...

```

I presume entity reference is the way to go. From my limited D6/7 experience I prefer having a parent ref on a child (having unlimited child inline entity references can seem confusing to my less web savvy users - a single parent from a drop down select is clearer). Although I am happy to be convinced otherwise if other factors outweigh this.

This stack exchange answer suggests the Views Tree module might have worked but it does not seem to be porting to D8.

I think waiting for the Views Field View module to be ported to D8 might provide a solution but this seems overkill.

This is such a basic need I suspect in my lack of experience I am missing a simple solution. Any suggestions how best to approach this appreciated.

# Answer
> 1 votes
Yes I was missing an obvious answer. As provided by steeph on drupal forum.

Have an entity reference (unlimited) that points at the children. In the content type teaser display include the children field and set that to display the teaser view. You then have a recursive view of all descendants in teaser view mode. Obviously you could create a custom view mode if needed but this is the principle.

Create a view which at the top level only displays views which have no parent (using relationship and filter). Make sure it is set to display content\>teaser and you should be seeing a flat list of instances. Use css to add a margin-left to your list-items and job done.

---
Tags: views, 8, entities
---


# Question
Title: Getting an error on field module when saving a node
When I'm saving a node using `node_save`, I'm getting the following fatal error:

Fatal error: Maximum execution time of 30 seconds exceeded in /data/www/www.example.com/htdocs/modules/field/field.attach.inc on line 664

This is not happening every time `node_save` is called, only for a certain new node and I can't find anything strange about the fields I'm populating. Any clue?

# Answer
I would check cck fields to find which one causes the issue first and go from there, the error message related to 'fetch entities from cache, if applicable'.
> 0 votes

---
Tags: nodes, entities
---


# Question
Title: Block view for only the images uploaded to the image field of the current node
I am working in Drupal 8.

I have a content type defined with an image field. For each page of that content type, I upload one or more images for its image field.

I want to create a block view in Views that presents images in a grid. How do I filter the block view so that the only images displayed are the ones for the image field of the current node? The block will be placed in the block layout for this content type. It is easy to create a view that creates a grid with images from all pages of this content type. I am stumped on how to filter the view so only images for the current mode are displayed.

# Answer
Got it figured out. In Views, goto Advanced,Contextual Filters. Select Node ID. Select "Provide default value". Select "Content ID from URL".

To only display this field only using Views, goto Content Type, and under Manage Display, set the both the label and format for the image field to hidden.
> 0 votes

---
Tags: views, blocks, media
---


# Question
Title: How to manage multisite themes from master Drupal installation
I have Drupal 8 multisite to benefit from a single codebase. **Also they share the same database**. How can I change themes of all the other sites from my main domain/site?

Parent and child domain :

```
- mainsite.com
-- childsite1.com
-- childsite2.com
-- childsite3.com

```

# Answer
> 1 votes
The README.txt file in Drupal's /themes directory states:

> …the sites/your\_site\_name/themes directory pattern may be used to restrict themes to a specific site instance.

For instance, you might have:

```
- sites/all/themes/m1
- sites/childsite1.com/themes/c1
- sites/childsite2.com/themes/c2
- sites/childsite3.com/themes/c3

```

---
Tags: 8, multi-sites
---


title: Views filter by type and taxonomy

text:
# Question
Title: Views filter by type and taxonomy
I have two types of content every one with two taxonomies:

TYPE A with Taxonomy 1 (multiple)

TYPE B with Taxonomy 2 (multiple)

Now I created a view with 3 filters exposed:

Node type: A or B or both

Taxonomy 1

Taxonomy 2

Now if I choose, all the nodes A and B with the term x (taxonomy 1) and the term y (taxonomy 2) does not return nothing.

I tried to change the AND and OR, but nothing comes out from the query.

Do you think it is possible a query like this with views filters?

# Answer
Ok,

Yes it's possible with group filters, but I discovered that there is a bug when grouped value contains an array (multiple items).

A patch fixed the problem: http://drupal.org/node/2224601#comment-8627337
> 0 votes

# Answer
Use group filters

First views filters group

```
Type A AND taxonomy 1

```

Condition between groups

```
OR

```

Second views filters group

```
Type B AND taxonomy 2

```
> 0 votes

---
Tags: database, views
---


title: Drupal 8 maintenance page theming

text:
# Question
Title: Drupal 8 maintenance page theming
I want to customize the maintenance page in Drupal 8.

How do I theme it?

# Answer
> 15 votes
In Drupal 8, **settings.php** contains the following line:

```
# $settings['maintenance_theme'] = 'bartik';

```

First, uncomment this setting and change "bartik" to the machine name of your custom theme.

Next, copy the core maintenance template **core/modules/system/templates/maintenance-page.html.twig** to **templates/maintenance-page.html.twig** in your custom theme directory.

Lastly, flush the Drupal cache to enable your new maintenance page template. If you need alter the template's variables, you can add the `MYTHEME_preprocess_maintenance_page()` to your \*.theme file.

---
Tags: theming, 8, maintenance-mode
---


# Question
Title: Different urls for front page depending on language
I'm using entity translation module and want to have different urls for front page in accordance with languages.

For example: front-eng
fr/front-page-for-france
pt/front-page-for-portugal
etc.

# Answer
> 0 votes
Use this code in your template file then you can page accoding to your choose language

```
  function yourtheme_preprocess_page(&$vars) {
        if ($vars['is_front']) {
            $langcode = $GLOBALS['language']->language;

            if ($langcode == "en") {
                drupal_goto('home');
            } elseif ($langcode == "fr") {
                drupal_goto('front-page-for-france pt');
            }
        }

```

---
Tags: 7
---


# Question
Title: Filter taxonomy term view by referenced taxonomy term
Using two taxonomies.

Fruit:

`Banana
Orange
Blueberry
Strawberry
Lemon`

Fruit taxonomy has a term reference to the color taxonomy

Color:

`Red
Orange
Yellow
Blue
Purple
Green`

Created a view using the built in taxonomy term view in a content pane::

Fields Taxonomy term: Fruit Color \[this is excluded from display\]

Taxonomy term: Name

Filter criteria Taxonomy vocabulary: Machine name (= Fruit)

Relationships Taxonomy term: Content using Fruit

\[Configure Relationship: Taxonomy term: Content using Fruit Relate each Content with a Fruit set to the term. Require this relationship\]

View Output::

`Red
 Strawberry`

`Orange
 Orange`

`Yellow
 Banana
 Lemon`

`Blue
 Blueberry`

I would like to add a contextual filter to this view that takes the Color taxonomy name from the url and only shows the fruit for that color.

color/red would only show:

`Red
 Strawberry`

color/yellow would only show:

`Yellow
 Banana
 Lemon`

I'm stuck on how to add the contextual filter. I've tried taxonomy term name with validation set to change the term name to id. I also tried the fruit\_color field with validation set to change the term name to id.

Should the term name/fruit\_color field be configured differently? Do I need to add another relationship?

> Additional info: The view displays taxonomy terms. The result set is empty when I try adding a contextual filter. The relationship field should only show Fruit terms that have been used at least once to tag content.

# Answer
> 0 votes
To answer you question: No, it shouldn't need to be configured differently; it should work the way you describe. Here is a screenshot of my configuration (following your description) that works as you would expect (you can see the contextual filter in the background set to 'yellow'):

Perhaps you can spot some tiny deviation from your config here.
Good luck in any case!

---
Tags: 7, views
---


# Question
Title: How to embed images in MIME mail system?
How to progamatically embed images in mail?
I am using mime and mail system module

Here is my code:

```
function send_rush_me_mail($node){
  $dataArr = array();
  $dataArr['field_name'] = $node->field_name['und'][0]['value'];
  $dataArr['field_email'] = $node->field_email['und'][0]['value'];
  $body = location_beacon_email_body_string('rush_me', $dataArr);
  $params = array(
    'body' => $body,
    'subject' => 'Auto Response for Ask Me',
  );

  drupal_mail('register', 'register', $dataArr['field_email'], language_default(), $params, 'example@domain.com', TRUE);
  watchdog('Ask me mail', print_r($params,1));
}

```

# Answer
With the help of Rules module and filtered HTML text format allowing **img** tag in the format you could send HTML emails with images.

Here is a summary of the required steps:

1. Enable the required modules, eg using Drush like so: `drush dl rules entity mimemail mailsystem`
2. Configure the **MAIL SYSTEM SETTINGS** choosing **MimeMailSystem** the **Site-wide default** and **Mime Mail module class** from `admin/config/system/mailsystem`
3. Set the text format to be filtered html or the format that allows img tag from `admin/config/system/mimemail`
4. Use Rules to send html e-mails.

For a more detailed tutorial, refer to How to Send HTML Emails in Drupal 7 using Rules.
> 1 votes

# Answer
you need to install 2 modules to make your email working and in mime mail config set the E-mail format to full html to send images

Mail System

mail

Mime Mail

mime

you can use the example module from drupal offical

example

in this u will find example\_email module and in that module u will get all the source code and check the below link for the explanation on each function EmailExample

This will help you, send emails pragmatically i have used the same and i am able to sent the email.
> 0 votes

---
Tags: emails
---


# Question
Title: Registration message after saving password for first time
I am using standard way of user registration. User enters default fields + some extra text fields, gets email, clicks link in email.
Back to website, he clicks one time login in button and enters password.
After saving password message pops up, which makes no sense.

"You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password. The changes have been saved."

Why is message "Please change your password" here ?

# Answer
You can use "String Overrides" module to achieve this. As this message sets using drupal\_set\_message function and this function stores these messages in session. So the best way to change this message is use of string overrides module. This module can easily replace anything that's passed through t() function. So you just need to put whole string that you want to replace with your own string.
> 1 votes

---
Tags: 7, users
---


# Question
Title: How do I get the UID in user-profile.tpl.php?
I'm trying to make a custom view mode for user profiles. In my `user-profile--myviewmode.tpl.php`, I want to get the UID for the user whose profile it is.

The help text for `user-profile.tpl.php` states:

> $user\_profile: An array of profile items. Use render() to print them. Field variables: for each field instance attached to the user a corresponding variable is defined; e.g., $account-\>field\_example has a variable $field\_example defined. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language, e.g. $account-\>field\_example\['en'\], thus overriding any language negotiation rule that was previously applied.

I used `dpm()` to print out the array `$user_profile`, but I couldn't find the UID anywhere.

Then I tried:

```
global $user;
$uid = $user->uid;

```

However, this doesn't work because when I use Views to render the view mode, it gives me the UID of the logged-in user, not the user whose profile is being rendered.

Is there a way to get the UID in `user-profile.tpl.php`? I need to get the UID to build some custom links based on it.

# Answer
I found the uid under the elements \>\> #account object:

```
$elements['#account']->uid;

```

Good luck!
> 5 votes

---
Tags: 7, theming
---


# Question
Title: How to print the products (fields) on a node using a custom display
I am new to Drupal and I've been trying to create a site to function as a lending inventory. I have so far created a new content type with my fields (describing product details) which the user fills with data every time he adds content(adds a product). I want to be able to print the saved result of the add content page to a document but not in the display that it has as a row of the table view. To be more specific I would like to print every product and its details in a customized way so that the details are displayed in two columns and above them a text of lending agreement can be put.

I am sorry in advance for the complexity of the description Does anyone have an idea?

Thank you

# Answer
> 0 votes
You could use Display Suite and do the following:

* Enable DS and DU UI modules
* Create a new View mode for nodes, e.g. "Receipt"
* For your content type, go to "Manage Display" \> "Custom display settings" and activate the "Receipt" view mode for your content type
* Now you should have, besides "Default" and "Teaser", the "Receipt" view mode available under "Manage Display" for your content type
    + Available directly under admin/structure/types/manage/PRODUCT\_CONTENT\_TYPE/display/receipt
* You can now select the layout that suits you under "Layout for PRODUCT\_CONTENT\_TYPE in receipt", for example "Two column stacked"
* You can use the available regions of that layout to lay the details out between the two columns
* For the "Lending agreement" text, you would need to use a DS Code field, available under "Custom fields" \> "Add a code field". You can enter your Lending agreement text in there, and then place that field in your header area.

That should be enough to cover the configuration of your custom display.

In order to get some URL access to that view, per product, you could use the View Mode Page module. Once you install it, you get a new configuration tab in your content type's "Manage Display" page, called "View mode pages". There you can do the following:

* Enter a URL patter under "URL pattern", e.g. 'node/%/receipt'

Save that configuration, clear all caches, and try to enter a URL for an available node, e.g. node/123/receipt
This should load that node using the view mode you configured above.

---
Tags: 7, nodes
---


# Question
Title: Is there a way to quickly disable caching for all views? (for dev work)
Is there a variable/other way to quickly disable all views caching when working on a dev server? I have a lot of views which have different caching settings, and there are times when I am doing testing that I would just like to turn all views caching off, similar to the way that you can turn CSS/JS aggregation off.

I found that the Views module itself has its own cache in the documentation, but this is not the caching for individual views-- and the caching for each individual view is what I want to turn off.

# Answer
> 1 votes
If You ask about drupal 7 can use

`cache_clear_all('*', 'cache_views', TRUE);`

in template file.

Refreshing page that is using the file will clear all views cache.

---
Tags: views, caching
---


# Question
Title: How to add Javascript tag in the head tag?
I want to add Javascript in Head Tag. I found an answer in How to add script to \<head\>? but it doesn't work for a theme.

```
function mytheme_preprocess_page(&$vars, $hook) {
  drupal_set_html_head('<script type="text/javascript" src="http://use.typekit.com/12345.js"></script>');
  $vars['head'] .= drupal_get_html_head();
}

```

Can I add JavaScript code in the `<head>` tag through page.tpl.php?

# Answer
> 5 votes
Here's the link to the full document on module developing aspect which I assume is not your main goal, there are some ways that you wanna skip for now, my suggestion is depending on the theme you are using, is to do it via `.info` file. the easiest and common way.

This link is a very good guide for adding js files to omega subtheme, you may find it useful.

## **The .info file approach:**

first open your theme's .info file that it should be something like `YOURTHEMENAME.info`

if you are using a subtheme there must be already some js files in there, you can find them and use them as an example.

what you wanna do is to add your js file like this:

```
scripts[] = somescript.js

```

this way the js file will be added to head of your website, remember after each time of editing a .info file you need to clear cache.

## **Adding External js to your site:**

In your theme's template.php file use drupal\_add\_js() to the page preprocess method (or an equivalent preprocess).

```
function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}

```

**Edit**: also with the extra info you just provided regarding **using functions in the header** you need to make a custom tpl file, locate the file that has `<head>` tag in your theme, it most likely be `html.tpl.php` (depends on the base theme you are using) if you couldnt find it you can copy it from `modules/system/html.tpl.php` and paste it into your theme's folder. edit the name of your file as this: `html--node--id.tpl.php` like `html--node--1.tpl.php` and clear cache afterwards. edit the file as you wish and you must be good to go.

# Answer
> 2 votes
The drupal\_add\_js function takes an `$options` argument.

This is an array that may have a value for key `scope` as `header` that would place the JS file specified in the header part of your template.

`drupal_add_js('path/to.js', array('scope'=>'header'));`

**Another way if you are working in a module :**

Add this in your module's .info

`scripts[] = somescript.js`

# Answer
> 2 votes
You can add something like this on your page. Use path and argument to identify the correct page. Or you can add it in hook\_init but in that case it will display on all pages which is not recommended.

```
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'header', 'weight' => 5)
  );

```

Alternatively you can use `drupal_add_html_head` like the following

```
 $inline_script = <<<EOL
      <script src="my_src" type="javascript"></script>
      <script src="my_src" type="javascript"></script></script>
EOL;
    $element = array(
      '#type' => 'markup',
      '#markup' => $inline_script,
    );
    drupal_add_html_head($element, 'jquery-tmpl');

```

# Answer
> 2 votes
You can add javascript to head by using theme\_preprocess\_html()

```
function theme_preprocess_html(&$var) {
  $script = array(
    '#tag' => 'script',
    '#attributes' => array('type' => 'text/javascript'),
    '#value' => 'Add your javascript here',
   );
   drupal_add_html_head($script, 'script');
}

```

# Answer
> 0 votes
Sure thing! `drupal_add_js` is your friend here. Documentation for Drupal 7 is here: https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_js/7

Basically, with `drupal_add_js` you get to select where the JS gets added, from a set of predefined options, which consist of 'header', 'footer', and your regions. So your function call, assuming this is a file in your module/theme, would look something like this:

```
drupal_add_js($path_to_js_file, array('scope' => 'header'));

```

There's a bunch more options you can use, like `type` to define the sort of JS you're adding (inline, external, etc) and `weight` to define the weight of the JS file relative to other JS files. There's more about that on the page linked in the first paragraph.

As for where this goes, I usually put mine in a `hook_init` function if it's part of a module, or in my `hook_preprocess_html` function if it's part of my theme.

There's also the option, if you have an `html.tpl.php` file that you can edit, of directly adding the JS to there. I'm not sure that that's the preferred method, though, and you can't sort where it lands in the list of other JS; it has to either be before the other JS is printed to the page or after it. Overall, not ideal.

---
Tags: 7, theming, javascript
---


# Question
Title: How to get in Views RESTful API non latin's letters on fields?
With this guide, I do my RESTful API view (through core modules: RESTful Web Services and Serialization). Ater go to API page, I get this JSON:

```
[{"title":"\u0411\u044b\u0441\u0442\u0440\u044b\u0439 \u0431\u044e\u0434\u0436\u0435\u0442\u043d\u044b\u0439 \u0424\u0440\u0438\u0437 \u041c\u0430\u0433 (Freeze Mage)"}]

```

All `\u0xxx` codes — it's non english/latin letters (Russian/Ukraine in UTF-8, for example).

How to correct (readable) display in JSON response?

# Answer
The Drupal 8 Rest module relies on the Serialization module to create the JSON output. This module, in turn, is using the Serializer Symfony component, which outputs escaped characters by default (it is not passing the JSON\_UNESCAPED\_UNICODE constant to the json\_encode call).

As far as I can see, the escaped UTF8 characters are fine (they are legal in JSON) and you should be able to parse it back to UTF8 from any REST client having a JSON decoder. They are just not very readable if you try to read the JSON directly.
> 1 votes

---
Tags: 8
---


# Question
Title: How do I check the current user session?
In Drupal 7, I was able to use bootstrap.inc in an external PHP script, which was a custom set of pages that simply bootstrapped Drupal to check the user was logged in Drupal.

The following code is a very basic version that just returns the username of an active session.

```
require_once '../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
echo $user->name;

```

I'm looking to implement something similar in Drupal 8. The same script returns a server error.

> Error: Class 'Drupal\Core\Session\AccountInterface' not found in core/includes/bootstrap.inc, line 63

How should I check for an active user session from an external script, in Drupal 8?

# Answer
You can't really do something like that in Drupal 8.

The short story is that we use Symphony for the Request / Response flow, so actually bootsrapping Drupal is a lot more complex than simply requiring the `bootstrap.inc` file. If you look at the index.php file, you can see an overview of a request in Drupal 8:

```
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

```

Most of this happens in the `DrupalKernal::handle` call. You could probably make a custom script that hooks into Drupal, but it probably will be a lot easier and more maintable to actually have this code be part of your Drupal installation.
> 3 votes

---
Tags: 8, bootstrapping, external-scripts
---


# Question
Title: If "tag" is "event" - how to do condition with php
I need to do a condition on a tpl.php

Basically I have a content type with taxonomy "tags" - some are News, some are Events.

On the page.tlp I want to do the following condition:

```
if ($content['field_tags']=='Events'):

    <p>test</p>

endif;

```

But this doesn't work.

Can you help me? Thanks.

# Answer
> 1 votes
This is where you will find it in `node.tpl.php`

```
$content['field_tags']['#items'][0]['taxonomy_term']->name

```

Be sure to test it for empty() or run it through isset() before you use it.

# Answer
> 0 votes
I would try it like this

```
if ($content["field_tags"] == 'Events')
echo '<p>Lorem ipsum dolor met</p>';

```

---
Tags: theming
---


title: How do I change my Admin theme?

text:
# Question
Title: How do I change my Admin theme?
I'm brand new to Drupal and have just installed Drupal 7. When I was configuring it, I originally selected "Stark" as my Admin theme, thinking I would create my own CSS later. In trying to learn Drupal and add content, I have decided that I would like to change my Admin theme. I went to the Admin tool bar (across the top) and clicked "Appearance" and changed my theme there, I even disabled the "Stark" theme, but my Admin theme is still defaulting to the Stark theme. How do I change this?

# Answer
Go to `admin/appearance` and you will see a fieldgroup called "Administration theme" at the bottom.
> 1 votes

# Answer
I found the error the code not working because i use Bootstrap theme, and administration theme use Seven theme, just change the administration theme to bootstrap or put the code under Seven code
> 0 votes

---
Tags: theming
---


# Question
Title: How to sort a view using values not stored in the database
I'm using a view where elements are sorted by price values, under certain conditions the price values are rewritten on the display (if there are offers) but not in the database. The problem is that I need the results to be ordered by the rewritten price. I can reorder the results returned by the query using a views\_pre\_render hook:

https://stackoverflow.com/questions/2471361/how-to-sort-view-results-programmatically

but it only affects the current page so elements are not properly ordered within the elements not shown in the current page.

Other option would be to order the view altering the query itself but since the right price values don't actually exist in the database I don't know how this could be done. Is there a way to order the results of a the whole view when paginator exists?

I've thought about not using pagination and requesting all the elements of the view so I can create my own paginator once I've ordered the results but I'm not sure how would it affect the speed of the page.

# Answer
I used a view pre render hook to alter the order of the returned rows (I had to disable pagination and create my own pagination system). Here's an example of the function:

```
function your_theme_or_module_views_pre_render(&$view) {
  if ('your_view' == $view->name && 'your_display' == $view->current_display ) {
    if(isset($_GET['sort_order'])){
      if($_GET['sort_order'] == 'ASC'){
        $sortorder = SORT_ASC;
      }else{
        $sortorder = SORT_DESC;
      }
      if($_GET['sort_by'] == 'field_price_value'){
        $byprice = true;
      }else{
        $byprice = false;
      }
    }else{
      $byprice = true;
      $sortorder = SORT_ASC;
    }
    $order = array();
    foreach ($view->result as $key => $row){
    /* Here you can modify the values you want to show
    and put them in an order array */
      $row->field_field_price[0]['rendered']['#markup'] = $thenewprice[$index]."€";
      $row->field_field_price[0]['raw']['value'] = $thenewprice[$index];
      $order[$key] = $thenewprice[$index]; // we will use this array for multisorting
    }

    //this will be used for pagination In my case I'll show 8 results per page
    $numpages = ceil(count($view->result)/8);
    if($byprice){
      /* we only change the rows order if we are sorting by the
      modified field, otherwise the order returned by the view is fine */
      array_multisort($order, $sortorder, $view->result);
    }

```

Now we create the pagination system you can use this as an example

```
    if(!isset($_GET['page'])){
      $view->result = array_slice($view->result, 0, 8);
    }else{
      $sumando = ((int)$_GET['page']*8);
      $view->result = array_slice($view->result, $sumando, 8);
    }
    $links = array();
    if(isset($_GET['page'])){
      $page = $_GET['page'];
      $absolute_url = full_url( $_SERVER );
      for($i=0;$i<$numpages;$i++){
        if($page == $i){
          $active = " active";
        }else{
          $active = "";
        }
        $urlconpage = str_replace("page=".$page,"page=".$i,$absolute_url);
        $links[] = "<a class='paginator ".$active."' href='".$urlconpage."'>".$i."</a>";
      }
    }else{
      $absolute_url = full_url( $_SERVER );
      $countarray = explode("?",$absolute_url);
      if(count($countarray)>1){
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."&page=".$i;
          $links[] = "<a class='paginator".$active."' href='".$urlconpage."'>".$i."</a>";
        }
      }else{
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."?page=".$i;
          $links[] = "<a class='paginador".$active."' href='".$urlconpage."'>".$i."</a>";
        }
      }
    }
    $_SESSION['links'] = $links;
  }

```

Most of the code in the paginator is just to keep unchanged the parameters in the url, essentials for the view returning the right results. The function full\_url that I call in the code is an adaptation of the function described in:

https://stackoverflow.com/questions/6768793/get-the-full-url-in-php

Using the SESSION variable You can print the links where you prefere, For example in a global textarea in the view footer, inside an `<ul> <li>` structure.
> 2 votes

---
Tags: database, views
---


# Question
Title: Clicking reset in Views UI causes PDOException Error
I have a searchable view created that returns the following error when I click to "reset" the search query. It only occurs when resetting a search from the search terms field.

> An AJAX HTTP error occurred. HTTP Result Code: 500.

The logs show the following:

> PDOException: You cannot serialize or unserialize PDO instances in DrupalDatabaseCache-\>set() (line 455 of /code/includes/cache.inc).

This error occurs in the preview, not on the live page.

# Answer
Something is trying to serialise a PDO object, which you can't do in PHP (unless you're running \< 5.3 and are happy with nasty workarounds).

Drupal core doesn't do this; The Views module itself doesn't do this; so you'll need to disable custom/contributed modules you have installed one by one until you find the culprit. If/when you do, either fix the module if custom, or report the bug to the module's issue queue on Drupal.org for review.

If you're making use of the PHP filter in that View, remove the PHP code temporarily to see if that's the problem. If it is, consider re-implementing that logic in a more stable manner, i.e. using the hooks from the Views module.
> 0 votes

---
Tags: 7, views, ajax
---


# Question
Title: menu item for current page is missing a href tag for anonymous user
drupal 8: Theme used "bartik".

If user is logged in, the active menu item has an `<a>` \- tag, if not the tag is missing.

**Is this the expected drupal behavior?** btw. the same happens on the language switcher block.

How can i output the a-href tag for anonymous users? This would make theming menus much easier. Thx for any help or pointing me into the right direction

**markup for anonymous user**

```
    <ul class="clearfix menu">
.....
<li class="menu-item menu-item--active-trail">
    c
</li>

```

**markup for admin user**

```
<ul class="clearfix menu">
......
<li class="menu-item menu-item--active-trail">
    <a href="/drupal-8.0.3-clean/node/3" data-drupal-link-system-path="node/3" class="is-active">c</a>
</li>

```

# Answer
> 0 votes
I fixed this issue by overriding menu.html.twig. You could override menu--main.html.twig instead, if you just want to target the main menu:

## menu.html.twig

```
<li{{ item.attributes.addClass(classes) }}>
  ##REPLACE THIS LINE:## {{ link(item.title, item.url) }}
  ##WITH THIS LINE:## <a data-drupal-link-system-path="{{ item.url }}" title="{{ item.title }}" href="{{ item.url }}">{{ item.title }}</a>
  {% if item.below %}
    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
  {% endif %}
</li>

```

I submitted a bug report here: https://www.drupal.org/node/2695619

---
Tags: users, navigation
---


# Question
Title: Can we use current views exposed filter values to prepopulate another form?
I've set up a view that displays users and has exposed filters user first and last names. If there is no user matching the filter values, I'd like to display a link to create a new user and prepopulate the name fields with the values searched in views.

I know there's the prepopulate module and likely other methods to do the actual prepopulating, but I guess this question is more centered on how to grab the filter values so they can be added to the new link url as properly formatted arguments.

EDIT: Got this solved with help from the answer below. Ending up grabbing the filter values with the "exposed filter values" module and populating the field values in a custom module with this code:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_register_form') {

        //Prepopulate the name fields with url args
        $field_lang = $form['field_name']['#language'];
        if(isset($_GET['first'])) {
            $first = $_GET['first'];
            $form['field_name'][$field_lang][0]['#default_value']['given'] = $first;
        }

        if(isset($_GET['last'])) {
            $last = $_GET['last'];
            $form['field_name'][$field_lang][0]['#default_value']['family']= $last;
        }
    }
}

```

# Answer
> 0 votes
After googling this question some, I came up with the following receipe:

1. Install prepopulate and exposed filter data
2. Modify exposed\_filter\_data.tpl.php provided by exposed filter data to produce a dynamic prepopulate URL for creating a new user

Hope this helps!

P.S.: Inspired from this discussion =\> https://www.drupal.org/node/1630198

---
Tags: 7, views, users
---


# Question
Title: How to redirect based on matching a node field?
This question is somewhat similar to How to redirect based on views results? which I think gives me part of the answer I want. Basically my situation is this:

I am migrating from an old xoops system which had its own set of content ids. I want to seamlessly make the switch to this new drupal system, meaning the old urls work, but redirect to their new pathauto equivalents.

By way of explanation, say the old url was `/view.php?docid=6252` and the new address should be `/pubs/capacity_building_climate_change_impact_assessment` which has been generated by pathauto.

I can do a redirect at the web server level to get from `/view.php?docid=6252' to`/pub/6252\`.

I have brought over the legacy document id, as a field on the new nodes, and I have a view working where I can visit /pub/6252 and get the right content. Now I want to make sure that the pathauto url is the definitive one url to rule them all for that particular node. How can I redirect to the proper url based on that url segment matching the legacy document id field in a node. It would be nice if it could be done without bringing all of the overhead of a views lookup into it, but if redirecting from that view is the best way, so be it. Hopefully I can aggressively cache that view since that data should almost never change.

I downloaded the Redirect module, hoping that it provided some of that, especially since it claims integration with the views api, but I didn't immediately see anything helpful there, and there doesn't seem to be any documentation for it.

# Answer
# Non-Views Answer

I finally figured out how this can be done without incurring the overhead of views. I'll leave the views answer below in case it is useful for someone, but this version seems snappier to me. As always, critique very welcome!

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu()
{
    $items = array();
    $items['pub'] = array(
        'title' => 'publications by Docid',
        'access callback' => TRUE,
        'page callback' => '_MYMODULE_pub_to_docid',
    );
    return $items;
}

/**
 * Redirect to a publication page based on its legacy_docid
 */
function _MYMODULE_pub_to_docid() {
    $path = current_path();
    $path = str_ireplace('pub/', '', $path);
    $args = explode('/', $path);
    $query = new EntityFieldQuery();
    if (_MYMODULE_isInteger($args[0])) { // Sanity check, local helper function just to check that the value is an integer.
        $query->entityCondition('entity_type', 'node')
            ->fieldCondition('field_doc_legacy_docid', 'value', $args[0]);
        $result = $query->execute();
        if (isset($result['node']) && count($result['node'] == 1)) {
            $node_holder = array_slice($result['node'],0,1)[0];
            $node = node_load($node_holder->nid);
            $language = language_list()[$node->language];
            drupal_goto(drupal_get_path_alias('node/'.$node_holder->nid, $node->language), array('language' => $language), 301);
        } else {
            return MENU_NOT_FOUND;
        }
    }
    return MENU_NOT_FOUND;

}

```

# Views Answer

Here is a views answer, but I'd still like to know if there is a better or preferred way of doing this. I added a function in my\_module:

```
function my_module_views_pre_render(&$view) {

  if ($view->name=='staff_views') { // user redirect
    drupal_goto(drupal_get_path_alias('user/'.$view->result[0]->uid));
  }
  if ($view->name=='pub_by_docid') {
      if (count($view->result) == 1) {
          $node = node_load($view->result[0]->nid);
          $language = language_list()[$node->language];
          drupal_goto(drupal_get_path_alias('node/'.$view->result[0]->nid, $node->language), array('language' => $language), 301);
      }

  }
}

```

Note that this function is actually redirecting for a view that matches users based on their legacy user id first, and then for a view that matches document id as mentioned originally in my question.

**Update:** I've updated the code here to reflect the suggestion from J. Reynolds that I include a http response code of 301 to avoid drupals default of 302.

I also found that to get things to work for non-English publications, I needed to add a language option to `drupal_goto()`, which needs to be a language object. That is the reason for the line creating the `$language` variable.
> 2 votes

# Answer
You could use the the Rules module to get this to work, together with the Rules URL Argument module. It will make the value of the URL argument available as new variable to Rules. Here is a quote about the Rules URL Argument module (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

So with that, and specific to your question here, you could make the Rules module perform a redirect of an URL like `/view.php?docid=6252` to '/pub/6252'. Combined with your "*I have a view working where I can visit /pub/6252 and get the right content.*" you should be OK to go.
> 0 votes

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


# Question
Title: How to set an expiration date on an active rule so that it is disabled on a certain date?
Anyone knows how to set an expiration date on a Drupal 7 Rule (using the Rules module) so that the rule is disabled on a certain date?

**Example Use Case:**

We've created a product (using Drupal Commerce) with a name that's just a long string of random upper and lowercase characters and numbers. We then created a rule with one condition and two actions so that when Drupal is initialized (the event) it recognizes a specific URL a user came to the site with (ie. sitename/?SKU=productnamewithlotsofcharacters)\[using the text comparison condition and then the provide URL argument value action\] and when that's the case it re-directs the user to a specific product form (page redirect action to a drupal commerce express checkout form).

We only want this promo to last until a certain date, but we will be using it again in the future (so we just want the rules disabled). When the user uses this link to get to our site and the promo is 'expired' it takes them to a page that says 'Promo Expired'.

It's not the most fool-proof method of doing things of course but it works well enough for our needs.

# Answer
> 4 votes
Programmatically disable a rule contains an example of how you can disable a rule programatically, as in this example:

```
/**
* Implements hook_update_N().
* Disables name_of_rule rule.
*/
function hook_update_N() {
  $rules_config = rules_config_load('name_of_rule');
  $rules_config->active = FALSE;
  $rules_config->save();
}

```

Tune this example to fit the machine name of your rule to be disabled, and then use that as the "PHP code " in a Rules Component (Action) which only performs an "Execute custom PHP code".

With that, the only challenge left to make this work, is to enhance your rule to be disabled, to conditionally trigger this (new) Rules Component "after the moment has arrived" for your rule to be disabled. For this you might want to add "Conditional Rules" (so that you can add a condition within the Rules Action of your rule to be disabled).

---
Tags: 7, rules
---


# Question
Title: Passing page arguments to custom block inside panel
I have created a page(Page Manager) in drupal 8 with a path say **/dashboard/{nodeid}**. Inside that I have created a Panel and inside panel I have added a Custom Block ( which I created programmatically by extending BlockBase). Now my problem is I want to use the {nodeid} inside my buildForm function.

Please suggest me.

My code is as follows.

**ABCBlock.php**

```
class ABCBlock extends BlockBase
{

    public function build() {

        return \Drupal::formBuilder()->getForm('Drupal\examples\Form\ABCForm');

    }

}

```

**ABCForm.php**

```
class ABCForm extends FormBase
{

    public function getFormId() {
      return 'example_ABCForm';
    }

    public function buildForm(array $form, FormStateInterface $form_state)    {

      drupal_set_message('Hello World.'); // displaying fine.
      $tmp = arg(0);//or arg(1) which i am assuming as url parameter value. But it FAILS.

      //load node object using $tmp

    }

}

```

# Answer
> 1 votes
While a very different question, the answer is the same as mine in https://drupal.stackexchange.com/a/188629/31.

In short, define a context on your block, make sure that the parameter in page manager is defined as type node and the rest should just work.

---
Tags: 8, blocks
---


# Question
Title: TWIG for loop returning first value only
I have an array of 5 objects. I would like to loop throught the 5 objects and display fields from within.

I have a for loop in place that is returning the appropriate fields, but it is displaying the same object 5 times.

```
{% for key, object in featured_resource_nodes %}

  {% if node.field_featured_resources[0].entity.field_resource_type.value == 'whitepaper' %}
    <span class="icon-icons_whitepaper"></span>
  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'Datasheet' %}
    <span class="icon-icons_datasheet"></span>
  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'blog' %}
    <span class="icon-icons_blog"></span>
  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'video' %}
    <span class="icon-icons_video"></span>
  {% elseif node.field_featured_resources[0].entity.field_resource_type.value == 'analystreport' %}
    <span class="icon-icons_analyst-report"></span>
  {% endif %}

  {% if node.field_featured_resources[0].entity.field_resource_type.value == 'video' %}
    <a href="{{ featured_resource_nodes[0].field_on_demand_webinar[0].data[0] }}"><h3 class="text-center">{{ node.field_featured_resources.entity.title.value }}</h3></a>
  {% else %}
    <a href="{{ file_url(node.field_featured_resources.entity.field_resource_file[0].entity.uri.value) }}"><h3 class="text-center">{{ node.field_featured_resources.entity.title.value }}</h3></a>
  {% endif %}

{% endfor %}

```

But this is what is being returned

How do I loop through the objects and have it display the 5 individual results?

# Answer
> 1 votes
It is displaying the same object 5 times because `node.field_featured_resources[0]` is referenced 5 times. Use the iterator variable `object` or use `node.field_featured_resources[key]` instead.

It also may be better to do this without all of the logic in the template. Off of the top of my head,

* In template preprocess for the field (PHP), set the class in Attribute.
* In module layer (PHP), add a Field Formatter.
    + Or if Field Formatter are already available, configure Manage Display to display the fields in the desired format.
* In template (Twig), print out the field value in the span directly.

Here's some Twig:

```
{% for key, object in featured_resource_nodes %}
  <span class="icon-icons_{{ object.entity.field_resource_type.value }}"></span>

  {% if object.entity.field_resource_type.value == 'video' %}
    {# @todo: Configure Field Display for On-Demand Webinar instead... #}
    <a href="{{ object.field_on_demand_webinar[0].data[0] }}">
      {# @todo: consider object.entity.title instead of .value #}
      <h3 class="text-center">{{ object.entity.title.value }}</h3>
    </a>
  {% else %}
    {# @todo: Configure Field Display for Resource File instead... #}
    <a href="{{ file_url(object.entity.field_resource_file[0].entity.uri.value) }}">
      {# @todo: consider object.entity.title instead of .value #}
      <h3 class="text-center">{{ object.entity.title.value }}</h3>
    </a>
  {% endif %}
{% endfor %}

```

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


title: View No Results Behavior not working

text:
# Question
Title: View No Results Behavior not working
I have a view with horses for sale. I have another view with a filter of `field_sold` = yes.

Currently there are no horses for sale. I want to add a `No Results Behavior` "Currently we have no horses for sale."

I tried in `Structure > View > Sold > Custom text (field) > NO RESULTS BEHAVIOR` but I don't see the message?

# Answer
> 2 votes
If I understood correctly, your view is not returning any results because of it's filter (field\_sold = yes), if so, then no field are going to be shown in the view, so if you rewrite a field 'No results behavior' it won't show, simply because your view is not returning any row.

What you are looking for is the 'No results behavior' that's in the advanced tabs in the view. That's what is going to show when your view returns no results at all.

Just add Custom text field and put whatever you want there.

---
Tags: 7, views
---


# Question
Title: How to force users to re-authenticate on specific pages?
Is there any possibility to Re-Authenticate user especially on ***specific pages*** like we see in some websites?

**Background**: for some of the websites like banking sites, when you are initiated fund transfer it will ask you to re-authenticate your account. Main moto is here, user will be logged in a long back ago using "Remember me", so for visiting few pages I want to re-authenticate user.

# Answer
> 3 votes
I think this module suits to my requirement: Protected Pages. Some details about it (from its project page):

> ... allows the administrator to secure any page in your website by password. You just need to go to configuration page of this module and add path, password. After that the added path will be password protected. This module also allows you to send the details of this protected page to multiple users by email.

# Answer
> 1 votes
Have a look at the Automated Logout module. Some details about it from its project page:

> ... provides a site administrator the ability to log users out after a specified time of inactivity.
>
> It is highly customisable and includes "site policies" by role to enforce logout.
>
> Features:
>
> * Different timeouts based on role.
> * Disabling of timeouts based on role.
> * Permission for users to set their own timeout.
> * Includes some JS mechanisms to keep uses logged in even if multiple tabs are open or if the user is working on a form for a long period of time.
> * Includes developer hooks to allow users to remain logged in depending on your own project specific requirements.
> * Optional integration with Javascript Timer.

If you limit your **specific pages** to be accessed only by "role", using this module should help. If needed using the available hooks to further refine its logic to meet your specific requirements.

Refer to the article about Auto Logout for some more details (and screenprints) about it.

---
Tags: 7, users
---


# Question
Title: Create node programmatically with menu entries
I created an action in Rules, which generates a duplicate of a node. If I am creating a node of the type "basic", it will duplicate the node for every taxonomy term. So when I have a node with three taxonomy terms, the action will generate three nodes.

The only difference are the taxonomy terms, because the created nodes should get the URL `'/taxonomy-term1/node-title', '/taxonomy-term2/node-title', ...`

My problem: If I have the taxonomy terms Taxonomy\_Term1, Taxonomy\_Term2 and Taxonomy\_Term3, I get the following result:

```
/taxonomy-term1/node-title

/default/node-title

/default/node-title-0

```

I am thinking the problem lies in the array which was created from the latest nid. But when I am printing each term\_name (to know what it looks like), the results are the Strings Taxonomy\_Term1, Taxonomy\_Term2 and so on.

```
function autocreatenode_rules_action() {
$nid = db_query_range("SELECT nid FROM {node} ORDER BY nid DESC", 0, 1)->   fetchField();
$string = token_replace('[node:field_tags]', array('node' => node_load($nid)));
$terms = explode(',', $string);
$i = 0;
foreach ($terms as $term_name) {
    $i++;
}
    if($i >= 2) {
        foreach ($terms as $term_name) {
            $node = new stdClass();
            $node->type = 'basic';
            $node->language = 'de';
            node_object_prepare($node);
            $node->title = 'Title';
            $node->field_body[LANGUAGE_NONE][0]['value'] = 'Something in the body';
            $menu = array();
            $menu['link_title'] = 'Menu Link title';
            $menu['description'] = '';
            $menu['menu_name'] = 'main-menu';

            switch($term_name) {
                case 'Taxonomy_Term1':
                    $menu['plid'] = 5;
                    break;
                case 'Taxonomy_Term2':
                    $menu['plid'] = 6;
                    break;
                case 'Taxonomy_Term3':
                    $menu['plid'] = 7;
                    break;
                default:
                    $menu['plid'] = 1;
            }

            $menu['enabled'] = 1;
            $node->menu = $menu;
            $node->status = 1;
            $node->promote = 0;
            $node->sticky = 0;
            $node->comment = 2;
            $node->uid = 1;
            $node->date = 'complaint_post_date';
            $node->created = strtotime('complaint_post_date');
            $node = node_submit($node);
            node_save($node);
        }
    }}

```

# Answer
> 0 votes
The code you posted seems a bit frail at places, but if it works for you, we can focus on your specific question.

The main problem is that you are not adding the $menu array to your node object before saving it. You would only need to add it to the object before you save it, similar to this:

```
$node->menu = $menu;
...
node_save($node);

```

Cheers and good luck!

P.S.: You can check out this thread for some code examples https://stackoverflow.com/q/2603289/5875098 P.S.2: To get all the terms directly from the $node object:

```
$terms = array();
$language = 'und'; // or will be provided by some Drupal hooks
foreach ($node->field_tags[$language] as $delta => $value) {
  $termObj = taxonomy_term_load($value['tid']);
  $terms[] = $termObj->name;
}

```

You can replace the $terms = explode... in your code with this snippet.

---
Tags: 7, nodes, taxonomy-terms, routes
---


# Question
Title: Drupal 7 form_state[redirect] does not work
I am new to Drupal development and I stuck on a problem. I have got a form which I append to a node. The custom submit method is called correctly, but my redirect does not work. When I press the button I got redirected to the form. Thank you very much in advance

```
    function ticketGenerator_node_view($node, $view_mode) {
    $nodetype = node_type_get_type($node);
    $nodetype = $nodetype->type;
    if ($view_mode == 'full' && node_is_page($node) && $nodetype=='event') {
    $node->content['buttonKaufentest'] = drupal_get_form('ticketGenerator_generateform',$node);
    }
    return $node;

```

}

```
    function ticketGenerator_generateform($form, &$form_state,$node){
    $form = array();
    $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
);
    $form['submit'] = array(
    '#type' => 'submit' ,
    '#value' => 'buttonalter',
    '#submit' => array('ticketGenerator_list_submit')
 );
 return $form;

```

}

```
   function ticketGenerator_list_submit($form,$form_state){
   drupal_set_message('custom submit has been invoked');
   $form_state['redirect'] = 'www.google.de';
   }

```

# Answer
> 4 votes
You need to pass `$form_state` in by reference, or the change won't be persisted outside of the function scope:

```
function ticketGenerator_list_submit($form, &$form_state) {

```

# Answer
> 0 votes
In my case for Drupal 7 forms. I was setting $form\_state\[redirect\] in the submit handler function and I also did a print\_r() to make sure it was there and it was. But it wouldn't redirect. I had to unset the following variables in order for it to work:

```
unset($form_state['rebuild']);
unset($_GET['destination']);

```

---
Tags: 7, redirection, forms
---


# Question
Title: Node form validates fields with #access = FALSE after ajax image upload
I have a node form for a content type rendered using *drupal\_get\_form()*, I wanted to hide some fields so I altered this form and set attribute *#access* to `FALSE` in order to hide it and not validate it.

Until this point everything goes nice but now I have a scenario that this form has an image field with ajax upload button, after removing / re-uploading the image the form validates the required fields that I already set its *#access* to `FALSE`.

I think that the form is rebuilt and all alteration to fields with `#access = FALSE` gone away. What should I do to avoid this?

# Answer
> 0 votes
You can use hook\_form\_alter() to hide the fields so that when the form is rebuilt (with AJAX or normal page load) the fields will still be hidden.

Also if you wanna make a field not validate then use the **code below** in your hook\_form\_alter() hook.

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your_form_id'){
    // To hide the field
    $form['your_field']['#access'] = false;
    // To remove validation
    $form['your_field']['#required'] = false;
  }
}

```

---
Tags: 7, ajax
---


title: Contact for per node in Drupal 8?

text:
# Question
Title: Contact for per node in Drupal 8?
This was quite easy on Drupal 7. You could just use Webform. In Drupal 8, I'm not so sure.

I have nodes of type "Business". I want a form to appear on this page, that when filled in, it must send an email to the business. The "Business" content type has a field on it called "Business Contact Email Address". This is where the mail must go...

I was thinking of:

1. Finding a way to do it using the inherent Drupal 8 contact forms... any clues as to how?
2. Creating a new content type called "Node Contact Form" that references a node and then use Rules to mail the field on the referenced node.

Is there an easy way to do this?

# Answer
> 4 votes
Not without code, but its fairly easy.

You could add a reference field to contact forms to your node type, and "view" the contact form. `contact_storage` provides a view builder that will display the form then. That doesn't work for your additional mail requirement, however.

To be able to do that, you need custom code to display the form, something like this in `hook_node_view()`. field\_node\_reference is an entity reference field that points back to the node. that will allow you to easily see for which node it was submitted and also use it later on to change the recipient:

```
  $message = \Drupal::entityManager()->getStorage('contact_message')
    ->create(array(
      'contact_form' => 'YOUR_FORM_ID',
      'field_node_reference' => $node,
      // You can generate a default subject or even hide it completely
      // and always use this value.
      'subject' => t('Contact about "@title".', ['@title' => $node->label()]),
    ));
  $form = \Drupal::getContainer()->get('entity.form_builder')->getForm($message);
  $build['yourmodule_contact_form'] = array(
    '#type' => 'details',
    '#open' => TRUE,
    '#title' => t('Contact the business'),
  );
  $build['yourmodule_contact_form']['form'] = $form;

```

yourmodule\_contact\_form can be defined as an extra field (`hook_entity_extra_field_info`), then you can conditionally display it using `if ($component = $display->getComponent('yourmodule_contact_form')) {` and you can configure the place and if it should be displayed per view mode.

The final piece is then to override the mail recipient of the sent mail using a hook\_mail\_alter():

```
function yourmodule_mail_alter(&$message) {
  if (!empty($message['params']['contact_form']) && !empty($message['params']['contact_message'])) {
    /** @var \Drupal\contact\Entity\ContactForm $contact_form */
    $contact_form = $message['params']['contact_form'];
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_form->id() == 'YOUR_FORM_ID' && $contact_message->hasField('field_node_reference')) {
      /** @var \Drupal\node\NodeInterface $node */
      $node = $contact_message->field_node_reference->entity;
      if ($node && $email = $node->field_email->value) {
        $message['to'] = $email;
      }
    }
  }

```

This could possibly be built in a generic way but it would require configuration for the mail and reference fields.

---
Tags: forms, 8, entities, emails
---


# Question
Title: How to print page/node templates being used on a page?
I'm using Drupal 6.19 and trying to debug why a custom page template for my login page isn't being picked up. I've tried to use devel themer, but I don't see the "widget" when I'm not logged in, and of course I can't see the login page when I am.

I'm hoping for a script that I can drop in on my page tpl that will print the current template being used. Or maybe there are other suggestions?

# Answer
> 3 votes
For Drupal 7, there's a new 'theme debug mode'. This eliminates the need for installing the Theme Developer module and its dependencies, if all you want is to see the templates being used on a page.

> As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme\_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments). To enable it, add this line to your settings.php:

```
$conf['theme_debug'] = TRUE;

```

see https://www.drupal.org/node/223440

# Answer
> 2 votes
Checkout Theme Developer module.

> Firebug for Drupal themeing. Note that this module injects markers into the DOM to do its magic.

# Answer
> 0 votes
Been a while since I've touched 6, so vars may be different than I recall, but you could use:

```
print_r($variables['theme_hook_suggestions']);

```

Inside of a preprocessor function. That will tell you what the system is trying to use. At that point I'd look for the files and put insert in 'This is path/to/file.tpl.php' in the templates.

Hope that helps.

---
Tags: theming
---


# Question
Title: How can I create a view of child nodes based on the menu relationship?
Say you have the following pages in a menu tree:

* Projects
    + Project One
    + Project Two
    + Project Three

I'm looking for a way to create a view that will be embedded in the Project (parent) page that will show a pic, title and text (summary) from the child pages.

The relationship between the parent and the children is defined in the menu tree.

I know I can use node reference, but that would mean every time someone creates a page they would have to define the menu relationship and then the node reference relationship.

Also I know that I could create another content-type but I think this is overkill as all content pages look the same.

# Answer
One solution is to use taxonomy terms to define the relationships and then to use the Taxonomy Menu module to translate those term relationships into menu items. You can then use the Custom Page module and Context modules to control information and regions on all the pages if you don't want to use panels.
> 4 votes

# Answer
You can do exactly this using the Menu Node API and the Menu Node Views modules.

Create a view with your required content type, and choose a contextual filter of "Menu: Menu link ID" (this is only available with the above modules installed).

Under, "When the filter value is not available," select "Provide default value" and choose "PHP code."

The following snippet will do it, then you just expose a block from the view and you are there:

```
if (function_exists('menu_node_get_links')){
   $node = node_load(intval(arg(1)));
   if (isset($node->menu_node_links)){
      foreach($node->menu_node_links as $mlid=>$data){
         return $mlid;
      }
   }
}

```
> 16 votes

# Answer
The Node Hierarchy Module allows this type of relationship, as well as providing a views integration.

> Node Hierarchy allows nodes to be children of other nodes creating a tree-like hierarchy of content. The module offers:
>
> * 1-Click creation of hierarchical menus
> * Hierarchical breadcrumbs
> * Automatic hierarchical urls using Pathauto (and token module)
>
> (eg: q=aboutus/history/beginning).
> * Automatic creation of hierarchical menus if desired.
> * Optional Views integration.
> * Optional Node Access integration.
> 4 votes

# Answer
Maybe this has changed for D7/Views 3, but you don't need any PHP in order to accomplish the desired behavior:

1. install menu\_views, menu\_node and menu\_node\_views modules.
2. create a new view of type "menu tree"
3. add fields "Menu: link title" and "Menu: description"
4. Add Contextual Filter/Argument "Menu: Node ID"; Provide default value "Content ID from URL"
5. Add Relationship "Menu: Parent menu link id"

voila. It shouldn't work, but it does.

It works fine with just nodes, but the advantage of using menu links over node hierarchy is that you're not limited to building navigation around nodes. You could even include external links in your view.
> 2 votes

# Answer
There's a relatively new module Views Menu Node Children Filter that seems to do exactly what you want:

> This module adds a contextual filter to Views that will retrieve a node's child nodes according to a menu's structure.
> 2 votes

# Answer
Have you considered using Node Reference for this purpose?

1. Provide a node reference field to the content type you want to display.
2. Use that field as a contextual filter in the View (default value: *Content ID from url*).
3. Add this view display as a block to the content. The node in which it's being displayed will be seen as a parent of the nodes that reference to it for instance.

Thus you can achieve a similar outcome as you're probably looking for.
> 0 votes

# Answer
The answer from Emile is right, but I had to paste the mentionned PHP code in a *contextual filter* of the type " **Menu: Parent menu link id** ".

```
if (function_exists('menu_node_get_links')){
   $node = node_load(intval(arg(1)));
   if (isset($node->menu_node_links)){
      foreach($node->menu_node_links as $mlid=>$data){
         return $mlid;
      }
   }
}

```
> 0 votes

# Answer
If you use entity translation and the node is attached to different menus, here is an adaptation of the code that filters on the current language. You need to copy this as PHP code for the contextual filter (parent menu link id) in your view like explained in the other answers

```
 if (function_exists('menu_node_get_links')) {
global $language;
$lang = $language->language;
$node = node_load(intval(arg(1)));
if (isset($node->menu_node_links)) {
  foreach ($node->menu_node_links as $mlid => $data) {
    if ($lang == $data->language) {
      return($mlid);
    }
  }
}
  }

```
> 0 votes

# Answer
From the issue queue of Menu Node Views we have this nice solution :

* add a contextual filter with 'Parent menu link id',
* select 'Provide default value'
* select 'custom php code'
* enter the following code

```
$menu_item = menu_get_active_trail();
$current_item = array_pop($menu_item);
$menu_item_plid = $current_item['plid'];
return $menu_item_plid;

```
> 0 votes

---
Tags: 7, routes, views, nodes
---


# Question
Title: Create image style options, when user is uploading an image
Is there any way to provide image style options, when user is uploading any image and can select any style from the drop down?

# Answer
Insert

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

more details Upload images style
> 1 votes

# Answer
You need to create an image style (say "A") via admin/config/media/image-styles first, when the new image style already created, you can of course choose it (A) from the drop down.
> 1 votes

---
Tags: media
---


# Question
Title: When taking a copy of the node template do you need to maintain the article tag that is in there
When taking a copy of the node template, should you keep/maintain the original code that is in the file?

Example the article tag.

nid; ?\>" class=" clearfix"\> etc..

What are the implications of removing this, if any?

# Answer
> 1 votes
Actually you're free to edit templates !

* The theme's css might depend on some tags, especially the article tag, so you could **lose layout/design**
* If you're a forward thinking brave drupalista you definitely want to keep title logic and the possibility of rendering all fields (and comments) and respect the view modes ;)

---
Tags: 7, theming
---


# Question
Title: Why is the login redirecting to the access denied page?
This question has been asked before but I see only D7 versions of the question, and none of their answers have helped me in D8.

I log in perfectly fine with Chrome or Firefox, **but IE 11** redirects to the `/user/1` page (or `/user/2`, or whoever you are logging in as) and states 'Access Denied.' If you enter incorrect credentials it states "unrecognized user/pass," but if you enter correct ones it just does the redirect and nothing happens.

This is on a fresh install of D8 RC2 and what's worse is I can do a fresh install of D8 RC2 on a different server and IE 11 login works fine. It's something about my server that's causing this. I thought it might be cleanURLs but mod-rewrite is on for both servers.

D7 solutions seem to say, check `settings.php` and the cookie\_domain or base\_url variables, but those don't seem to be a part of Drupal 8.

I have cleared IE's cache/cookies about a thousand times.

# Answer
I had the same issue but for *Chrome* and this was caused by the old cookies since it perfectly worked on the other web browser (*Opera*). When I've removed old cookies while being on that page, it worked as well.

If this doesn't work on one browser, but not on the other, definitely it's related to the invalid cookies.

If this doesn't work for all web browser, then most likely it's invalid `cookie_domain` setting in your `services.yml` file. By default Drupal automatically generates a unique session cookie name based on the full domain name used to access the site and it's sufficient for most cases. However if you're re-using across different subdomains, then you need to set your `cookie_domain`.
> 0 votes

---
Tags: users, 8
---


# Question
Title: Why can't I access my custom fields in Rules?
What I want: I want to give my products a weight and I want to calculate the total weight of the order.

What I did:

* I'm using Drupal Commerce Kickstart 7.x-2.0.
* I added a field 'weight' to the Product Variation 'Product'.
* I created a custom Rule
* Added a condition 'Entity is of type': commerce-line-item == commerce\_product
* Tried also to add or replace the condition above with the conditio 'Entity has field': commerce-line-item has field 'field\_weight'
* Create a Loop Action for commerce-line-items
* Add a Loop Action **but don't find the field 'field\_weight'**

Can someone explain me why I can't access my custom fields in Rules even though I added specific conditions?

Thanks in advance!

# Answer
> 2 votes
You're not looking for the field on the entity you've added it. You added it to the product, so in addition to your "Entity is of type" on the line item, then you need to check the type of the commerce-line-item:commerce-product for whatever product type you're expecting to find the weight field on. Only then will Rules know that that product has that field.

# Answer
> 1 votes
I know this was asked a few years ago so it's likely not relevant to Mr. B any more, however I had this same issue and spent a bit over a day figuring it out so maybe this can help someone else with the same problem.

As Ryan said the field\_weight (custom\_field) is part of commerce\_product so another link is required. The path to a custom field is **commerce-line-item:commerce-product:custom\_field**. However to get this field available within a loop, a rule component (which contains the conditions and calculations) must be called from within that loop. Also using "data comparison" rather than "has field" opens up all the fields within that entity.

To be able to reference these conditions you must have the module entity\_reference installed. www.drupal.org/project/entityreference

# Creating the rule component

* From the rules page click on **Components** tab
* Click **Add new component**
* Component plugin = **Rule**
* Add a custom name
* Variables: Date type = **Commerce Line Item**, Label = **Line Item**, Machine name = **commerce\_line\_item**
* Condition 1: Add new conditions -\> Data comparision -\> Data selector = **commerce-line-item:type**, Value = **equals**, Value = **Product**
* Condition 2: Add new conditions -\> Data comparision -\> Data selector = **commerce-line-item:commerce-product:type**, Value = **equals**, Value = **your\_product\_type**
* Action: Any action can now be used with the data selector **commerce-line-item:commerce-product:custom\_field**
* Processing or calculations that you would like done on each line item should be done here.

# Creating the rule

* Add new rule
* Name = Your rule name, React on event = **Completing the checkout process**
* Conditions are not required as these have been set up in the rule component
* Add loop variable name = **list\_item**
* Add action within loop: Action to add = Components -\> Rule: Your rule component name, Data selector = **list\_item**
* Any other actions that apply to the order as a whole can be added outside the loop

Using this method any custom fields that you have created should now be accessible for all line items with a loop.

---
Tags: commerce, rules
---


# Question
Title: Where does Drupal store its url/domain name?
I created a site using an IP address and imported a live site on another server, then I made the domain name live on the new server created with the IP address. Since then I get permissions error for the admin when logged into the domain name/ url. However if the same admin logs in using the IP address, I can see the broken links report. Otherwise it says I don't have permissions. I'm trying to reset the root domain url but uncommenting it in the settings file doesn't fix the permissions issue. I think it is something deep in the DB

# Answer
Check https://www.drupal.org/node/776864 under Troubleshooting - No user login. It might help.

Basicly, it says Enable clean URLs, check Apache config, check .htaccess, you probably want to uncomment rewritebase. Also check that "$cookie\_domain" is not set to your old domain.
> 0 votes

# Answer
The main places that the domain will be affected are:

1) DNS

2) .htaccess - Look for the RewriteBase setting AND RewriteEngine on

3) settings.php - Look for $base\_url and $base\_path

Don't forget to clear the cache after you change these settings. If you can't access the site, use `drush cc all` or login to your database and truncate all tables that start with `cache_` (sometimes clearing the cache still leaves persistent entries).
> 0 votes

---
Tags: users, uri
---