title: How to find the source of inline css

text:
# Question
Title: How to find the source of inline css
I'm kind of new to Drupal and I have to work on an already existing site using Drupal 8. In the main menu, when the links are hovered, they take the color of the background which is caused by some inline css tagged `!important` and I don't know how to find the file containing that line. Any idea on where to start?

# Answer
> 1 votes
* Enable twig debugging to pin down the used template file(s) (if the output was added inside of a template). Search the templates before the !important output for that markup.
* If you can't find it look at the preprocess functions used for those templates.

# Answer
> 0 votes
The CSS will be set in whatever theme is active at the time. To find out, in Drupal 8:

1. Log in
2. Click on "Manage"
3. Click on "Appearance"
4. Look at the list of "Installed Themes"

Once you know which theme you're using, you can search in that for your CSS.

Note that it's best practice to put your theme in /docroot/themes/ (if you're using a built-in theme, copy it to this location and edit that)

---
Tags: theming, 8
---


# Question
Title: How to enable special characters in Drupal Menu?
I am using Drupal5 and Nice Menu Module. I need to provide a URL in my Menu dropdown. There are special characters in it. When I add the complete path it works but on giving the relative path special characters doesn't show up(it gets replaced by the hex code). How can I display the special characters in Drupal Menu Dropdown as it is?

# Answer
I guess that you can review in the `nice_menus.module` file, specifically in `theme_nice_menu_tree()` module function to parse/filter/encode/replace each hexadecimal string that seems be pushed by `menu_item_link($mid)` or `$mid` string. Remember do this kind of test with a copy of your production site. I have not tried this suggestions, sorry, I only guess after a rough review of the code. I think that could be useful. - @cigotete
> 0 votes

---
Tags: navigation, 5
---


# Question
Title: How to work with field collections in $build in hook_entity_view_alter?
I have a `hook_entity_view_alter()` function inside the `.module` file for a custom content entity type that I am working on. I want to be able to conditionally show or hide fields in the canonical view of the entity based on the value of that field.

Example for a checkbox field: show it in the canonical if it was checked in the form, hide it in the canonical completely if it was unchecked in the form.

I am using `unset($build['field_id'])` for fields that are not inside field collections, and this is working fine. However, I would also like to use `unset()` for some fields that are contained within field collections.

I feel like this is probably a pretty simple thing to do and I'm just completely missing it. I've been var\_dumping $build for a while and can't figure out what to unset, or if this is even the way to do it.

edit: here is the code I am working on in {module}.module

```
function {module}_{entity}_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {

  $notAllowed = stripos($entity->get('field_category')->getValue()[0]['value'], "Not Allowed");
  $allowedConditionally = $entity->get('field_maintenance_info')->first()->getFieldCollectionItem()->get('field_allowed_on_maintenance')->getValue();

  if ($notAllowed !== false) {
    if (!$allowedConditionally[0]['value']) {
        //the next 4 lines work with fields defined at the module settings level, not inside field collections - this works!
        unset($build['field_allowed_1']);
        unset($build['field_there_are_multiple_varieti']);
        unset($build['field_variations']);
        $build['title']['#prefix'] = "No ";
    }
  }

  $protein = stripos($entity->get('field_category')->getValue()[0]['value'], "Protein");

  //this is just a loop I had for exploring $build, this outputs string(2) "25" which I am pretty sure is the field collection ID
  //'field_allowed_1' and 'field_serving_settings' are both field collections, the latter nested inside the former
  if (!($protein && !$notAllowed) && !($notAllowed && $protein2 && $allowedOnMaintenance)) {
    var_dump($build['field_allowed_1'][0]['#field_collection_item']->field_serving_settings[0]->value);
  }
}

```

# Answer
HOOK\_entity\_view\_alter() works with render elements. That are all array keys, that have no '#' sign.

At the point you are now there are only fields prepared for rendering on the top level, that means the fields, which are not in a field collection.

Fields that are inside a field collection have at this point no renderable output.

To get the render elements of these fields you have to use the hook for `field_collection_item`:

```
function mymodule_field_collection_item_view_alter(&$build, $entity, $display) {
   kint($build);
}

```

Here you will be able to unset fields inside the field collection.
> 3 votes

---
Tags: 8, hooks, entities
---


# Question
Title: Is it correct that a node and it's translations have the same node id?
I just translated a node and I saw that both nodes have the same node id. Since I cant find anything about it: is this correct?

# Answer
Yes it's correct because Drupal 8 use Entity Translation (in core) for the translations.

You can more about this in Drupal 8 multilingual tidbits 17: content translation basics

> If you already built multilingual sites with Drupal 7 that had content translation, you may notice this model is a refined version of the Drupal 7 Entity translation module (without awkward modules required like Title) rather than the Drupal 7 core content translation module. The core module in Drupal 7 keeps different copies of nodes and relates them together in a translation set. In Drupal 8 this feature is not available, instead you can configure translatability on a field (and in some cases subfield) basis. However if you configure all fields to be fully translatable, you can essentially reproduce the Drupal 7 behavior. Compared to the Drupal 7 core solution with different entity identifiers then, Drupal 8 will have the same entity identifier but a different language variant.
>
> The biggest advantage of the Drupal 8 solution is you can configure to translate as much as needed and not more. With one unified solution to translate only some fields or all fields, (contributed) modules only need to deal with one system instead of two. With storing translations under one entity, modules that don't want or need to deal with multilingual scenarios can still consider the entity as one, no need for special translation set support. That is way more flexible than Drupal 7 and best of all it applies to all kinds of content, not just nodes. It is future proof for modules you enable like rules and commerce.
> 5 votes

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


title: How do you improve Drupal performance?

text:
# Question
Title: How do you improve Drupal performance?
Drupal is fast at develop, but the performance is so poor. It is hard to reach 50 request per second.

And there are so many SQL queries in a simple web page. If you test the request time of a form submit in Drupal.org it will always take seconds to finish.

How do you improve the speed of your web site?

# Answer
Caching, caching, and caching.

Some suggestions I have previously given to a similar question on d.o.

1. Putting Varnish or another reverse-proxy in front of your http-deamon is probably the single best thing you can do.
2. During DrupalCon Copehagen, Rasmus stated that using a php opcode cache, such as APC, is one of the best things you can do to speed up PHP in general. Performance improves with newer versions of PHP. There is also additional benefits to upgrading PHP when you upgrade Drupal. From 6 to 8, Drupal will go through a major shift towards object orientation, which is also were most performance improvements happens in the newer PHP versions.
3. Memcache is a popular choice for speeding up cache, by putting the cache into memory instead of disc.
4. Panels \+ Caching combined with Cache actions can increase performance significantly, even for logged in users, as it supports quite complex logic.
5. The Entity Cache is a nice and zero-conf speed boost for anyone using Drupal 7.
6. Write-heavy sites have fewer "well established" solutions. Some options include.
    1. Moving frequent writes entirely, for example statistics, somewhere else, such as google analytics.
    2. Caching frequent write operations with a custom solution in something like NodeJS that will write to DB once every Xth second.
    3. Sacrifice the sacred ACID, and use a database like MongoDB. (See Berdir's comment below)
    4. Cluster your SQL-database. Do reads from one database, writes to another. This is native to D7 and Pressflow can help with that in D6.
> 61 votes

# Answer
These are notes from my experiences and might vary from what others experience. I predominantly use LAMP stack and have considered the same in my suggestions.

**Thumb rules for caching that I generally follow.**

1. Process Once Use Multiple Times.
2. Live with stale data when possible
3. Clear Caches infrequently and keep it very specific.
4. When possible do the changes at the lowest level in the stack. LAMP - DCCc : Linux, Apache, Mysql, PHP, Drupal Core, Contrib and custom module.

**Improve Performance of a Drupal Site (In the increasing order of complexity)**

5. Keep the core updated, contrib module and themes updated. Yes it matters.
6. Install APC on your server. (Moved to top based on suggestion from Letharion)
7. Page Caching : admin/config/development/performance Difference between Minimum cache lifetime and Expiration of cached pages
8. Block Caching https://drupal.org/project/blockcache\_alter Caching options for all the blocks.
9. Aggregate javascript and css files - Front End Improvements https://www.drupal.org/project/advagg
10. Disable Unnecessary modules. Every module adds to the amount of code that needs to be available for a page load. And it also increases the number of lookups. Wherver possible use a generic module in place of multiple module that does specific functionalities.
11. Cache Views content - Content aware caching for Views https://www.drupal.org/project/views\_content\_cache
12. Disable DB logging - Use https://drupal.org/project/syslog\_ng
13. Reduce 404 Errors - http://www.brokenlinkcheck.com/
14. Fast 404 Responses - https://drupal.org/project/fast\_404 \- Try handling at server level.
15. Client Side Validations - https://www.drupal.org/project/clientside\_validation
16. Compress Image - https://www.drupal.org/project/imageapi\_optimize
17. Lazy Loading of Images - Don’t load unnecessary images - https://www.drupal.org/project/lazyloader
18. Use Sprite Sheets - https://www.drupal.org/project/spritesheets
19. Set Minimum Cache Life Time Value to a higher number and use cache clearing modules to clear the caches for specific pages - Whenever I edit/update a node all the page caches for anonymous user are lost
20. Use Devel Module to watch queries.
21. Rewrite Views Queries / avoid Views if its a overkill.
22. XHProf - https://www.drupal.org/project/XHProf
23. FPM, HHVM.
24. DB Profiling and Tuning - https://www.drupal.org/project/dbtuner
25. **Use Boost**, don't Bootstrap DB if not required. https://drupal.org/project/boost For most of the small to medium sites Boost is good enough and you may not need Reverse Proxies or so.
26. Use CDNs - https://www.drupal.org/project/cdn Its easy to set up.
27. If your cache tables are huge use Memcached - If you can install memcached and set up RAM for it, it is not as complex as it sounds.
28. Etags - Configure Etags properly. https://developer.yahoo.com/blogs/ydnfiveblog/high-performance-sites-rule-13-configure-etags-7211.html
29. **Use Reverse Proxy Server** \- Varnish(at-least for assets). Helps a lot if most of your users are anonymous.
30. Compressed transfer - Enable gzip compression
31. Keep Alive - Use Persistent Connections where possible.
32. Progressive JPEGS -
33. CACHING IN CODE - Eaton’s blog is awesome. http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
34. Implement Cache Warming - https://www.drupal.org/project/cache\_warmer \- Cache Warm the pages before the end user hits them.
35. Master Slave DB Config - https://www.drupal.org/project/autoslave makes it easier for you to set up one.
36. Database Clusters - https://stackoverflow.com/questions/1163216/database-cluster-and-load-balancing
37. Load Balancers -http://en.wikipedia.org/wiki/Load\_balancing\_(computing)
38. Use heuristic Cache Warming - https://www.drupal.org/project/cache\_graceful
39. Authenticated User Caching - https://www.drupal.org/project/authcache
> 23 votes

# Answer
Boost module is also quite useful, it creates static file caches from your webpages. It's mostly for websites with lots of Anonymous user traffic.

> Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic. For shared hosting this is your best option in terms of improving performance. On dedicated servers, you may want to consider Varnish instead.
>
> Apache is fully supported, with Nginx, Lighttpd and IIS 7 semi-supported. Boost will cache & gzip compress html, xml, ajax, css, & javascript. Boosts cache expiration logic is very advanced; it's fairly simple to have different cache lifetimes for different parts of your site. The built in crawler makes sure expired content is quickly regenerated for fast page loading.
> 17 votes

# Answer
It worth mentioning, if you are using SQLIte database driver you might have to disable disk synchronization.

```
/**
 * Implements hook_init().
 */
function HOOK_init() {
  db_query('PRAGMA synchronous = OFF');
}

```

On some server configurations it will improve performance dramatically.
> 4 votes

# Answer
The secret of Drupal performance is in **caching** and following the good practices. Suggestions:

### Drupal back-end

* Enable caching in *Performance* section.
* Check Performance and Performance and Scalability Checklist modules.
* Check Drupal 7 Performance Optimization Options and Checklist.
* Disable unused and non-production modules (such as Devel, Views UI, Rules UI, etc.).
* Disable unstable modules.
* Disable statistics.
* Disable dblog core module and replace with syslog.
* Disable Update Manager core module.
* Cron: Use Drupal's builtin cron, not poormanscron (consider Elysia or Ultimate cron).
* Views: Use cache for views at different layers (database query, markup, time-based).
* Blocks: Use block caching if your view is a block (per page, user, etc.).
* Blocks: Consider tweaking cache settings per block by Block Cache Alter module.
* Panels: Use cache as much as possible (for D7 check PCC & PHC modules).
* Entity: Enable Entity cache.
* When using multiple environments, consider missing module which can improve page load.
* Enable authenticated users page caching with Authcache module.
* Avoid redirects which slow down the user experience.
* Enhance cache invalidation by using Expire module.
* Use PHP profiling before production (e.g. XDebug).

### Drupal front-end

* Minimalize HTTP Requests by:
    + Enable JS/CSS aggregation in *Performance* section.
    + Use CSS Sprites for reducing the number of image requests.
    + Use small images as inline data (URIs in a stylesheet).
    + Use Image maps to combine multiple images into a single image.
    + Also consider using lazy images loading (see: Image Lazyloader).
    + Install BigPipe module to reduce load times.
    + Consider Lazy loading vs Lazy evaluation.
    + See: Browser Cache Usage - Exposed!
* Consider making some JavaScript and CSS External (in some cases it's quicker).
* Minify JavaScript and CSS (see: Speedy module). Avoid inline.
* When referencing a JS, use either `defer` or `async` attributes.
* Minimize the number of iframes.
* Optimize images, fonts, CSS Sprites, make favicon small cacheable and reduce cookie size.
* Reduce the number of DOM elements and cache references to accessed elements.
* Make your 404 pages load faster by using *Fast 404* module.
* Enable front-end resources aggregation and caching with Advanced CSS/JS Aggregation.
* Put stylesheets at the top and scripts at the bottom.
* Add an *Expires* or a *Cache-Control* header, also *ETags* to reduce the responses.
* Use GET for AJAX and make them cacheable.
* Preload and Post-load components to take advantage of the time the browser is idle.
* Sometimes splitting components across domains can maximize parallel downloads.
* Don't scale images in HTML and keep components under 25k.
* Avoid Filters, CSS Expressions, HTML elements with empty src or href.
* Use reverse proxy to debug your web requests (e.g. Charles).
* Use tools such as Y-Slow and PhantomJS for basic performance checks.
* Use Google PageSpeed tools to analyze and optimize your website.
* Read about W3C Navigation Timing specs (GitHub).

### PHP

* Enable PHP caching (e.g. *OpCache*, *APC*) and tweak settings.
* Consider using PHP-FPM instead of mod\_php plus Nginx instead of Apache.

### Database

### Server

### High-traffic websites

If you expect high load for your website, use Varnish. Consider also using CDN.

Read more at: Real world experience in scaling and tuning performance

---

Further resources:
> 3 votes

# Answer
There is a book named High Performance Drupal that's provides best practices, examples, and in-depth explanations for solving several performance and scalability issues. You’ll learn how to apply coding and infrastructure techniques to Drupal internals, application performance, databases, web servers, and performance analysis.

In the Performance and Scalability in Drupal 7 article you can find some examples about Drupal 6 and Drupal 7 and the following list:

> Drupal 7 performance and scalability projects to watch:
> 2 votes

# Answer
There have been a lot of tweaks to optimize the performance of your Drupal site - but not all are imperative though. We have to look around for certain alternatives and techniques that would lead to an optimize platform of Drupal. Cache, yes, it is a way to optimize the website through different means but some more add-ons and tips can increase and tune up your website with no hassle free processes to undertake.

We have published a similar article to our website recently which i believe might help you in doing some tweak work.

Source: http://www.cloudreviews.com/blog/drupal-performance-optimization-tips
> 1 votes

# Answer
There are some possibilities to improve Drupal speed for a reasonable level by without installing any new modules. Yes, Drupal has performance configuration.

1. You can set this up by going to: YourSiteDomain/admin/config/development/performance
2. Enable 'Cache pages for anonymous users' under Chaching
3. Minimum cache lifetime: 1 day (If you don't do regular updates)
4. Expiration of cached pages: 1 day (If you don't do regular updates)
5. Enable 'Compress cached pages'
6. Enable 'Aggregate and compress CSS files'
7. Enable 'Aggregate JavaScript files'
8. Once this configurations are set, Go to: YourSiteDomain/admin/reports/status
9. Check for if there is any permission issues for 'css' and 'js' directories
10. Correct the permission as defined on the Status Report page

And now you are done with the speed optimization for your drupal 7 site.

There are few online speed testing tools to check the speed. Make sure to use one of the speed check tool and run a test before updating the above settings. And once after you have updated the performance setting run the speed test again. You will definitely see improvement.

Pingdom and the HTTP Fox (FireFox plugin) are the best tools to check the site speed.

The above settings not only caches your pages for anonymous users, It also compresses the CSS and JS files. Example if your site is loading 80 files, post these settings the number of requests will cut down to at least by 50%, So here you have 2x speed improvement on your Drupal site.
> 1 votes

# Answer
As a backend developer there is always room to improve your code to boost the performance of the website. Some guidelines for backend developers could be:

1) Clean up your watchdog table

2) Don't abuse the variable API

3) Make Fewer or Better HTTP Requests

4) Keep your "dot module" short

When it comes to font-end and site builders much more can be achieve but it is important to take performance into consideration from every point of view.

Source: Optimize before you go live
> 1 votes

# Answer
An unoptimized Drupal 7 site with 2 GB of RAM can serve about 20-25 requests per second satisfactorily. If you want to go beyond that, the site will require some tweaking. What you tweak depends on whether most of the users on the site are anonymous or authenticated. Here are the top things you can do for performance improvement:

**Site is serving mostly anonymous users:**

1) Definitely install and configure APC, memcache and entitycache.

2) Put Varnish proxy in front of the webserver. It takes about 30 minutes to install and configure but will dramatically lower your page load times. In fact, Varnish can handle about 300 requests per second on a 2 GB machine if all the pages are cached. Use Expire module to expire only selected pages on content update/deletion.

3) Use Advanced CSS/JS Aggregation module to aggregate CSS and JS files. Try moving all the JS files to the bottom of the page. But note that this may break your site so implement this on production after thorough testing. Also experiment with inlining critical CSS. In my experience, it will decrease page load time by about half a second.

4) CSS/JS/images should have far future expiry header. This will ensure that browsers won't request for the same CSS/JS/images again and again.

5) Make sure that webserver is serving compressed pages/CSS/JS.

After implementing the above 5 steps, your 2 GB RAM server should be able to server 50 requests per second pretty easily.

**Site is serving mostly authenticated users:**

Optimizing such a site is more complex. Such sites fall in one of the two sub-categories for optimization purposes:

(a) Most of the pages on the site are identical except 1 or 2 blocks that have user-specific information. For e.g. Drupal Commerce site.

(b) Most of the pages are completely customized for the user. For e.g. Drupal Commons site.

If your site falls in category (a), then apply most of the techniques that we discussed for the site serving mostly anonymous users. The only difference is that for non-admin pages, Varnish will need to remove the SESSION cookie from the header and serve cached pages. Use AJAX Block module to server blocks with user-specific information using AJAX. This way most of the page will be served extremely quickly using Varnish and then user-specific information will be served over AJAX.

If your site falls in category (b), then use Authcache module. I prefer not to use it as much as possible because it requires quite a bit of configuration and maintenance. But it does work really well. It won't be as fast as using Varnish but it will be able to handle 50 requests per second that you are looking for.

If you are looking to go above and beyond what we have discussed here, then have a look at Drupal Performance Optimization Checklist. Disclosure: It is written by me. It cites an exhaustive list of things you can do to make your Drupal site blazing fast.
> 1 votes

---
Tags: performance
---


# Question
Title: check mark disappear after moving to new ip address
I moved my web server to another ip address. But "Advanced CSS/JS Aggregation" still refer the images from the old ip address. All the checkmark in my dashboard are disappeared, no matter for radio or checkbox.

Here is an example:

**Update:**
I checked the console and found an error message: "Failed to load resource: net::ERR\_CONNECTION\_TIMED\_OUT".
Here is a screenshot for error from console:  What do I need to do??? How can I update the css and js file? Does anyone have any idea?
Thank you for all helping.

# Answer
Thank you for all your help. I found out the reason for a long time searching. Cause I moved an existing complicated website to a new ip address. The Advanced CSS/JS Aggregation module does affect images, css and js.

Here are some solutions that I found might be useful:

* **Check $base\_url in setting.php file** (might be set as old url/ domain name/ ip address)
* **Uncommend "#RewriteBase /" in .htaccess file then flushing the cache** (Do not try this unless you know what you are doing)
* **Unable Advanced CSS/JS Aggregation Module** (It will compass your js/css, this might cause some problem. Just unable it, use your original css file) -- This works for me.

Here are some references I used here:

1. Need help changing domain/url on existing drupal site...
2. images not showing / displaying after moving to localhost (Wamp Server)
> 0 votes

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


# Question
Title: How to add a custom marker icon on gmap using the gmap module?
I want to add a custom marker to the list of markers on the gmap module I tried the following link which is as described below :http://mydrupaltricks.be/article/drupal-7-custom-gmap-markers but it did not worked

```
<?php
$markerdir = variable_get('gmap_markerfiles', drupal_get_path('module', 'gmap') . '/markers');
?>

```

By setting the "gmap\_markerfiles" variable, we can change the location of our new markers folder. We have to set this variable only once so we put the code in our "my\_module.install" file.

```
<?php
/**
* Implements hook_install().
*/
function my_module_install() {
  variable_set("gmap_markerfiles", drupal_get_path("module", "my_module_name") . "/markers");
}
?>
Now we can create the new "markers" folder in our new module. Gmap expects a .ini file to describe all your markers. We add the file "markers/my_module.ini".
; Defaults
[defaults]
; Note: An empty shadow property will break IE.
; Leave it commented out if you aren't supplying an image.
; shadow = ""
anchorX = 15
anchorY = 17
infoX = 17
infoY = 6

; Marker sets

[drupal]
name = "drupal"
sequence = "marker-green.png"

[salepoint]
name = "salepoint"
sequence = "marker-green.png"

[headquarter]
name = "headquarter"
sequence = "marker-green.png"

[shop]
name = "shop"
sequence = "marker-yellow.png"

```

# Answer
You do not really need to write your own module (unless it does something out of the box) in order to use custom markers.

Here is an guide how you can do that (I assume we use gmap module and views module to display google map.

1. Upload you custom markers to Drupal website, f.x. to your theme folder (i.e. /sites/all/themes/**yourtheme**/images/markers or another location that suit you more.
2. In that folder you need to create an **INI** file and declare your custom markers (give them name etc). See example with 1 custom marker below.
3. Go to gmap settings **/admin/config/services/gmap** and specify folder where you saved your marker image and ini file (see image below).
4. Now make sure you saved everything and cleared cache.
5. Go to your view and in the settings you must get your custom marker available (at the bottom).
> 11 votes

# Answer
Just thought I'd point out in the this somewhat long-running thread that, due to an update, Dmytro Pastovenskyi's answer is no longer valid in 7.x-2.11. The "Custom markers path" field is still present in the UI form at /admin/config/services/gmap, however any value entered there is effectively ignored. What I did to get it working:

1. Install the Libraries API module (https://www.drupal.org/project/libraries)
2. Create a directory in sites/all/libraries called "gmap\_markers"
3. Put your ini file and any related images in this folder
4. Clear the caches
> 10 votes

---
Tags: 7, google-maps
---


title: Loading current revision node

text:
# Question
Title: Loading current revision node
How do I construct an entity condition so that it loads current revision of all nodes? This is my attempt.

```
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'xxxxx')
->fieldCondition('xxx_module','tid', $tid,'=')
->age(FIELD_LOAD_CURRENT)
->execute();

```

Instead of loading the current revision, it loads the published revision.

# Answer
> 0 votes
By default, `EntityFieldQuery` checks the currently logged-in user has the permission to access the queried entities. This is could be undesired, especially when the queried entity is not shown to the users, for example when a module just needs to get a list of entities to delete them.

To avoid `EntityFieldQuery` checks the currently logged-in user has the permission to access the entity, you need to use the following method:

* `addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')` for Drupal 7.15 or higher version
* `addMetaData('account', user_load(1))` for previous versions

Assuming you are using any version higher than 7.15, you code should be the following one.

```
query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'xxxxx')
  ->fieldCondition('xxx_module','tid', $tid,'=')
  ->age(FIELD_LOAD_CURRENT)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
->execute();

```

There could be a module that alter the query done from `EntityFieldQuery` and doesn't respect that tag; in that case, the query could still not return an entity revision that is not published.

---
Tags: database, nodes
---


title: db_fetch_object returning null

text:
# Question
Title: db_fetch_object returning null
This is the line:

```
$row = db_fetch_object($result);

```

While $result is valid but $row is getting a null value which I've checked with is\_null.

As per this function's @return value, it can only return FALSE in failure.

Also mysql\_db\_object states the same.

What could be the reason it is returning null?

# Answer
Actually, `db_fetch_object()` could also return `NULL`, contrary to what the documentation says. The documentation assumes you aren't passing to the function a value that for PHP is equivalent to `FALSE`, for example `NULL`, an empty array, or an uninitialized variable. If the function gets a value that for PHP is equivalent to `FALSE`, the function will not execute any instruction, and it will return `NULL`.

```
function db_fetch_object($result) {
  if ($result) {
    return mysql_fetch_object($result);
  }
}

```

The same is true for other database engines, for example PostgreSQL, which uses the following function.

```
function db_fetch_object($result) {
  if ($result) {
    return pg_fetch_object($result);
  }
}

```

This is usually not a problem, since the function should normally be called as in the following snippets.

```
 if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
    $block['subject'] = check_plain($category->title);
    $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = %d ORDER BY i.timestamp DESC, i.iid DESC', $category->cid, 0, $category->block);
    $read_more = theme('more_link', url('aggregator/categories/' . $category->cid), t("View this category's recent news."));
  }

```

```
  while ($item = db_fetch_object($result)) {
    $items[] = theme('aggregator_block_item', $item);
  }

```

In both the cases, the control statements will not be executed, since for them `NULL` is equivalent to `FALSE`.
> 0 votes

---
Tags: 6, database
---


title: Add related field node limit

text:
# Question
Title: Add related field node limit
I am using drupal search api with facet api modules.

I am trying to add more than 3 related node in my search index, but I am limited to max 3 nodes.

I have articles, styles, brands, designers, themes content nodes. I created a search index on articles on the fields page; after adding 3 nodes, the fourth node doesn't show. The reason I am doing this is to have title of nodes as facets.

I was able to add 4 related nodes on another machine. Is there any limitation to the number of related nodes that can attached to the index?

# Answer
> 0 votes
I found a solution instead of related nodes. I am using default node field attached with articles and have cache mapping of other content types with titles and id. And implemented custom code segment encoding which replaces id with title from mapping.

---
Tags: search
---


# Question
Title: How to Create a Table of PDFs with Views?
I've been tasked to develop my company's intranet with Drupal. One of the key items is to allow our HR department to upload job openings (PDF's) to display on site. I'm envisioning having this table output using Views but I'm not sure how to set up the front end for the Department to publish the files.

They need to be able to upload a file, give it a name (Job title) & date of upload. Table will then populate with them.

Any guidance would be greatly appreciated, I'm new to Drupal.

Regards Tony

# Answer
> 3 votes
Generally there would be two steps to this in Drupal 7.

1. Create a content type with the fields you need
2. Create a view to pull in that content

In your content type settings, manage the fields, and you can add a file attachment field (for uploading the PDF) and a text field for entering the job title. Date of upload is automatically created in the sense that your HR people will create a new piece of content (of this new type) when they want to upload a new job opening, and you can use that piece of content's date last edited data for that field. You can enable display of that info in the view settings under Fields.

Once you get your view correctly displaying all the content from your new content type, you can work on styling it as a table with CSS.

---
Tags: 7, views, entities, files
---


# Question
Title: Content type errors - "The Byline text" error
I'm having trouble creating a content type. I can't seem to figure out to fix these validation errors. I'm not user what they mean.

```
The Byline text - Full content view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Teaser view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - RSS view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Search index view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Search result highlighting input view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Colorbox view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Revision comparison view mode is using the following invalid tokens: [node:author], [node:created].
The Byline text - Tokens view mode is using the following invalid tokens: [node:author], [node:created].

```

# Answer
> 0 votes
I found the issue. Event though I had unchecked 'Display author and date information.' under 'Display settings', I still needed to empty the text fields or at least remove the tokens from them.

---
Tags: views
---


# Question
Title: What are the variables does one search for when trying to render a custom form?
In Drupal 8, the following code renders the node creation form (node/add/page) when integrating it into a custom module:

```
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create(['type' => 'page']);

$form = \Drupal::service('entity.form_builder')->getForm($node);

print \Drupal::service('renderer')->render($form);

```

We know the module in question is the Node module, which generates the content type page. What should I do to render the user creation form (/admin/people/create)?

I can easily change the code to the following, and replace `'node'` with `'user'` and `'page'` with `'user`'.

```
  ->getStorage('user')
  ->create(['type' => 'user']);

```

This would now render the user creation form. For me to come to the conclusion that it would render the user form was only a guess and apparently it works. But this problem solving approach will not work if I wanted to render some other form that might not be so obvious.

What does one have to grep for in the code base or other investigative work to come to the conclusion of the following 2 lines in the above code?

# Answer
> 1 votes
To answer your explicit question (and to reiterate what Clive said), there's no one thing that you could grep to conclude the arguments to change for the `getStorage()` & `create()` methods.

The above solution assumes:

1. You're looking for an entity form.
2. You're aware that `EntityFormBuilderInterface::getForm()` needs an entity object.
3. You can build an entity object with `Drupal::entityTypeManager()`.

It's a specific solution to building *entity forms*. If you're looking for a method to find any *arbitrary constructed form*, this solution isn't going to help here.

The most generic thing one could search for to find such a form (an invoke it for rendering), is probably a label that is unique to the custom form, but it really depends on how the form is constructed (e.g. `EntityFormBuilderInterface::getForm()`, `FormBuilderInterface::getForm()`, or some arbitrary form array builder function).

If you're familiar with the pattern of construction, there might be some specific terms to search for (e.g. searching for classes implementing `FormBuilderInterface` or `EntityFormBuilderInterface`), but there's not going to be one search pattern that works for all forms.

---
Tags: forms, 8
---


# Question
Title: Is it possible to assign attributes to different roles?
So let's say I have a student role. And I want assign variables to student such as attendance and grade.

Then i want a teacher role that can assign this attendance and grade to their students.

We can pretend that there is only one teacher and there are many students.

How would this be done? I know that you can edit fields under Config-\>People in drupal 7, but this causes there to be the same fields for all users.

In a similar way, is it possible to have like a "Student Page' where a student sees his/her own grade but not any one else?

I've been trying to find similar function but it seems to not exist.

Thanks

# Answer
> 0 votes
Yes. There many ways to go about this but the Profile2 module is one that covers the entity field data (variables) per a specified user role.

> Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!

Your your student role can be assigned to have to have a student profile which a Teacher can edit, but only a student can view. It has the additional permission *View Own Profile...* which should restrict students from seeing other profile pages.

---
Tags: users
---


title: Css files of liberary can not be load

text:
# Question
Title: Css files of liberary can not be load
I'm trying to add Zurb Foundation framework to my theme library file. However, when I add the following code to my library, the java script file load without any probleme or difficulty but css files only can not be load.

I would be grateful to hear what is the problem with the code and what is the right way to load a css of the library?

This is my theme folder structure (Zurb Foundation folder location):

```
|-Theme Name
|  |-includes
|  |  |-foundation
|  |  |  |-css
|  |  |  |-js

```

Library file:

```
foundation:
  version: 6.x
  css:
    includes/foundation/css/app.css: {}
    includes/foundation/css/foundation.css: {}
    includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

```

\[theme\_name\].info.yml file:

```
name: Theme Name
type: theme
core: 8.x
base theme: classy
libraries:
  - Theme Name/foundation
  - Theme Name/global

```

And finally, I uncheckmark **Aggregate CSS** and **Aggregate JavaScript files** boxes in performance, flush caches and clear my browser cache.

screenshot of Source page:  As you can see the javascript files load witout any problem.

# Answer
You can follow document

> You may notice the 'theme' key for css which is not present for js. This indicates the style type the css file belongs to.
>
> You can set CSS weights with 5 different levels of styling:

* **base** key assigns a weight of CSS\_BASE = -200
* **layout** key assigns a weight of CSS\_LAYOUT = -100
* **component** key assigns a weight of CSS\_COMPONENT = 0;
* **state** key assigns a weight of CSS\_STATE = 100
* **theme** key assigns a weight of CSS\_THEME = 200

> This is defined by the SMACSS standard. So here if you specify theme it means that the CSS file contains theme related styling which is pure look and feel. More info here. You **cannot use** other keys as these will cause strict warnings.

In your case you can use key **theme**

```
foundation:
  version: 6.x
  css:
    theme:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

```
> 4 votes

---
Tags: 8, theming
---


# Question
Title: How to insert any view inside of another view?
I wonder how to insert any view inside of another view in Drupal 8?

Simply, we have products pages, which contains product details pages in views. When I click on any product detail page from view, it should open window with text which is set up in one view and display another second view with related receipts.

Both views should be filtered according to Taxonomy reference.

How can I achieve this?

# Answer
## OPTION 1

**If you want to display it after your current view** In Views, click on +Add button and select `Attachment`.

Now go to your page view in the FOOTER add `Global: View area` and select your attachment.

## OPTION 2

Download and enable Twig Tweak

**If you want this as a field**, add a Global: Custom text and put:

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

```

Ex: `{{ drupal_view('frontpage', 'page_1') }}`

OR

**If you want to display it after your current view**, in footer add Global: Text area, checkmark ☑ Use replacement tokens from the first row put `{{ drupal_view('view_name', 'machine_name') }}` and select FULL HTML as your text formatt.
> 7 votes

# Answer
I am not sure, if you need views inside view for your purpose. But there is a module for Views inside view,

Views Field View

> There are a lot of cases in views where you want to embed a list inside each row. One example could be, you have a list of groups, and for each groups you want to list the first and last name of all of their members.
>
> This can be achieved with this module, as views\_field\_view allows you to embed one view into another view and pass arguments along.

If you want some tutorial on that,

1. Drupal Views Inside Other Views
2. Create a View with Views inside in Drupal 7
> 1 votes

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


# Question
Title: Webform calculator (I need to delay the result)
https://www.drupal.org/project/webform\_calculator

Hello, is there a way to delay the calculation for performance purpose ? The problem is that I have a TON of formulas being calculated every time I type inside the inputs, and this is making the whole thing very SLOW.

**I need something like: "Wait 2 seconds after keyup and mouseup \> show formula results"**

# Answer
Well, this is how I managed to delay the calculation results in webform\_calculator.js line 12, 13, 14

```
setTimeout(function(){
  Drupal.webformCalculator.evaluateAllFormulas();
}, 3000);

```
> 1 votes

---
Tags: javascript, webforms
---


# Question
Title: How to create a layout with different size grid theming with Views?
I recently saw this Wordpress website.

I am curious on how to create such a layout with different columns for each row in views.

Can someone help me out with this what to do?

# Answer
This you can do using combination of Views and Panels. Views will provide whatever data you want. This will be the easiest and straight.

* **Views** is for -\> Fetching the data
* **Panels/DS** is for -\> To arrange Display layout

**Panels**,

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout.

Or instead of Panels, Display suite also,

**Display suit**,

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How to set the "Read More" link (in Rewrite Rules for Body field) to point to the node url instead of the title?
I have created the blog as a view in Drupal 7.14 site. On my main blog page, I want to show 5 trimmed versions of the posts. I have added the following fields for the main blog page view - Title, Author, Post date, Body. In the Body field, I select the following options in "Rewrite Rules" section - Trim field, add read more text. Btw, I have selected the default format for the body. I add the "More link path" as \[title\] after referring to the Replacement Patterns.

When I apply the changes, I see that the "Read More" links to the actual title and not the url that is linked to the title. Example, it will create a link "www.mysite.com/My post title" instead of "www.mysite.com/blog/my-post-title".

In the Title field, I have selected the option to link the field to original piece of content.

The same setup worked on my localhost and it is not working on my Joyent server. Am I missing something? I have spent several hours looking at concepts like Pathauto, replacement tokens, etc, but no help.

# Answer
Just change the More link path to the **node/\[nid\]**

Add field nid to the views field and exclude from display. Make sure nid is above body field. Re-arrange the fields by clicking on select list next to field label and drag nid field to top of body field. It works !

Drupal l function while generating links will convert automatically to path alias blog/blog-title !
> 15 votes

# Answer
You can also add a separate 'Content:Link' field:

Then select the text you want to display on the 'Readmore' link (you may select a fixed text, or a dynamic text \[like nodetitle\] when you rewrite the field results).
> 6 votes

# Answer
I had the same problem - my assumption was the same as the OP's in that the "title" field/token would link, but it didn't, even when it was set to link to the original piece of content. I also tried the "link" field which also didn't work (same effects as reported above). It turns out the field you need is "path" - this has to be positioned above the body field (or whichever field it is you want to rewrite as the link to the node) in the fields list, and excluded.
> 0 votes

---
Tags: 7, views, tokens
---


# Question
Title: Why doesn't my custom entity work in an entity reference field?
I've got a custom entity with bundles that I want to be able to use in an entity reference field in a different entity. So, I've got an the content entity for my entity type:

```
/**
 * Defines the Redacted teaser entity.
 *
 * @ingroup redacted
 *
 * @ContentEntityType(
 *   id = "redacted_teaser",
 *   label = @Translation("Redacted teaser"),
 *   bundle_entity_type = "redacted_teaser_bundle",
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\redacted\RedactedTeaserListBuilder",
 *     "views_data" = "Drupal\redacted\Entity\RedactedTeaserViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "add" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "edit" = "Drupal\redacted\Entity\Form\RedactedTeaserForm",
 *       "delete" = "Drupal\redacted\Entity\Form\RedactedTeaserDeleteForm",
 *     },
 *     "access" = "Drupal\redacted\RedactedTeaserAccessControlHandler",
 *     "translation" = "Drupal\node\NodeTranslationHandler",
 *   },
 *   base_table = "redacted_teaser",
 *   admin_permission = "administer RedactedTeaser entity",
 *   translatable = FALSE,
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "bundle" = "type",
 *     "langcode" = "langcode",
 *     "user_id" = "user_id",
 *     "created" = "created",
 *     "changed" = "changed",
 *   },
 *   links = {
 *     "canonical" = "/admin/redacted_teaser/{redacted_teaser}",
 *     "edit-form" = "/admin/redacted_teaser/{redacted_teaser}/edit",
 *     "delete-form" = "/admin/redacted_teaser/{redacted_teaser}/delete"
 *   },
 *   field_ui_base_route = "entity.redacted_teaser_bundle.edit_form",
 * )
 */

```

And the config entity for my bundles:

```
/**
 * Defines the Redacted teaser bundle entity.
 *
 * @ConfigEntityType(
 *   id = "redacted_teaser_bundle",
 *   label = @Translation("Redacted teaser bundle"),
 *   bundle_of = "redacted_teaser",
 *   handlers = {
 *     "list_builder" = "Drupal\redacted\RedactedTeaserBundleListBuilder",
 *     "form" = {
 *       "add" = "Drupal\redacted\Form\RedactedTeaserBundleForm",
 *       "edit" = "Drupal\redacted\Form\RedactedTeaserBundleForm",
 *       "delete" = "Drupal\redacted\Form\RedactedTeaserBundleDeleteForm",
 *       "default" = "Drupal\redacted\Entity\Form\RedactedTeaserForm"
 *     }
 *   },
 *   config_prefix = "redacted_teaser_bundle",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}",
 *     "edit-form" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}/edit",
 *     "delete-form" = "/admin/structure/redacted_teaser_bundle/{redacted_teaser_bundle}/delete",
 *     "collection" = "/admin/structure/visibility_group"
 *   }
 * )
 */

```

I then try to use that in an entity reference field in another entity:

```
->setSetting('target_type', 'redacted_teaser')

```

But when I go to create an instance of this entity, the reference field isn't getting any of my bundle instances.

I've also try adding an entity reference field to a content type in the UI. The field settings recognize my defined bundles when I'm setting up the field, but when I go to create a node of that content type the entity reference field doesn't pick up any of my bundles instances there, either. I've compared my annotations to those in Node and NodeType and don't see that I'm missing anything. I've also stepped through with Xdebug, and I can see that when my create form loads, it's getting "redacted\_teaser" as the expected type for the reference field.

Everything else about my entity and bundles works just as expected.

# Answer
> 1 votes
You have no label key, so autocomplete doesn't know what to search for.

---
Tags: 8, entities
---


# Question
Title: Is drupal bootstrap phases will be called for each page request or its only once on site load?
All drupal bootstrap phases will be called on each page load or only one time when site will load.

# Answer
Since Drupal is a PHP application, there isn't a persistent process running on the server for it (unlike some other language frameworks). This means that Drupal will bootstrap for each request it handles. This can be a page load, a request to make an image derivative, an AJAX handler, a 404 page, and other things that aren't thought of as normal pages. It also means that concurrent requests will result in concurrent PHP execution.

However, with the way it is designed, there are various levels of bootstrap, and different requests don't require the full bootstrap. For example, a page request from a cold cache will require the full bootstrap. When the page cache is enabled, and there is a hit, it will stop at `DRUPAL_BOOTSTRAP_PAGE_CACHE`.
> 0 votes

---
Tags: bootstrapping
---


title: How to Query MySQL Database Module

text:
# Question
Title: How to Query MySQL Database Module
**Could you help help me correct the follow piece of code**

I am getting the following error.

"The website encountered an unexpected error. Please try again later."

```
public function __construct(Connection $connection) {
    $this->connection = Database::getConnection();
  }
public function hello($state = '0') {
    $sqlQuery = $connection->select('pop11', 'C2011')
    ->fields('C2011', array('male', 'female'))
    ->condition('C2011.sCode', '10', '=');
    $data = $sqlQuery->execute();
    if ($data) {
        $results = $data->fetchAll(\PDO::FETCH_OBJ);
        foreach ($results as $row) {
        echo "Field a: {$row->male}, field b: {$row->female}";
        }
    }else{
        return array('#title' => 'Error', '#markup' => 'Could not Find. What you are Looking for.',);
    }

}

```

# Answer
`$connection` doesn't exist in the context of `hello()`. You need to use `$this->connection` if you're wanting to use the Connection that's built in your object.
> 1 votes

# Answer
Finally I have the solution after trying a lot of example code from different websites...

namespace Drupal\hello\_world\Controller;

use Drupal\Core\Database\Connection;

class HelloWorldController {

```
public function hello($state = '0') {

   $sqlResult = db_select('pop11', 'C2011')
    ->fields('C2011', array('male', 'female'))
    ->condition('C2011.code', '10', '=')->execute() ->fetchAll();

    foreach ($sqlResult as $row) {
        echo "Field a: {$row->male}, field b: {$row->female}";
    }

}

```

}
> 0 votes

---
Tags: 8
---


# Question
Title: How can I get the roles for the currently logged-in user?
How can I get the roles for the currently logged-in user, in Drupal 8?

In Drupal 7, it could be achieved by accessing `$GLOBALS['user']->roles;`.

# Answer
> 52 votes
Something like:

```
$current_user = \Drupal::currentUser();
$roles = $current_user->getRoles();

```

will return an array like:

```
Array
(
  [0] => authenticated
  [1] => administrator
  [2] => some_other_role
)

```

where the array values are role IDs (equivalent to the machine name of the role in Drupal 7). In OO code, use the appropriate mechanism get the current user from the container, eg

```
$current_user = $container->get('current_user');

```

---
Tags: users, 8
---


title: File field URI to URL link in module

text:
# Question
Title: File field URI to URL link in module
I'm creating a custom file field display formatter module.. https://www.drupal.org/sandbox/vincer/2779871

Right now it's just printing the URI as..

```
public://my-file.mid

```

I'm trying to get the default output that I would get by using the File module - a full path as a link, like..

```
http://my-site/sites/default/files/my-file.mid

```

The field\_formatter\_view looks like..

```
function fieldmidity_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'midi_formatter') {
    foreach ($items as $delta => $item) {
      $element[$delta] = array('#markup' => $item['uri']);
      // Options for $item; filename, uri, description, filesize, timestamp, fid, uid
    }
  }

  return $element;
}

```

Based on code I see in the File and Field modules, I'm suspecting that the solution might be more complicated than the approach that I'm attempting.

Any thoughts would be appreciated.

# Answer
Use this:

```
function fieldmidity_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'midi_formatter') {
    foreach ($items as $delta => $item) {
        if ($item['uri']){
            $element[$delta] = array('#markup' => file_create_url($item['uri']));
        }else{
            $element[$delta] = array('#markup' => $item['uri']);
        }
      // Options for $item; filename, uri, description, filesize, timestamp, fid, uid
    }
  }

  return $element;
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: How to fix error Undefined index: parent in taxonomy_form_term_submit()?
I got below error on my site recently.

> Notice: Undefined index: parent in taxonomy\_form\_term\_submit() (line 829 of /var/www/Sites/xxxxx/modules/taxonomy/taxonomy.admin.inc).

I google it and find there is an old issue but seems nothing solved.

In the issue, @Cracu did mention some part of core code may cause this error:

```
  if (!variable_get('taxonomy_override_selector', FALSE)) {
    $parent = array_keys(taxonomy_get_parents($term->tid));
    $children = taxonomy_get_tree($vocabulary->vid, $term->tid);

    // A term can't be the child of itself, nor of its children.
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
    $exclude[] = $term->tid;

    $tree = taxonomy_get_tree($vocabulary->vid);
    $options = array('<' . t('root') . '>');
    if (empty($parent)) {
      $parent = array(0);
    }
    foreach ($tree as $item) {
      if (!in_array($item->tid, $exclude)) {
        $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
      }
    }
    $form['relations']['parent'] = array(
      '#type' => 'select',
      '#title' => t('Parent terms'),
      '#options' => $options,
      '#default_value' => $parent,
      '#multiple' => TRUE,
    );

  }

```

I try to look into the latest core, this part of code is still there with same logics. Unfortunately, I need `taxonomy_override_selector` be `TRUE`.

Apart from setting `taxonomy_override_selector` to `FALSE` or adding new form validation handler to set `$form_state['values']['parent']`.

Do anyone know if there is solution for that?

# Answer
There's a couple of ways you could go about the problem:

1. **Patch Core:** If there's no outstanding issue for the problem, alter core, create a patch & bug report, and submit your patch. You can manage your patch in your deployment process until the patch is accepted upstream.
2. **Custom Module:** Looking at the comment above the code you posted, it was authored with the intention that someone might need to alter the form ("Contrib modules can then intercept before hook\_form\_alter to provide scalable alternatives."). You can use a `HOOK_form_taxonomy_form_term_alter` invocation to alter the submission handler or the form array to mitigate the warning introduced.
> 0 votes

---
Tags: 7, forms, taxonomy-terms
---


# Question
Title: How to disable a permission for a moderator role which is granted to an authenticated user?
There are two roles I have created 1. Authenticated user 2. Moderator,

Authenticated user can post the content as I expected.

But for Moderator role, I don't want to give permission to add content on site.

Because of moderator is an authenticated user, he is getting all permissions of authenticated user.

And the checkbox of permission is selected and disabled, how can I uncheck it ?

Or there is any other way to prevent moderator for upload content ?

# Answer
Your key challenge is to get around what seems to be a contradiction, which is that a user with role "moderator" is, by design of Drupal, also an authenticated user.

By using the Rules module, it is possible to implement something that looks like restricting access to URLs that start with `node/add`, and this for one or more selected role(s). So you could use this as a kind of workaround, as further detailed below.

To "*add content to a site*" (as in your question), a user needs to enter such URLs (starting with `node/add`) to actually start doing so (or click some link that matches with such URLs). By "redirecting" those URLs for users with a specific role you can implement what you're asking for.

Here is a rule (in Rules export format) which should be pretty close to implement such access restrictions like you're asking for:

```
{ "rules_limit_access_to_node_add_urls_" : {
    "LABEL" : "Limit access to URLs to add nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/node\/add",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "You are not allowed to use such path...",
          "type" : "warning"
        }
      }
    ]
  }
}

```

The above rule performs a redirect for users who have a role with role id = "4". Just adapt that role id to fit your moderator role (if needed) and import (using the Rules UI) the above rule and you should be good to go.
> 1 votes

# Answer
Follow this Answer Question,

There, I have mentioned two Modules and in another answer one more module. This modules expands the functionality of the Drupal core function. And provides the control at admin level.
> 0 votes

---
Tags: users
---


# Question
Title: How to create a relationship between user and some content type?
I am new to Drupal and I need to create a relationship between user and content type.

There is a content type called 'Property'. The user who creates a property page must specify either:

* I am an owner, OR
* I am a tenant.

And I need to show this relationship on the property detail page.

How can I achieve this?

**Note**: I want to keep record of this, it mean the property detail page would always shows the previous tenant and owner information. And later that I want to show the reviews of user under owner and tenant tabs.

# Answer
> but I want to keep record of this, it mean the property detail page would always shows the previous tenant and owner information. And later that I want to show the reviews of user under owner and tenant tabs.

* The initial question sounds simple but the added comment turns it into a fairly complicated site build which I believe is outside the scope of StackExchange questions. I'm just going to give the OP a brief overview of what I would do. Mods, feel free to edit or whatever you need to do.

---

So along with normal fields like images, locations etc., you need a place to store all of the information relating to each owner or tenant in each property.. The screenshot below gives a basic example of this.

Field Collection will let you store this information. You should have one field collection for owners and another for tenants. All reviews etc. of each person will have to be inside a field collection. Or reference a field collection using the module below.

Entity Reference will let you reference the people and vice versa. You'll use this a massive amount on a site like this for almost everything.

Entity Forms \+ Rules should allow tenants / owners to create property and also add themselves to a property by creating field collections from form data. You don't want to give them the ability to change other people's data so forms are essential.

Entity Reference Prepopulate will be essential for pre-filling form data and then disabling or hiding fields. This way, people can't view the workings of your site and more importantly, add and edit whatever they like. (for a regular end-user anyway).

Etc. Etc. Etc.

Anyways, that should be enough for you to look at for a couple of months. Good luck!
> 1 votes

# Answer
This really seems like a perfect usecase for the Flag module. Just create 2 (non global) flags to be used for flagging content of type "Property" (only) with labels something like this:

* (flag 1): I am an owner
* (flag 2): I am a tenant

When configuring these flag(s), you can also attach fields to each of them. You can use those fields to have a use enter a start date and possibly also an end date (since you seem to also "*want to keep record (track?) of this*". However to be able to attach fields (actually for users to enter date for those fields), make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

> By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
>
> Navigate to `Administration > Structure > Flags` page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

To "*show this relationship on the property detail page*" (as in your question also), just create an appropriate views (using the Views module) about users who flagged a node, format it as a block, and display the block on a property page.

But wait, there is more: the Flag module has great integrations with the Rules module. So pretty sure you'll find additional cases where you'll want to take advantage of these integrations also.
> 1 votes

# Answer
I'm not sure what is the ultimate goal but you could just create a new List field for the content type named "Author is" and set it's options to: Owner, Tenant.

Author/creator could then select suitable option and when Property page is viewed it shows the author's "status".
> 0 votes

---
Tags: users, entities
---


# Question
Title: Ignoring unpublished/published as criteria for "Has new content"
I have rudimentary Recycle Bin system based on Flags and unpublishing / republishing content. However, when republished, "Has new content" displays *Updated*.

I still want *New* and *Updated* for when there are new comments so I'm not sure of the best way to go about it.

Thanks.

# Answer
> 2 votes
You need custom code to achieve this. There's 2 things to know here:

## Updated Status Logic

The logic for driving the *New* & *Updated* labels is based on the `history` table (which stores the last time a user viewed a node) & the `node.changed` column:

```
$changed = $this->get_value($values, 'changed');

$last_comment = module_exists('comment') && !empty($this->options['comments']) ? $this->get_value($values, 'last_comment') : 0;

if (!$last_read && $changed > NODE_NEW_LIMIT) {
  $mark = MARK_NEW;
}
elseif ($changed > $last_read && $changed > NODE_NEW_LIMIT) {
  $mark = MARK_UPDATED;
}
elseif ($last_comment > $last_read && $last_comment > NODE_NEW_LIMIT) {
  $mark = MARK_UPDATED;
}
return $this->render_link(theme('mark', array('type' => $mark)), $values);

```

Essentially, it's comparing when a user *last viewed* a node vs. when a node was *last changed*.

What ***isn't known***, is *what was changed* (e.g. the publish status) so to implement some sort of exclusionary logic you're going to have to track the history of publishing/unpublishing to check if the last update was just a change in publish status (`node.status`).

## Updated Status Display

Assuming you have that logic in place, it's possible to override the output a views field. Here you can extend the `views_handler_field_history_user_timestamp` class with your own custom class implementing a `render()` method that adds the logic to check whether the last change *was only a publish status change*. In the final step, you can use `hook_views_data_alter` to override the handler for the *Has new content* field.

---
Tags: 7, views
---


title: Difference between text filter types?

text:
# Question
Title: Difference between text filter types?
When creating text filter, there are several "type" options (see here). What is the difference between these two?

```
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE: Irreversible transformation filters.
FilterInterface::TYPE_TRANSFORM_REVERSIBLE: Reversible transformation filters.

```

Are there some examples when to use them? For example, when I add a class to a HTML element without any class or specific attribute, is that reversible or irreversible?

# Answer
> 5 votes
Per the Filter API docs:

> * Every filter plugin must specify a filter type in its annotation. Filter types were added specifically to support in-place editing. There are four filter types:
>     1. `FilterInterface::TYPE_MARKUP_LANGUAGE` — Non-HTML markup language filters that generate HTML. The filter converts something that's not HTML to HTML in a way that is not compatible with WYSIWYG editing.
>     2. `FilterInterface::TYPE_HTML_RESTRICTOR` — HTML tag and attribute restricting filters to prevent XSS attacks. The filter restricts the HTML allowed, for example, to protect against XSS.
>     3. `FilterInterface::TYPE_TRANSFORM_REVERSIBLE` — Reversible transformation filters. The filter performs a transform for which a WYSIWYG plugin exists to perform the same transformation (and its reverse) client-side. For example, `<img data-caption="Druplicon">` may be (reversibly!) transformed to `<figure><img><figcaption>Druplicon</figcaption></figure>`.
>     4. `FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE` — Irreversible transformation filters. The filter performs a transform for which a WYSIWYG plugin does not exist to perform the transformation client-side (especially, the reverse of it); instead, the WYSIWYG editor displays the unfiltered text. For example, Token Filter.

The type examples given are pretty descriptive of when to use them.

If you **CAN** take the filtered output and put it back into its original form via a WYSIWYG plugin (e.g. structured markup like XML -\> JSON -\> XML), use `FilterInterface::TYPE_TRANSFORM_REVERSIBLE` because the filter output can be reversed.

If you **CANNOT** take the filtered output and put it back into its original form via a WYSIWYG plugin(e.g. a token filter that prints the node title), use `FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE` because the filter output cannot be reversed.

---
Tags: 8, input-formats
---


title: Drupal commerce and big cart

text:
# Question
Title: Drupal commerce and big cart
I'm using drupal commerce for ecomerce project. Shopping cart views with 100-200 line\_items renders extremely slow - 5-10sec. How to fix it?

# Answer
This is too vague to really answer well. A View may be slow for any number of reasons, but at a minimum, this View is loading 200 entities and potentially 400 if you're joining to products (or any other entity). You're going to need some pretty aggressive query caching, both at the database level and likely at the Views level, to perform at that scale of carts without having to change the way Drupal Commerce loads / manages cart orders.
> 1 votes

---
Tags: views, commerce, performance
---


title: Bootstrap edit the file page.vars.php

text:
# Question
Title: Bootstrap edit the file page.vars.php
I wish to customize the file page.vars.php (col-sm-9 by col-md-9) I want to replace :

```
  elseif (!empty($variables['page']['sidebar_first']) || !empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class'] = ' class="col-sm-9"';
  }

```

by :

```
  elseif (!empty($variables['page']['sidebar_first']) || !empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class'] = ' class="col-md-9"';
  }

```

The hostname of my theme is "bootstrap\_subtheme\_front\_office".

Here are the contents of the original file page.vars.php :

```
<?php
/**
 * @file
 * Stub file for "page" theme hook [pre]process functions.
 */

/**
 * Pre-processes variables for the "page" theme hook.
 *
 * See template for list of available variables.
 *
 * @see page.tpl.php
 *
 * @ingroup theme_preprocess
 */
function bootstrap_preprocess_page(&$variables) {
  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class'] = ' class="col-sm-6"';
  }
  elseif (!empty($variables['page']['sidebar_first']) || !empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class'] = ' class="col-sm-9"';
  }
  else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

  if (bootstrap_setting('fluid_container') == 1) {
    $variables['container_class'] = 'container-fluid';
  }
  else {
    $variables['container_class'] = 'container';
  }

  // Primary nav.
  $variables['primary_nav'] = FALSE;
  if ($variables['main_menu']) {
    // Build links.
    $variables['primary_nav'] = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
    // Provide default theme wrapper function.
    $variables['primary_nav']['#theme_wrappers'] = array('menu_tree__primary');
  }

  // Secondary nav.
  $variables['secondary_nav'] = FALSE;
  if ($variables['secondary_menu']) {
    // Build links.
    $variables['secondary_nav'] = menu_tree(variable_get('menu_secondary_links_source', 'user-menu'));
    // Provide default theme wrapper function.
    $variables['secondary_nav']['#theme_wrappers'] = array('menu_tree__secondary');
  }

  $variables['navbar_classes_array'] = array('navbar');

  if (bootstrap_setting('navbar_position') !== '') {
    $variables['navbar_classes_array'][] = 'navbar-' . bootstrap_setting('navbar_position');
  }
  elseif (bootstrap_setting('fluid_container') == 1) {
    $variables['navbar_classes_array'][] = 'container-fluid';
  }
  else {
    $variables['navbar_classes_array'][] = 'container';
  }
  if (bootstrap_setting('navbar_inverse')) {
    $variables['navbar_classes_array'][] = 'navbar-inverse';
  }
  else {
    $variables['navbar_classes_array'][] = 'navbar-default';
  }
}

/**
 * Processes variables for the "page" theme hook.
 *
 * See template for list of available variables.
 *
 * @see page.tpl.php
 *
 * @ingroup theme_process
 */
function bootstrap_process_page(&$variables) {
  $variables['navbar_classes'] = implode(' ', $variables['navbar_classes_array']);
}

```

And content of page.vars.php file I copied the template of my sub-theme folder :

```
<?php
/**
 * @file
 * Stub file for "page" theme hook [pre]process functions.
 */

/**
 * Pre-processes variables for the "page" theme hook.
 *
 * See template for list of available variables.
 *
 * @see page.tpl.php
 *
 * @ingroup theme_preprocess
 */
function bootstrap_subtheme_front_office_preprocess_page(&$variables) {
  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class'] = ' class="col-sm-6"';
  }
  elseif (!empty($variables['page']['sidebar_first']) || !empty($variables['page']['sidebar_second'])) {
    $variables['content_column_class'] = ' class="col-md-9"';
  }
  else {
    $variables['content_column_class'] = ' class="col-sm-12"';
  }

  if (bootstrap_setting('fluid_container') == 1) {
    $variables['container_class'] = 'container-fluid';
  }
  else {
    $variables['container_class'] = 'container';
  }

  // Primary nav.
  $variables['primary_nav'] = FALSE;
  if ($variables['main_menu']) {
    // Build links.
    $variables['primary_nav'] = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
    // Provide default theme wrapper function.
    $variables['primary_nav']['#theme_wrappers'] = array('menu_tree__primary');
  }

  // Secondary nav.
  $variables['secondary_nav'] = FALSE;
  if ($variables['secondary_menu']) {
    // Build links.
    $variables['secondary_nav'] = menu_tree(variable_get('menu_secondary_links_source', 'user-menu'));
    // Provide default theme wrapper function.
    $variables['secondary_nav']['#theme_wrappers'] = array('menu_tree__secondary');
  }

  $variables['navbar_classes_array'] = array('navbar');

  if (bootstrap_setting('navbar_position') !== '') {
    $variables['navbar_classes_array'][] = 'navbar-' . bootstrap_setting('navbar_position');
  }
  elseif (bootstrap_setting('fluid_container') == 1) {
    $variables['navbar_classes_array'][] = 'container-fluid';
  }
  else {
    $variables['navbar_classes_array'][] = 'container';
  }
  if (bootstrap_setting('navbar_inverse')) {
    $variables['navbar_classes_array'][] = 'navbar-inverse';
  }
  else {
    $variables['navbar_classes_array'][] = 'navbar-default';
  }
}

/**
 * Processes variables for the "page" theme hook.
 *
 * See template for list of available variables.
 *
 * @see page.tpl.php
 *
 * @ingroup theme_process
 */
function bootstrap_process_page(&$variables) {
  $variables['navbar_classes'] = implode(' ', $variables['navbar_classes_array']);
}

```

When I clean the cache, I get a blank page. How to fix this ?

# Answer
> 2 votes
You forgot to change:

```
/**
 * Processes variables for the "page" theme hook.
 *
 * See template for list of available variables.
 *
 * @see page.tpl.php
 *
 * @ingroup theme_process
 */
function bootstrap_process_page(&$variables) {
  $variables['navbar_classes'] = implode(' ', $variables['navbar_classes_array']);
}

```

To

```
/**
 * Processes variables for the "page" theme hook.
 *
 * See template for list of available variables.
 *
 * @see page.tpl.php
 *
 * @ingroup theme_process
 */
function bootstrap_subtheme_front_office_process_page(&$variables) {
  $variables['navbar_classes'] = implode(' ', $variables['navbar_classes_array']);
}

```

The reason is you cannot redeclare existing function (**bootstrap\_process\_page**).

The error should be like this:

> Fatal error cannot redeclare function ..., previously declared in ...

You have to replace every instance of `bootstrap_` to the name of your subtheme.

And as a developer always enable error reporting in your local development machine. That will help you identify the error.

---
Tags: 7, theming
---


# Question
Title: How to remove front tag from landing page and logged in home page?
I have a D7 website on the production environment. On the landing page and logged in page i see the page head title "Front | XXXXXXXXXX". Basically xxxxxx is portal name. I would like to remove the Front keyword from the title and show only XXXXXXXXX.

I tried with several options like \- handling in the template.php with in goodnex\_preprocess\_page() \- handing via module with hook\_init().

Please suggest how to fix it.

# Answer
> 1 votes
There is th module Page Title that fixed this. Also if you're using Metatag, its functionality has moved into the module. They should let you use a custom title that will remove your site name.

---
Tags: 7, theming
---


# Question
Title: Custom MigrateMap to sync by field or property, e.g. SKU
### Existing situation: MigrateSQLMap

Normally with migrate API, a migration will use `MigrateSQLMap` to identify imported rows with existing entities.

This means: A database table named like `migrate_map_*` will be created for each migration. The `*` part of the table name is based on the migration machine name. This table associates primary key of the source data (e.g. a primary key column of a csv file) to entity ids.

Whenever a row is to be imported, Migrate API will look into the respective `migrate_map_*` table, and check if a row with this id was already imported, and if the imported entity still exists. If it does, it will update this existing entity, and update the value `last_imported` in the migrate map table. If it does not, it will create a new entity, and create a new entry in the `migrate_map_*` table.

### What I want instead: Map to existing entities.

Now what if instead of creating new entities, I would like to update existing entities which were previously created with another mechanism, unknown to Migrate API? E.g. these might have been created manually, or with a home-grown migration script.

In my case, these entities are commerce products, which were created with a custom script which is to be replaced with Migrate API.

The idea is:

1. Compute an SKU from the imported csv row.
2. Find out if a product with this SKU already exists.
    * If yes, update.
    * If no, create a new product.
3. If possible, save the import timestamp somewhere.

### Solutions I can think of so far

I can imagine two possible solutions.

1. A custom migrate map `class SkuMigrateMap extends MigrateMap`.
Seeing how many abstract methods `MigrateMap` has, this could be quite a lot of work.
2. Use `MigrateSQLMap`, but prefill the table based on existing products.

### Question

Is there an existing or recommended solution for this somewhere?

# Answer
> 1 votes
The map class doesn't (and shouldn't) know anything about either your source or your destination - its job is simply tracking the relationships between their keys.

I've done this in the migration's prepareRow(), doing an explicit lookup for a matching destination object, and if found saving that destination ID to the map and returning FALSE to prevent further processing. Look at how migrate\_d2d maps user accounts based on email:

```
// On initial import, if this email address already exists, just map to the
// existing uid and don't allow it to be deleted. When updating, we can
// take the existing uid from the map instead of querying for it. Make sure
// when updating an imported user that we don't apply this logic.
if (empty($row->migrate_map_destid1)) {
  $new_uid = db_select('users', 'u')
             ->fields('u', array('uid'))
             ->condition('mail', $row->mail)
             ->execute()
             ->fetchField();
  // If we haven't mapped the admin account based on email address, map it
  // directly to the destination admin account.
  if (!$new_uid && $row->uid == 1) {
    $new_uid = 1;
  }
}
elseif ($row->migrate_map_needs_update == MigrateMap::STATUS_IGNORED &&
        $row->migrate_map_rollback_action == MigrateMap::ROLLBACK_PRESERVE) {
  $new_uid = $row->migrate_map_destid1;
}

if (!empty($new_uid)) {
  $hash = isset($row->migrate_map_hash) ? $row->migrate_map_hash : NULL;
  $this->map->saveIDMapping($row, array($new_uid), MigrateMap::STATUS_IGNORED,
    MigrateMap::ROLLBACK_PRESERVE, $hash);
  $this->rollbackAction = MigrateMap::ROLLBACK_PRESERVE;
  return FALSE;
}

```

# Answer
> 0 votes
I found that in my case I had to do it a little differently than Mike Ryan suggests. This is not a right vs wrong, it simply depends on the intended behavior.

The problem was that with Mike Ryan's solution the existing legacy products would have been left as they are and not updated.

The solution below is actually easier. It does not require to create a migrate mapping from this user code. Instead all you do is set `$row->migrate_map_destid1 = $existing_product_id`.

Note that all the lines dealing with revision messages are not really necessary, but I find them useful.

Also note that this solution is not setting `$this->rollbackAction = MigrateMap::ROLLBACK_PRESERVE`. This would prevent the updated legacy products from being rolled back. More on this further below, step II.

## Step I: Modifications to the migration class.

```
class MyMigration extends MigrationBase {

  /**
   * @var int[]
   *   Format: $[$sku] = $product_id
   */
  private $productIdsBySku;

  /**
   * @param array $arguments
   */
  function __construct(array $arguments) {
    [..]
    $this->productIdsBySku = db_select('commerce_product', 'cp')
      ->fields('cp', array('sku', 'product_id'))
      ->execute()
      ->fetchAllKeyed();
    [..]

    // The following only makes sense if you continue reading further below, step II.
    $this->destination = new MyMigrateDestination();
  }

  function prepareRow($row) {

    if (!parent::prepareRow($row)) {
      return FALSE;
    }

    $sku = $this->rowBuildSku($row);

    if (isset($this->productIdsBySku[$sku])) {
      // Product with same sku exists.
      $existing_product_id = $this->productIdsBySku[$sku];
      if (empty($row->migrate_map_destid1)) {
        // Product exists, but is NOT in the migrate map.
        $row->migrate_map_destid1 = $existing_product_id;
        $row->revision_log_message = 'Migrate: Update legacy product.';

      }
      // Possibly comparing string vs integer, so using == and not ===.
      elseif ($row->migrate_map_destid1 == $existing_product_id) {
        // Product exists, and is in the migrate map, with correct id.
        $row->revision_log_message = 'Migrate: Update already-imported product.';
      }
      else {
        // Crazy case: Product is mapped, but to wrong id.
        // This means that something went wrong in the past.
        // @todo Log this problem?
        return FALSE;
      }
    }
    else {
      // Product with this SKU does not exist yet.
      if (empty($row->migrate_map_destid1)) {
        // This is really a new product.
        $row->revision_log_message = 'Migrate: Create new product.';
      }
      else {
        // The migrate map suggests this is an update. But the product to be
        // updated does not exist. Weird.
        // Let migrate module decide what to do.
        $row->revision_log_message = 'Migrate: Create product, which was already mapped.';
      }
    }

    return TRUE;
  }

  function prepare(\stdClass $product, \stdClass $row) {
    [..]
    if (isset($row->revision_log_message)) {
      $product->log = $row->revision_log_message;
    }
    [..]
  }

```

Now, this solution still has a problem.

On rollback, the updated legacy products will be *deleted* instead of reverting to the old pre-migrate revision.

## Step II: Custom migrate destination class.

Solution: A custom migrate destination class with an overridden bulkRollback method. (Actually in the code above I cheated, and it already contains the code to add this destination in the migration class.)

This overridden bulkRollback() decides for each product (entity) to be rolled back whether it should be deleted or an old revision restored.

It uses a heuristic to find an old revision, but this only works in my own special case. You likely need to do something else! More about this further below, step III.

```
class MyMigrateDestination extends \MigrateDestinationEntityAPI {
  [..]

  /**
   * @param int[]|string[] $ids
   *
   * @return bool
   */
  public function bulkRollback(array $ids) {
    migrate_instrument_start(__METHOD__);
    $this->prepareRollback($ids);

    $q = db_select('commerce_product_revision', 'cpr');
    $q->condition('cpr.product_id', $ids);

    // @todo You need to be creative and find a different criterion here.
    $q->condition('cpr.type', 'product');

    $q->fields('cpr', array('product_id', 'revision_id'));
    $q->orderBy('cpr.revision_timestamp');
    // This gets the youngest revision.
    $rvids_by_id = $q->execute()->fetchAllKeyed();

    migrate_instrument_start('revert revisions');
    foreach ($rvids_by_id as $product_id => $revision_id) {
      $entity = entity_revision_load('commerce_product', $revision_id);
      if (FALSE === $entity) {
        unset($rvids_by_id[$product_id]);
        continue;
      }
      $entity->revision = TRUE;
      $entity->log = "Revert via migrate rollback.";
      entity_save('commerce_product', $entity);
    }
    migrate_instrument_stop('revert revisions');

    $ids_to_delete = array_diff($ids, array_keys($rvids_by_id));

    migrate_instrument_start('entity_delete_multiple');
    $deletion_success = FALSE !== entity_delete_multiple($this->entityType, $ids_to_delete);
    migrate_instrument_stop('entity_delete_multiple');

    $this->completeRollback($ids);
    migrate_instrument_stop(__METHOD__);

    return $deletion_success;
  }

}

```

## Part III: Criterion for finding the old pre-migrate revision.

Now there is one piece of homework left for the esteemed reader.

The query above relies on a specificity of my personal use case. In my personal own use case, the migration would change the bundle of legacy entities. This makes it easy to distinguish between revisions before and after the migration was introduced.

```
    $q->condition('cpr.type', 'product');

```

However, even with this specificity, this only works because I "hacked" the commerce\_product\_revision table by adding a "bundle" column, using a module I cooked up for this purpose. I suspect that this is a rather exotic scenario.

Now you need to figure out another way to distinguish product revisions from before and after the migration, and work it into the query.

---
Tags: 7, migrations
---


# Question
Title: How to link user taxonomy-term to a list with all users with that term applied?
So in my testcase you see, that there are some taxonomy terms applied to this user. However when one does click on a taxonomy term there appeares an empty view. Why are not all users with that taxonomy term listed?

# Answer
> 2 votes
First of all, I assume that the views module is installed and both the views and views\_ui modules are enabled.

In the views admin page (/admin/structure/views), there is a view **Taxonomy term**. If you click edit to see the view settings, you will see that the view is only configured to show Content (i.e. nodes of a content type).

Off hand, I am not sure how to configure the Taxonomy term view to also show Users. Anyway, I would not take this approach.

My suggestion is to:

Step 1) In the manage display screen for the User fields (/admin/config/people/accounts/display), set the display of your term field to Hidden.

Step 2) Add a new view page display that lists users associated with a term. You need to use a Contextual filter on the term id (TID).

Step 3) Add a new view block display to lists terms associated with a User. You need to use a Contextual filter on the user id (UID), so that only the terms related to the user are displayed. For the term field, Rewrite the output so that it is formatted as a link to the aforementioned view page (Step 2) and passing the TID as an argument.

Step 4) Display the view block on the user page such that it appears in a region below the user fields.

This is somewhat involved, but should work.

You may also want to take a look at the module https://www.drupal.org/project/taxonomy\_display. This module may open up some other options.

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


# Question
Title: How to display custom news from other news providers?
I want to show news from news providers of my choice to users on my drupal site. Imagine a horizontal news ticker block on the front page with individual news from different news providers. I am using drupal 7.50.

Some more details: I just want to know the way to grab/fetch/retrieve news from websites like cnn, al-jazeerah, etc of my choice to my drupal site and show them in a slider. For example yahoo has a nice news slider. I have views ticker and views slideshow modules, but it is not necessary I use them if other modules fulfill the purpose.

# Answer
> 1 votes
You could import RSS feeds from cnn etc as nodes or aggregate the feed using the feeds module

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


# Question
Title: How can I download files from public folder?
I want to provide download link to the users to download the files which are present in the public folder. How can I achieve that, I tried below but not worked.

```
if ($handle = opendir(variable_get('file_public_path', conf_path(). '/files/') .'/xmluploads/Sainath')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $file = basename($_GET[$entry]);//$file consists caste certificate.pdf
            $file = variable_get('file_public_path', conf_path(). '/files/') .'/xmluploads/Sainath'.$file;
            if(!$file){ // file does not exist
                die('file not found');
            } else {
                header("Cache-Control: public");
                header("Content-Description: File Transfer");
                header("Content-Disposition: attachment; filename=$file");
                header("Content-Type: application/zip");
                header("Content-Transfer-Encoding: binary");

                // read the file from disk
                readfile($file);
            }
        }
    }
    closedir($handle);
}

```

This error I am getting:

```
Notice: Undefined index: caste certi.pdf in file_upload_download() (line 194 of C:\xampp\htdocs\academy\sites\all\modules\custom\file_upload\file_upload.module).
Warning: readfile(sites/default/files/xmluploads/Sainath): failed to open stream: Permission denied in file_upload_download() (line 206 of C:\xampp\htdocs\academy\sites\all\modules\custom\file_upload\file_upload.module).

```

Please help regarding this, Thanks in advance..

# Answer
> 1 votes
I think just giving a link to the file itself will download the file. In case of an image or PDF file, won't opening the file in new tab from where they can download suffice for you?

Regards, Supriya Rajgopal

---
Tags: 7, files
---


# Question
Title: Accessing content variables through the page variable
I have a template that extends the **page.html.twig** base template. I wish to render a field variable from the node as a heading in other parts of the page template.

I've tried `{{dump(page.content)}}` but the variable does not seem to be there, it is already rendered into HTML.

What's the syntax - if it exists - for accessing a node variable from the `page.content` variable?

For example, at the node level, I can access `{{ content.field_heading }}`.

At the page level, what can I use? (`{{ page.content.??? }}`)

# Answer
Per the docs on the core **page.html.twig**:

```
 \* Page content (in order of occurrence in the default page.html.twig):
 \* - messages: Status and error messages. Should be displayed prominently.
 \* - node: Fully loaded node, if there is an automatically-loaded node
 \*   associated with the page and the node ID is the second argument in the
 \*   page's path (e.g. node/12345 and node/12345/revisions, but not
 \*   comment/reply/12345).

```

The `node` variable is available in **page.html.twig**. If you need to access one its fields you can use `{{ node.field_myfield.value }}` to print it out.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: How to get notified by eMail after someone edited his own webform submission?
I have a webform, and I'd like to be notified whenever **someone edited his own submits**. I'm using the Webform module.

I found the Webform Rules module but I didn't get how to use it, any way to set this up?

# Answer
Using Webform Rules (and Rules of course), it's a peace of cake to send an eMail using Rules Event "`After a webform submission is updated`". To actually do so, refer to the answer from CodeNext. However, the real challenge in this question here, is to address this part of the question: "***someone edited his own submits***". Read on for more details on how to implement that part of it.

Assumptions:

1. It should also work for "***someone edited 'her' own submits***".
2. The question is NOT about anonymous users (for that you might need things like IP address, session API, etc ... be my guest to also get that to work ...).

With these assumptions in mind, you'll need to have something in your webform available to store, as part of the submitted webform, the uid of the user who actually submitted the webform. I've not found (yet) any such data that is available as a token to Rules (you'll need it in Rules to get this challenge to work). So therefor I'd use an approach like adding an extra (hidden?) webform field that is automatically set (eg using Rules) when the webform is first submitted, let's say using a field with machine name `field_webform_submitter_uid`.

After all the above is in place and agreed about, you're in good shape to address the challenge "***someone edited 'his/her' own submits***": all you'd have to do is to further enhance the rule detailed in the prior answer, by adding an appropriate Rules Condition, to check if the uid of the currently logged in user matches `field_webform_submitter_uid`.

**But**, there is 1 more challenge to implement that extra Rules Condition: how should the Rules token look like for the value of `field_webform_submitter_uid`? To find the answer to this, refer to the README.txt of Webform Rules: based on what's documented there, the token to be used in that extra Rules Condition should be \[data:field\_webform\_submitter\_uid-value\].

Voilà ...

**Note** (about the token for the uid of the user who submitted the webform): each submission has data like "submitted by" and "submitted on", however from all `uid`-variations I've experimented with, none of them contain the value that always matches the "submitted by" (not to be confused by tokens like `node:author:uid`, those are for sure not what matches the "submitted by"). To convince yourself, try a scenario where the user who submitted the webform is different from the one who edits that submission ...
> 2 votes

# Answer
**Note: Please Do not follow this Answer, as I misunderstood the requirement previously. You can follow this to get the general idea of how to create Rules**

You have right module sets, You need Rules and Webform Rules, as webform rules module depends on rules module.

Now, if you go to Admin/Config/Workflow/rules.

**1.** **Create a new Rule and select event**, as shown in following image I have created a new rule named `Webform Edit Notification`. Then select a Event, as you can see in image, I have selected a option under Webform `After a webform submission is updated`

**2.** **Select the Action**, from options I did choose `Send a mail` as shown in following image. If you save a move to next step it will open a new page for sending a email setup.

**3.** **TO**: Now first field is **TO** whom you want to send. As you click the button `switch to the direct input mode` and click on the data selector the options as shown in image will open.
Now form the image I am selecting `node:...(The webform node)`. After selection it will show options which are under that under that. So I am selecting `node:author:...(Author)`. Then again same in next step I am selecting `Email`.

Hence, It will end up as **`node:author:email`** which translate, `**Email address of Author of that particular node**` So this will make a TO:

>

Then you can add,

**Subject:**

**Add message:**

**From:**

So, this way it will send a mail to the mail to the author of that webform.

> *I have not used this as I am not using in my site, But this is the logic. You can try it to validate it before finalizing for Live site.*
> 1 votes

---
Tags: 7, webforms, emails, notifications
---