# Question
Title: Access denied for all users, sessions table empty, access log shows NULL uid
My Drupal 7 site has been up and running for a couple years without issue. I went to log in as admin today to check for security updates and had the following experience:

1. When I first browse to the page (as anonymous), the site works fine.
2. Enter login information to log in as admin, immediately greeted with "Access denied".
3. Browse other pages in the same browser session, the entire site says "Access denied".
4. Visit the website in a new browser session, a private browser session, a private browser session on a different computer, or a private browser session on a different computer at a remote site with a different IP address, all using 4 different browsers - all say "Access denied".

The first thing the internet said was to edit settings.php and modify the $cookie\_domain setting, which I had left at default (unconfigured). I tried setting this to my domain but it made no difference.

After extensive troubleshooting, I have identified the following additional behavior:

* When I log in and get Access Denied, it only affects a particular subdomain even though it's the same site (example.com vs www.example.com).
* When the site is in a working state, the accesslog table shows anonymous browsing with uid of 0. After I attempt to log in, the accesslog shows activity with a uid of NULL. This makes some sense if there's no session in the sessions table to match the cookie in my browser.
* The watchdog table shows no errors, only "user Session opened for %name." and "access denied user/1".
* Anonymous access to the site returns to normal after a CRON job runs. Since I installed Drush I can now run CRON manually which speeds up troubleshooting.
* If I attempt to log in using correct credentials, it breaks the site again and access is denied (as described) until the next CRON job.
* If I attempt to log in using incorrect credentials, I get "unrecognized username or password" and the site continues to work fine for anonymous browsing.

So I started digging around:

* I found the Anonymous user's "status" in the users table was set to 0 (blocked). I set this to 1. No change.
* I found that the row for the Anonymous user was completely missing from the users\_roles table. I added this row with values 0,1 for uid and rid respectively. No change. (This row is also missing from a new install so it may not be necessary - I'm not an expert here.)
* I verified that the role, role\_permission, and node\_access tables were properly populated. No change.
* I attempted to browse to /admin/content/node-settings/rebuild but get access denied on that, too.
* I checked the accesslog table and recent entries from today show numerous logins with a uid of NULL.
* I truncated the sessions table and when I attempt to browse or log in to the site no new rows are added to the table (similar to this question).
* I installed drush and cleared the cache and ran the cron logout as suggested by the answer in the StackOverflow question. This reduced the problem from everyone getting access denied to only me getting access denied, resolved by clearing the site's session cookie. So it's an improvement in that attempting to log in doesn't break the site for everyone now. Still no rows in the sessions table.
* I hashed a new password and set it directly in the database. No change in behavior.
* I have attempted to reset my password using the password reset links. I receive the password reset e-mail. When I open the link, I get a new accesslog entry with uid of 0 and when I click "login" I get an accesslog entry with uid of 1 (my admin user), and then when I attempt to reset my password or go anywhere else on the site, I get accesslog entries with uid of NULL. Sessions table is still empty. This works the same if I use the command `drush uli` to generate a login.
* I found this question/answer and checked my themes. Unable to access the admin pages, I checked in the database and found my current theme was set to 0 (disabled). I set this to 1 (enabled) as well as its prerequisites. No change.
* I found this question/answer and attempted a repair on my sessions table. I had to set it o use MyASM instead of InnoDB to run the repair. Repair succeeds with no change to behavior.
* I found this question/answer and disabled all modules using the provided drush command. No change in behavior. Other suggestions in that answer either do not apply to my situation (hosted platform) or likewise do not work.
* I attempted to install a new instance of Drupal 7 on the same server. The new instance has the exact same problem. This leads me to believe it's something systemic on the server. Based on the above StackOverflow answer I suspect my hosting provider may have forced an update from PHP 5.3 to 5.4 without notifying me. I have now tried several PHP versions available from my hosting provider (5.4, 5.5, 5.6, and 7.0) in addition to all of the steps outlined above.

I have streamlined my troubleshooting process to the following steps:

1. Make a change
2. Clear browser cookies
3. Use Drush to clear cache and run CRON
4. Refresh website and clear cookies again if a session cookies shows up
5. Test login -\> Access Denied
6. Check Watchdog and Sessions tables in PHPMyAdmin

So far nothing seems to be making any difference at all. The majority of suggestions I've found on the internet all point to clearing cookies or setting the $cookie\_domain variable which make no difference.

Can anyone help me regain admin access to my site and get this working?

---

More notes

* I have created a duplicate of my site at an alternate URL for invasive testing.
* I have attempted a new install of Drupal 7.59 using my hosting provider's CPanel. Same behavior.
* I have attempted a new instance of Drupal 7.59 downloading directly from Drupal.com and running install.php. Same behavior.

This HAS to be something on the server itself.

At this point I'm looking at building a copy of my site on a VM at home to try and fix while I look for another hosting provider.

I'd like to migrate to Drupal 8, but that's a huge project - finding replacements for themes and modules that aren't supported in Drupal 8 and migrating data and content. I'm not looking forward to that with admin access broken.

---

Modules list from Drush:

```
 Package                      Name                                                         Type    Status         Version
 Administration               Module Missing Message Fixer (module_missing_message_fixer)  Module  Enabled        7.x-1.7
 Administration               Rename Admin Paths (rename_admin_paths)                      Module  Enabled        7.x-2.3
 Advanced CSS/JS Aggregation  AdvAgg Async Font Loader (advagg_font)                       Module  Enabled        7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg Bundler (advagg_bundler)                              Module  Enabled        7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg CDN CSS (advagg_css_cdn)                              Module  Not installed  7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg CDN Javascript (advagg_js_cdn)                        Module  Not installed  7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg Compress CSS (advagg_css_compress)                    Module  Enabled        7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg Compress Javascript (advagg_js_compress)              Module  Enabled        7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg CSS/JS Validator (advagg_validator)                   Module  Not installed  7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg External Compression (advagg_ext_compress)            Module  Disabled       7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg Modifier (advagg_mod)                                 Module  Enabled        7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg Relocate (advagg_relocate)                            Module  Not installed  7.x-2.30
 Advanced CSS/JS Aggregation  AdvAgg Subresource Integrity (advagg_sri)                    Module  Not installed  7.x-2.30
 Advanced CSS/JS Aggregation  Advanced CSS/JS Aggregation (advagg)                         Module  Enabled        7.x-2.30
 CCK                          CCK (cck)                                                    Module  Enabled        7.x-3.0-alpha3
 CCK                          Content Migrate (content_migrate)                            Module  Not installed  7.x-3.0-alpha3
 Chaos tool suite             Bulk Export (bulk_export)                                    Module  Not installed  7.x-1.12
 Chaos tool suite             Chaos tools (ctools)                                         Module  Enabled        7.x-1.12
 Chaos tool suite             Chaos Tools (CTools) AJAX Example (ctools_ajax_sample)       Module  Not installed  7.x-1.12
 Chaos tool suite             Chaos Tools (CTools) Plugin Example (ctools_plugin_example)  Module  Not installed  7.x-1.12
 Chaos tool suite             Custom content panes (ctools_custom_content)                 Module  Not installed  7.x-1.12
 Chaos tool suite             Custom rulesets (ctools_access_ruleset)                      Module  Not installed  7.x-1.12
 Chaos tool suite             Page manager (page_manager)                                  Module  Not installed  7.x-1.12
 Chaos tool suite             Stylizer (stylizer)                                          Module  Not installed  7.x-1.12
 Chaos tool suite             Term Depth access (term_depth)                               Module  Not installed  7.x-1.12
 Chaos tool suite             Views content panes (views_content)                          Module  Not installed  7.x-1.12
 Core                         Aggregator (aggregator)                                      Module  Not installed  7.59
 Core                         Block (block)                                                Module  Enabled        7.59
 Core                         Blog (blog)                                                  Module  Not installed  7.59
 Core                         Book (book)                                                  Module  Not installed  7.59
 Core                         Color (color)                                                Module  Enabled        7.59
 Core                         Comment (comment)                                            Module  Not installed  7.59
 Core                         Contact (contact)                                            Module  Disabled       7.59
 Core                         Content translation (translation)                            Module  Disabled       7.59
 Core                         Contextual links (contextual)                                Module  Disabled       7.59
 Core                         Dashboard (dashboard)                                        Module  Disabled       7.59
 Core                         Database logging (dblog)                                     Module  Enabled        7.59
 Core                         Field (field)                                                Module  Enabled        7.59
 Core                         Field SQL storage (field_sql_storage)                        Module  Enabled        7.59
 Core                         Field UI (field_ui)                                          Module  Enabled        7.59
 Core                         File (file)                                                  Module  Enabled        7.59
 Core                         Filter (filter)                                              Module  Enabled        7.59
 Core                         Forum (forum)                                                Module  Not installed  7.59
 Core                         Help (help)                                                  Module  Disabled       7.59
 Core                         Image (image)                                                Module  Enabled        7.59
 Core                         List (list)                                                  Module  Enabled        7.59
 Core                         Locale (locale)                                              Module  Enabled        7.59
 Core                         Menu (menu)                                                  Module  Enabled        7.59
 Core                         Node (node)                                                  Module  Enabled        7.59
 Core                         Number (number)                                              Module  Enabled        7.59
 Core                         OpenID (openid)                                              Module  Not installed  7.59
 Core                         Options (options)                                            Module  Enabled        7.59
 Core                         Overlay (overlay)                                            Module  Disabled       7.59
 Core                         Path (path)                                                  Module  Enabled        7.59
 Core                         PHP filter (php)                                             Module  Disabled       7.59
 Core                         Poll (poll)                                                  Module  Disabled       7.59
 Core                         RDF (rdf)                                                    Module  Enabled        7.59
 Core                         Search (search)                                              Module  Enabled        7.59
 Core                         Shortcut (shortcut)                                          Module  Disabled       7.59
 Core                         Statistics (statistics)                                      Module  Enabled        7.59
 Core                         Syslog (syslog)                                              Module  Not installed  7.59
 Core                         System (system)                                              Module  Enabled        7.59
 Core                         Taxonomy (taxonomy)                                          Module  Enabled        7.59
 Core                         Testing (simpletest)                                         Module  Not installed  7.59
 Core                         Text (text)                                                  Module  Enabled        7.59
 Core                         Toolbar (toolbar)                                            Module  Enabled        7.59
 Core                         Tracker (tracker)                                            Module  Not installed  7.59
 Core                         Trigger (trigger)                                            Module  Not installed  7.59
 Core                         Update manager (update)                                      Module  Enabled        7.59
 Core                         User (user)                                                  Module  Enabled        7.59
 Development                  Metatag: Devel (metatag_devel)                               Module  Not installed  7.x-1.22
 Feeds                        Feeds (feeds)                                                Module  Not installed  7.x-2.0-alpha8
 Feeds                        Feeds Admin UI (feeds_ui)                                    Module  Not installed  7.x-2.0-alpha8
 Feeds                        Feeds Import (feeds_import)                                  Module  Not installed  7.x-2.0-alpha8
 Feeds                        Feeds News (feeds_news)                                      Module  Not installed  7.x-2.0-alpha8
 ImageAPI                     ImageAPI (imageapi)                                          Module  Disabled       7.x-1.x-dev
 ImageAPI                     ImageAPI GD2 (imageapi_gd)                                   Module  Disabled       7.x-1.x-dev
 ImageAPI                     ImageAPI ImageMagick (imageapi_imagemagick)                  Module  Not installed  7.x-1.x-dev
 Menu                         TB Mega Menu (tb_megamenu)                                   Module  Enabled        7.x-1.0-rc2
 Multilingual -               Panels translation (i18n_panels)                             Module  Not installed  7.x-3.9
 Internationalization
 Other                        Chosen (chosen)                                              Module  Disabled       7.x-1.0-beta6
 Other                        Facebook comments (facebook_comments)                        Module  Enabled        7.x-1.0
 Other                        Fast 404 (fast_404)                                          Module  Enabled        7.x-1.5
 Other                        Font Awesome (fontawesome)                                   Module  Disabled       7.x-1.0-beta6
 Other                        Job Scheduler (job_scheduler)                                Module  Not installed  7.x-2.0-alpha3
 Other                        Job Scheduler Trigger (job_scheduler_trigger)                Module  Not installed  7.x-2.0-alpha3
 Other                        Libraries (libraries)                                        Module  Enabled        7.x-2.3
 Other                        Pathauto (pathauto)                                          Module  Enabled        7.x-1.3
 Other                        Quicktabs (quicktabs)                                        Module  Enabled        7.x-3.8
 Other                        Quicktabs Styles (quicktabs_tabstyles)                       Module  Enabled        7.x-3.8
 Other                        Site map (site_map)                                          Module  Not installed  7.x-1.3
 Other                        Special menu items (special_menu_items)                      Module  Enabled        7.x-1.0-beta6
 Other                        Token (token)                                                Module  Enabled        7.x-1.7
 Panels                       Mini panels (panels_mini)                                    Module  Enabled        7.x-3.9
 Panels                       Panel nodes (panels_node)                                    Module  Enabled        7.x-3.9
 Panels                       Panels (panels)                                              Module  Enabled        7.x-3.9
 Panels                       Panels In-Place Editor (panels_ipe)                          Module  Enabled        7.x-3.9
 Performance and scalability  APC - Alternative PHP Cache (apc)                            Module  Disabled       7.x-1.0-beta6
 Performance and scalability  HTTP Parallel Request Library (httprl)                       Module  Enabled        7.x-1.14
 Radioactivity                Radioactivity (radioactivity)                                Module  Enabled        7.x-2.10
 Radioactivity                Radioactivity defaults (radioactivitydefaults)               Module  Not installed  7.x-2.10
 Responsive                   Respond.js (respondjs)                                       Module  Enabled        7.x-1.5
 Search                       Custom Search (custom_search)                                Module  Enabled        7.x-1.20
 Search                       Custom Search Blocks (custom_search_blocks)                  Module  Not installed  7.x-1.20
 Search                       Custom Search Internationalization (custom_search_i18n)      Module  Not installed  7.x-1.20
 Search                       Custom Search Taxonomy (custom_search_taxonomy)              Module  Not installed  7.x-1.20
 SEO                          Metatag (metatag)                                            Module  Enabled        7.x-1.22
 SEO                          Metatag Importer (metatag_importer)                          Module  Not installed  7.x-1.22
 SEO                          Metatag: App Links (metatag_app_links)                       Module  Not installed  7.x-1.22
 SEO                          Metatag: Context (metatag_context)                           Module  Not installed  7.x-1.22
 SEO                          Metatag: Dublin Core (metatag_dc)                            Module  Not installed  7.x-1.22
 SEO                          Metatag: Dublin Core Advanced (metatag_dc_advanced)          Module  Not installed  7.x-1.22
 SEO                          Metatag: Facebook (metatag_facebook)                         Module  Enabled        7.x-1.22
 SEO                          Metatag: favicons (metatag_favicons)                         Module  Not installed  7.x-1.22
 SEO                          Metatag: Google Custom Search Engine (CSE)                   Module  Not installed  7.x-1.22
                              (metatag_google_cse)
 SEO                          Metatag: Google+ (metatag_google_plus)                       Module  Not installed  7.x-1.22
 SEO                          Metatag: hreflang (metatag_hreflang)                         Module  Not installed  7.x-1.22
 SEO                          Metatag: Mobile & UI Adjustments (metatag_mobile)            Module  Enabled        7.x-1.22
 SEO                          Metatag: OpenGraph (metatag_opengraph)                       Module  Enabled        7.x-1.22
 SEO                          Metatag: OpenGraph Products (metatag_opengraph_products)     Module  Not installed  7.x-1.22
 SEO                          Metatag: Panels (metatag_panels)                             Module  Not installed  7.x-1.22
 SEO                          Metatag: Twitter Cards (metatag_twitter_cards)               Module  Enabled        7.x-1.22
 SEO                          Metatag: Verification (metatag_verification)                 Module  Enabled        7.x-1.22
 SEO                          Metatag: Views (metatag_views)                               Module  Enabled        7.x-1.22
 Sharing                      ShareThis (sharethis)                                        Module  Enabled        7.x-2.13
 User interface               CKEditor (ckeditor)                                          Module  Enabled        7.x-1.18
 User interface               Gallery Formatter (galleryformatter)                         Module  Enabled        7.x-1.4
 User interface               jQuery plugins (jquery_plugin)                               Module  Enabled        7.x-1.0
 User interface               jQuery Update (jquery_update)                                Module  Enabled        7.x-2.7
 User interface               Superfish (superfish)                                        Module  Enabled        7.x-1.9
 User interface               Wysiwyg (wysiwyg)                                            Module  Enabled        7.x-2.4
 Views                        Views (views)                                                Module  Enabled        7.x-3.18
 Views                        Views Content Cache (views_content_cache)                    Module  Enabled        7.x-3.0-alpha3
 Views                        Views Slideshow (views_slideshow)                            Module  Enabled        7.x-3.9
 Views                        Views Slideshow Simple Pager (views_slideshow_simple_pager)  Module  Not installed  7.x-3.9
 Views                        Views Slideshow: Cycle (views_slideshow_cycle)               Module  Enabled        7.x-3.9
 Views                        Views UI (views_ui)                                          Module  Enabled        7.x-3.18
 XML sitemap                  XML sitemap (xmlsitemap)                                     Module  Enabled        7.x-2.3
 XML sitemap                  XML sitemap custom (xmlsitemap_custom)                       Module  Enabled        7.x-2.3
 XML sitemap                  XML sitemap engines (xmlsitemap_engines)                     Module  Enabled        7.x-2.3
 XML sitemap                  XML sitemap internationalization (xmlsitemap_i18n)           Module  Not installed  7.x-2.3
 XML sitemap                  XML sitemap menu (xmlsitemap_menu)                           Module  Enabled        7.x-2.3
 XML sitemap                  XML sitemap node (xmlsitemap_node)                           Module  Enabled        7.x-2.3
 XML sitemap                  XML sitemap taxonomy (xmlsitemap_taxonomy)                   Module  Enabled        7.x-2.3
 XML sitemap                  XML sitemap user (xmlsitemap_user)                           Module  Disabled       7.x-2.3
 Core                         Bartik (bartik)                                              Theme   Disabled       7.59
 Core                         Garland (garland)                                            Theme   Disabled       7.59
 Core                         Seven (seven)                                                Theme   Enabled        7.59
 Core                         Stark (stark)                                                Theme   Disabled       7.59
 Other                        nucleus (nucleus)                                            Theme   Enabled        7.x-1.5
 Other                        nucleus_starter (nucleus_starter)                            Theme   Enabled        7.x-1.5
 Other                        Tb Sirate (tb_sirate)                                        Theme   Enabled        7.x-1.1

```

# Answer
> 0 votes
This was finally resolved by my web host. Good grief it was frustrating!

I still do not know for sure what the solution was. They had a widespread (but publicly unidentified) database issue that was causing a number of problems which may have been the solution. Unfortunately they did not notify me when that issue was resolved so I did not test until after working with them to resolve a different problem related to a php.ini conflict.

Sorry that this answer can't be more helpful, but if you have the same problems then at least you can be confident it's something with your host. If you self-host, I recommend rebuilding a server from the ground up at least as a test.

---
Tags: users, sessions
---


# Question
Title: Views page redirect to current page with parameter
in drupal 7, I use `drupal_goto` function for the redirection. I'm trying a few methods in d8, but couldn't make it work.

If I visited a certain page for example `/views-page-example`, I would like to redirect users to the same page, but with parameters. Once visited, the users should be redirected to `/views-page-example?name=value`. I'm using `template_preprocess_page` to trigger the redirection.

This is the current code I have so far:-

```
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

function THEME_preprocess_page(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();

  if ($current_path == '/views-page-example') {
    $path = "/views-page-example?name=value";
    $route_name = url::fromRoute($path);
    $response = new RedirectResponse($route_name->toString());
    $response->send();
  }
}

```

# Answer
> 3 votes
Don't send a response in custom code. Use an event subscriber to set the response, so that it can be returned by Drupal:

*mymodule.services.yml:*

```
services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

```

*src/EventSubscriber/MymoduleSubscriber.php:*

```
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(RequestEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkForRedirection'];
    return $events;
  }

}

```

Source: https://www.drupal.org/node/2013014

---

Example to check the current path and that the query parameter is not present yet:

```
public function checkForRedirection(RequestEvent $event) {
  $request = $event->getRequest();
  if ($request->getPathInfo() == '/example' && !$request->query->has('name')) {
    ...

```

---
Tags: 8
---


# Question
Title: EntityQuery not returning content based on language
I'm trying to get a list of all of a specific content type, but my entityQuery is only returning the original language of the site (English). Here's my code:

```
  public function fetchDocumentReferenceOptions() {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'document')
  ->condition('langcode', $language)
  ->sort('title', 'ASC');

$nids = $query->execute();

$nodes = node_load_multiple($nids);

$options = [];

foreach($nodes as $node)
{
  // check if the document (content type) has an uploaded file
  if ($node->field_document->entity) {
      $options[$node->id()] = $node->getTitle();
  }
}

return $options;

```

}

This is how I call the function:

```
'#options' => $DocumentReferenceCore->fetchDocumentReferenceOptions(),

```

What I am expecting, based on condition for langcode would be that, if, for example, I am editing a Chinese language node (translated from the original English node), I should see Chinese nodes, and the content being returned, but instead I am still seeing the original English content.

What am I doing wrong here?

# Answer
> 9 votes
Content entities have an active language concept. When loaded, they by default return values for the default translation.

With your query, you know it has that translation, so you can use this code.

```
$node = $node->getTranslation($language);

```

If you're not sure it exists, you can use this code.

```
$custom_tag = \Drupal::service('entity.repository')->getTranslationFromContext($node, $desired_langcode);

```

That will return the node matching the language, if it exists, or the best alternative. You can also leave out the language code; in that case it will use the current content language.

---
Tags: 8, entities, forms, i18n-l10n
---


# Question
Title: How to see unpublishes content types In a view?
I have a view which displays a list of unpublished content type "Nascholingen".

I use D8 + varbase + content access module

In super admin all goes good. I added a new rol called "lid". Logged in with this member the view does not display any result.

I did \- remove permissions on the view \- added all needed permissions on /permissions to edit this \- Access control for "Nascholingen" are set correctly. \- set priority of Content Access to 10 \- Rebuild with drush cr

But whatever I do no results are displayed. grrr

Any suggestions? Is there a good way for debugging this?

# Answer
$query = \Drupal::entityQuery('node'); $query-\>condition('status', 0); // 0 CERO IS UNPUBLISHED $query-\>condition('type', 'CONTENT TYPE NAME'); $entity\_crop = $query-\>execute();
> -1 votes

# Answer
This can be solved with the following module:

https://www.drupal.org/project/view\_unpublished

After installation there are some new permissions in the permissions list which should be configurated and then unpublished items will be visible for the roles you configured.
> 0 votes

---
Tags: 8, users
---


# Question
Title: Update image tags using entity metadata wrapper
I'm trying to bulk update image tags using `entity_metadata_wrapper`.

I'm unable to see the image field when I use `$emw->getPropertyInfo()`.

The bundle is called `hub_page`.

The code I'm using is:

```
$wrapper = entity_metadata_wrapper('node', $node_id, array('bundle' => 'hub_page'));
var_dump($wrapper->getPropertyInfo());

```

Is this the correct way?

# Answer
> 2 votes
You must pass in a node object as the second value, instead of a node ID.

```
$node = node_load($node_id);
$wrapper = entity_metadata_wrapper('node', $node, ['bundle' => 'hub_page']);

```

That might be your problem. Check out the docs: Entity metadata wrappers.

---
Tags: 7, entities
---


# Question
Title: Wich template to override for user account form
I am building a theme for my Drupal 8 site and I want to create a custom profile page with user information like this: http://bootsnipp.com/snippets/featured/profile-card but I can't find the correct template to override where I can have access to all the information needed like username, name, picture and for example his address. Also I can't find where is the user-edit form to change the HTML so I can display it as I want.

I am new to Drupal 8 theming and that's why my question may look kind of no sense. Thank you

EDIT (add more information)

So, I want to make my user's profile edit page to a two column layout where I can have the user base information like name and picture on left and on the right having the form to change the rest of the information like user and password. What is the best way to achieve that?

# Answer
> 0 votes
use the native interface to add fields and change display

```
/admin/config/people/accounts/fields

/admin/config/people/accounts/display/full

```

if the html structure need to be changed , the template

> user.html.twig

can be override in the theme child templates folder.

As an exmaple for custom added individual fields, with fundation classes :

```
<article{{ attributes }}>
  {% if content %}
    <div class="grid-x grid-margin-x">
      <div class="cell small-12 medium-6 large-3">
        {{ content.field_user_photo }}
      </div>
      <div class="cell small-12 medium-6 large-9">
        {{ content.field_user_name }}
        {{ content.field_user_status }}
        {{ content.field_user_email }}
        {{ content.field_user_phone }}
      </div>
    </div>
  {% endif %}
</article>

```

# Answer
> -1 votes
Enable Twig in services.yml. No you can see the active template in the html-code

---
Tags: theming, 8, users
---


# Question
Title: Can forms be added to a page of quick tabs?
I want to create a page of quick tabs with some node editing pages, webforms and some admin pages as well regular static pages which just display information without any editing.

Is that possible?

# Answer
Should be possible via custom code. You can read up on how to build quicktabs programmatically here:

https://www.drupal.org/node/2119625

For the node editing pages you will want to use the example for `Custom contents (HTML or renderable Array)` on that page, where you get the form using the core function `drupal_get_form('node_BUNDLE_form')` and add it as the "renderable array".

For the webforms you could try to work with the `Callback` tab type, or again by loading the webform and building the render array.

For the static content i'd recommend to use nodes as this is always better than hardcoding things, so use the `Node` tabs type.
> 1 votes

---
Tags: 7
---


# Question
Title: How can I iterate through all the key and value of configuration object
I have an admin setting form (Configuration form) called 'example.settings'. I can load the configuration using below code.

> $config = \Drupal::config('example.settings');

Is there a way to iterate through and get all the configuration values in this config object

# Answer
> 3 votes
You could try the following to get the raw values back:

```
$config->getRawData()

```

E.g. the following

```
$config = \Drupal::config('system.maintenance');
$config->getRawData()

```

Returns and array of something like: 'message' =\> string(93) "@site is currently under maintenance. We should be back shortly. Thank you for y…" 'langcode' =\> "en" →'\_core' =\> array(1)

---
Tags: 8, configuration
---


# Question
Title: How to make sure simpleSamlAuth module is working as intended?
I'm working on a Drupal site which is utilizing the simpleSAMLphp\_auth module. We want users to be able to log in using their Gmail accounts, so long as they have an **pre-existing** Drupal account to match. If it turns out they do not, I don't want them being authenticated.

As of now, when I attempt to use the federated login through Gmail, it seems to authenticate me because it doesn't complain at all about access being denied. It simply takes me back to the homepage of our Drupal website.

How can I check if I am actually being authenticated, even though the email I am testing with the federated login **does not** have a pre-existing Drupal account associated with it?

Also, I am using the *email* as the simpleSAML attribute for the users unique identifier and for their email as well.

# Answer
> 0 votes
There are hooks and config in the module UI that should aid in this. Here is an example from a Drupal 8 project I did that does just this:

```
/**
 * Implements hook_simplesamlphp_auth_allow_login().
 */
function MYMODULE_simplesamlphp_auth_allow_login(array $attributes) : bool {
  // Debugging purposes
  \Drupal::logger('mymodule')->log('info', 'Attributes contained: @attributes', ['@attributes' => $attributes]);

  if (empty($attributes['EMAIL_ATTRIBUTE_IDENTIFIER'])) {
    \Drupal::logger('mymodule')->log('info', 'Attribute was not present.', ['@attributes' => $attributes]);
    return FALSE;
  }

  // Run a query to see if the user exists by email address in Drupal
  $exists = // query users by email address

  return $exists;
}

```

Perhaps a simpler approach in your case would be hook\_form\_alter, adding a new submit handler and doing the email check there before anything else happens, but the hook above is the final say-so in if a user can authenticate and login or not.

---
Tags: users
---


# Question
Title: Adding a flag to Menu Content Link to display as a non-link
I have been struggling/failing for the last day to try find a way that I can add a flag/marker to the Drupal menu links that I can examine within the menu TWIG template to modify the link such that it becomes plain text instead of a menu link.

I am not using any menu modules, standard Drupal Menu with CSS to provide the drop down functionality and styling.

What I need is to be able to output a menu item as shown in the screen shot, specifically the 'Sell your property' & 'Essential Services' items which are unlinked headers.

Initially I attempted to use the contributed module `menu item extras` (https://www.drupal.org/project/menu\_item\_extras) which works fine from a menu management plugin point of view but then they change the markup way too much and it actually breaks the drop down functionality, so I cannot use it.

I then tried a second module which seemed simpler, i.e. `Menu link content fields` (https://www.drupal.org/project/menu\_link\_content\_fields).

This module has some strange behaviour in that it makes the menu links fieldable. I can add a new field but after adding a field, it does not appear under the `Manage Fields` tab, and in the twig template the new field is un-available in the menu item object (Examined through xDebug)

Also, trying to remove this invisible field at a later stage seems difficult.

**Question**: How can I easily add some sort of marker to a menu item link to allow me to modify the template output for said link. Or is the re a module that will allow then insertion of HTML markup/plain text instead of a link (*Megamenu doesnt seem to allow this*)

Also, I cannot seem to find the hook which deals specifically with a sites menu, i.e. the hook that is executed for each menu link. Does one even exist?

I'd like to avoid a hack whereby I put in a unique string into the text of the link and then examine this in the menu twig templates to see if that string exists to know if I need to modify it.

# Answer
> 1 votes
The module Special menu items allows you this, even some control over the HTML output.

This is now in Drupal core (although Docs need some updating):

> This features is in core for \>=8.2.0. Create menu without link by entering route: `<nolink>`.

That is, you enter into Link:

`route:<nolink>`

and select:

`Show as expanded`

if you need it for drop-downs.

---
Tags: 8, theming, navigation
---


title: Convert pot file to array

text:
# Question
Title: Convert pot file to array
So, what I need to do is to convert the contents of a `.pot` file to an array.

I know there is `_locale_import_read_po()`, but when I tried using it with the following code, I got an error.

```
$translations = _locale_import_read_po('db-store', 'translations.pot');

```

The `translations.pot` file is located in the same directory containing the file with the code I wrote.

The error I get with `dpm($translations)` is the following one.

> Error message
>
> The translation import failed, because the file could not be read.

This is the code from the `_locale_import_read_po()` function, that outputs that error.

```
// The file will get closed by PHP on returning from this function.
$fd = fopen($file->uri, 'rb');
if (!$fd) {
  _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  return FALSE;
}

```

As far as I know the `'rb'` file open mode is to open non-text files.

Why do I get that error message?

# Answer
> 1 votes
The second parameter of `_locale_import_read_po()` is a Drupal file object, which in Drupal 7 is simply a `stdClass` object.

The quicker way to use that function and pass a file object as it expects is using code similar to the following one.

```
 $po_files = file_scan_directory('./', '^translation\.po$', array('recurse' => FALSE));
 if (count($po_files)) {
   require_once DRUPAL_ROOT . '/includes/locale.inc';
   $po_file = reset($po_files);
   _locale_import_read_po('db-store', $po_file);
 }

```

Notice that the second argument of `file_scan_directory()` is a `preg_match()` regular expression, not a filename.

Using that code, you don't need to save the file using the file API, which is essentially useless, since there is already a file in the file system.
`file_save()` stores the file in the database; for a file that is used for a single operation like that, it's not necessary.

I used `st()` as example for writing the code I shown in this answer.

You could also make the code I show more generic to accept a regular expression and a directory name, and use it to load more files.

```
function mymodule_import_translations($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern, array('recurse' => FALSE));
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';
    foreach ($po_files as $po_file) {
      _locale_import_read_po('db-store', $po_file);
    }
  }
}

```

# Answer
> 0 votes
The `$file` parameter needs to be a *Drupal file object* corresponding to the PO file to import.

You can create one using the file\_save function:

```
$file = file_save((object)array(
    'filename' => $file_name,
    'uri' => $destination_uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($destination_uri),
  ));

```

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


# Question
Title: Drupal behaviors not attached after Ajax load
I'm facing a weird problem on my clean Drupal Installation I attached a js library to page with this

```
function fs_gal_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'fs_gal/fs_gal';
}

```

This js file I have:

```
(function ($, Drupal, drupalSettings) {
  'use strict';
   Drupal.behaviors.GalJs = {
    attach: function (context, settings) {
        alert("Gal");
    }
  };
}) (jQuery, Drupal, drupalSettings);

```

In my custom theme I created a Ajax call:

```
$('.button a').on('click', function (e) {
    e.preventDefault()
    $.ajax({
        type: "POST",
        url: "path-to-controller",
        cache: false,
        success: function(htmlText) {
            $('.text-container').html(htmlText);
        }
    });
});

```

After clicking the button, the text is correctly replaced in the `.test-container` but the library is not re-attached to the newly changed DOM. Do someone know a technique to re-attach all behaviors to the content injected after an Ajax call ?

Many thanks for your help

# Answer
> 9 votes
Behaviours are fired after a *Drupal* AJAX call - a call to jQuery.ajax isn’t the same thing.

Fortunately it’s easy to attach them yourself, just add this in the success callback when you’ve finished manipulating the DOM:

```
Drupal.attachBehaviors();

```

---
Tags: ajax
---


# Question
Title: Trusted_host_patterns not working with domain
I'm working with a drupal 8 site and trying to get trusted\_host\_patterns working properly with the domain that I'm using, and no matter what combination of regex I try I can only get it to work with the catch-all '^.\*$'. So far, I've used (plus a couple more):

```
'^production\.sitename\.com$',
'^www\.production\.sitename\.com$',
'^.+.production.sitename.com.$',   // which I know is the same but more general than above

```

which as far as I know from looking at examples, should work. Is there anything I'm missing?

# Answer
> 0 votes
Figured this one out after some trial and error. I don't know if it is necessary due to some server settings I have, but I fixed this by adding the private IP of my server to the trusted host names setting. I'm uncertain as to why this is necessary since all the other examples I've seen don't need any reference to the private IP, but in my case it seems to be needed.

---
Tags: configuration
---


title: Concatenate url() in Twig

text:
# Question
Title: Concatenate url() in Twig
I tried to do something that I thought was fairly simple, but it's giving an error:

> Notice: Array to string conversion in \__TwigTemplate\_dd3a187031be000574aa6b2149e8b2daacd4f1d086638752b5928811c46b8adf-\>doDisplay() (line 132 of vendor/twig/twig/lib/Twig/Environment.php(462) : eval()'d code).

What caused it:

```
{% set support_url = url('<front>') ~ 'support' %}

```

So I tried something:

```
{{ url('<front>') }}<br />
{% set support_url = url('<front>') %}
{{ support_url }}<br />
{% set support_url = url('<front>') ~ 'support' %}
{{ support_url }}<br />

```

The result of the above is:

> http://www.example.com/
>
> http://www.example.com/
>
> Arraysupport

What is going on?

# Answer
The url function returns a render array, so you can't concatenate it with a string. You must first convert it to a string.

try render\_var():

```
{% set support_url = render_var(url('<front>')) ~ 'support' %}

<h1>{{ support_url }}</h1>

```

This will convert the render array created by the url function to a string.
> 3 votes

# Answer
I do not know if my contribution is useful, but I had a problem with a **multilanguage** site and I solved it in this way.

The drawback was, that the language is not shown /ES, / EN, /pt-br, etc. It always showed the url of the base language, that is, EN.

```
{% set support_url = path('<front>') ~ '/node/102' %}

{% set base_url = render_var(url('<front>')) ~ support_url %}

<a href="{{ base_url }}">
    <h2 class="block-title">{{ 'Change'|t}}    </h2>
</a>

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Views block template print individual field from content
I created a view of paragraphs and I passed the parent ID as the contextual filter using a relationship to the content that use the field that reference the paragraph.

I can see the data been display and now I want to theme the output that I want to display on a block. I created a custom template file for the view block:

> block--views-block--MY-VIEW-NAME-block-1.html.twig

and it is working. I can see the content of the view by adding:

```
{% block content %}
{{ content }}
{% endblock %}

```

But I would like to access the fields value individually. I have try the followings without luck:

```
content.field_name
content.field_name[0]
content.field_name[0].value

```

What am I missing?

# Answer
I finally found the answer to this issue. Here it is in case some one is having the same issue.

The solution is insanely simple use the views fields template.

In my case I created a new template:

```
views-view-fields--VIEW-NAME.html.twig

```

And now you can access your fields values like this:

```
{{ fields.field_NAME.content }}

```

More details here

Enjoy.
> 2 votes

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


# Question
Title: Can You Use HOOK_node_builder() to Set Custom Node ID?
Drupal 8.x

How do you set the node id in HOOK\_node\_builder()? Is it even possible?

There is a similar question here: Specifying a custom node id when creating new content, however it is a different approach or need.

**MYMODULE.module**:

```
function MYMODULE_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state) {

    $node->setTitle('Node Title');

}

```

I am able to set the title fine. I am hard pressed to find any docs or posts on this hook.

# Answer
> 2 votes
There is no HOOK\_node\_builder, here are the available hooks in the Entity API.

I think hook\_ENTITY\_TYPE\_presave is the one you are looking for.

```
function MYMODULE_node_presave(\Drupal\node\NodeInterface $node) {
  $node->nid->value = 5;
  $node->enforceIsNew(TRUE);
}

```

Here is the order of hooks and other events that happen during an entity save:

* preSave() is called on the entity object, and field objects.
* hook\_ENTITY\_TYPE\_presave()
* hook\_entity\_presave()
* Entity is saved to storage.
* For updates on content entities, if there is a translation added that was not previously present:
    + hook\_ENTITY\_TYPE\_translation\_insert()
    + hook\_entity\_translation\_insert()
* For updates on content entities, if there was a translation removed:
    + hook\_ENTITY\_TYPE\_translation\_delete()
    + hook\_entity\_translation\_delete()
* postSave() is called on the entity object.
* hook\_ENTITY\_TYPE\_insert() (new) or hook\_ENTITY\_TYPE\_update() (update)
* hook\_entity\_insert() (new) or hook\_entity\_update() (update)

---
Tags: 8, nodes, hooks
---


title: Search result - 500 error

text:
# Question
Title: Search result - 500 error
My Drupal 7 websites started to throw 500 error when I see the search result page.

# How to replicate:

When I enter any keyword and hit search button then I see this URL "http://www.website.com/search/node/keyword" and I see the broken page layout with no result. and I see the error "500 server error" on browser console. Please see the screenshot: https://snag.gy/VsoQqj.jpg

Please see the screenshot of search settings and permissions

**Search Module:** https://snag.gy/LNBciP.jpg

**Search Permission:** https://snag.gy/EGMIfc.jpg

**Search Settings:** https://snag.gy/7yGmQ6.jpg

# Answer
> 0 votes
It is really hard to say without seeing an actual error.

Do you have see this url: "http://www.website.com/search/node/keyword" or was this just to give an example? If you see that url, I supposed that you see this in an ajax call somewhere since you would get a 404 and not a 500 error. If you see this error, check in your settings.php file if you have a base\_url variable set to www.website.com.

Go in /admin/reports/dblog and chec if you get a more detailed error message.

---
Tags: 7, search
---


# Question
Title: How to replace allowed_values for a select field by external definition?
I created a custom content entity, called member, with some fields of which one, called status, is a list appearing in form as a select:

```
$fields['status'] = BaseFieldDefinition::create('list_integer')
  ->setLabel(t('Statut'))
  ->setRequired(TRUE)
  ->setSettings(array(
    'allowed_values' => array(
      0 => 'Ancien',
      1 => 'Actif',
      2 => 'Non renouvelée',
      3 => 'Renouvelée',
      4 => 'En attente',
    ),
  ))
  ->setDefaultValue(4)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'weight' => 7,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'options_select',
    'weight' => 7,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

I'd like to put the definition of the allowed values 'somewhere else' (meaning not directly in the definition of the member entity).
I know I could create another content entity (e.g. possible\_status) that I would reference this way:

```
$fields['status'] = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'possible_status)')

```

But it seems a bit 'rich' to handle a couple of values...
Is there another way to store the values 'outside' the code defining the member entity?
An include file, a text file, a JSON file I could import?
What would be the best practice for that?

\[EDIT\]
I changed for this:

```
$fields['status'] = BaseFieldDefinition::create('list_integer')
  ->setLabel(t('Statut'))
  ->setRequired(TRUE)
  ->setSettings(['allowed_values_function' => 'association_allowed_values_function'])
  ->setDefaultValue(4)

```

with this in my module:

```
function association_allowed_values_function(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {

  if ($definition['entity_type'] == 'member' && $definition'field_name' == 'status') {
    $values = [
      0 => 'Ancien',
      1 => 'Actif',
      2 => 'Non renouvelée',
      3 => 'Renouvelée',
      4 => 'En attente',
    ];
  }
  return $values;
}

```

and it works!

Now, I'd like to move `association_allowed_values_function` to an include file. And I don't know how...

# Answer
Instead of `allowed_values` you can add a callback to set the allowed values:

```
  ->setSettings(['allowed_values_function' => 'callback_allowed_values_function'])

```

The callback:

```
function callback_allowed_values_function(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {
  if (isset($entity) && ($entity->bundle() == 'not_a_programmer')) {
    $values = [
      1 => 'One',
      2 => 'Two',
    ];
  }
  else {
    $values = [
      'Group 1' => [
        0 => 'Zero',
        1 => 'One',
      ],
      'Group 2' => [
        2 => 'Two',
      ],
    ];
  }

  return $values;
}

```

You can get the allowed values from a text file or put the callback in an include file.

For more information see options.api.php

---

A different approach might be to store the allowed values in config, for which there is a bundle specific base field override, see How to easily alter an entity's base field definition per bundle. Then you can manage the allowed values list in a yaml file of an exported config.
> 4 votes

---
Tags: 8, entities
---


# Question
Title: How to send formatted html email using swiftmailer?
How can I send styled html body using custom module to send an email. I am using swiftmailer module. With that I am able to send normal body, but I am not able to use html tags or css. How can I do this?

# Answer
> 3 votes
Swiftmailer only sends mails, it doesn't let you create HTML / plaintext content for emails.

I think that you want to use a module like mimemail to do this.

I came across this article that describes how to style mails send out using mimemail.

Theming HTML Mail sent through Mime Mail

This guide is made for Drupal 7, but the module has been made for Drupal 8 as well, so I think you might just create a `mimemail-message.html.twig`

---
Tags: 8, emails, page-controller
---


title: Convert imported strings into array

text:
# Question
Title: Convert imported strings into array
I have imported a `.pot` file using the `_locale_import_read_po` function, like this:

```
$po_files = file_scan_directory('/', '/.*\.pot$/');
if (count($po_files)) {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  $po_file = reset($po_files);
  $translations = _locale_import_read_po('db-store', $po_file);
}

```

Now, what I want is to convert all the imported strings into a PHP array.

Is there any way to do that, and how?

# Answer
> 0 votes
Passing `'db-store'` as first argument of `_locale_import_read_po()` will cause the content of the translation file to be imported in the database. To import it in memory, it's necessary to use the following code.

(As usual, replace *mymodule* with the machine name of the module that contains this function.)

```
function mymodule_import_translations_in_memory($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern);
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';

    // Allow execution to continue even if the request gets canceled.
    @ignore_user_abort(TRUE);

    // Try to allocate enough time to import all the file.
    drupal_set_time_limit(240);

    foreach ($po_files as $po_file) {
      _locale_import_read_po('mem-store', $po_file);
    }

    @ignore_user_abort(FALSE);
  }

  return _locale_import_one_string('mem-report');
}

```

Passing `'mem-report'` to `_local_import_one_string()` will cause the function to return all the imported strings, while passing `'mem-store'` to `_locale_import_read_po()` will import the translation in a static variable.

The code I shown works, but if another module called `_locale_import_read_po()` passing `'mem-store'` as first argument, `mymodule_import_translations_in_memory()` would return the content of the files imported from the other module and the content of the files `mymodule_import_translations_in_memory()` imported. A more generic code would be the following one.

```
function mymodule_import_translations_in_memory($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern);
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';

    // Allow execution to continue even if the request gets canceled.
    @ignore_user_abort(TRUE);

    // Try to allocate enough time to import all the file.
    drupal_set_time_limit(240);

    $strings =& drupal_static('_locale_import_one_string:strings', array());

    // Store the old string list to restore it at the end.
    $old_strings = $strings;

    // Reset the string array to an empty array.
    $strings = array();

    foreach ($po_files as $po_file) {
      _locale_import_read_po('mem-store', $po_file);
    }

    @ignore_user_abort(FALSE);

    // Store the value to return.
    $string_list = $strings;

    // Restore the value set before this function was called.
    $strings = $old_strings;
  }

  return $string_list;
}

```

The code is directly accessing a static variable set by another function, but since there isn't any function to reset its value, that is the only possibility.

In the case of importing a big translation file, keep in mind that loading it all in memory is probably going to cause memory problems. Before doing it, PHP should be set to use more memory than Drupal would normally use.

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


# Question
Title: Core search is not searching content in the node which is fetched through an entity reference field
Core search in Drupal 7 not searching the content in the node which has been fetched through an entity reference field.

What could be the solution to search for a keyword in all pages of the website?

Would there be any alternative?

# Answer
> 2 votes
The search index is build from a special view mode for nodes, called 'search\_index'.

The easiest way to configure this is

* Install/enable Entity View Modes
* Enable configuration of the 'search\_index' view mode for your content type. I believe it will appear as a tab under /admin/structure/types/manage/page
* Configure the 'search\_index' at /admin/structure/types/manage/page/display/search\_index
* Add/remove fields as needed. For your entity reference, change the display to "rendered entity".

Clear the search index, and rebuild it.

---
Tags: search
---


# Question
Title: How to add a profile cover with a user field image in a view?
I am trying to add a cover image to user profiles in a block view, the image comes from a user profile field.

The problem is that I need the path to that image because my neede code is like this:

```
<div class="profile-background"  style="background-image: url('/sites/all/themes/pingu/img/Circles.jpg');">

```

# Answer
You need to install the Image URL Formatter module

Then in your view, click on your image field and select url as the formatter, so it prints the url rather than the image.

Views doesn't allow to use the style attribute in re-write results.

Therefore, you will need to use a template file. **views-view-fields--\[view-name\]--\[machine-name\].tpl.php**). This file needs to be in */sites/all/themes/THEMENAME/templates* folder.

put this inside it:

```
<div class="profile-background"  style="background-image: url('<?php print $fields["field_image"]->content; ?>');">

<div><?php print $fields["field_other"]->content; ?></div>

...

```

Clear/Flush all caches to see changes.
> 1 votes

---
Tags: 7, views, media
---


title: How do I turn on theme_debug?

text:
# Question
Title: How do I turn on theme_debug?
I want to use theme\_debug to check which elements of a site use which .tpl files.

I have tried turning it on by using the drush command:

```
drush @mysite vset theme_debug 1

```

Though I do get the response `theme_debug was set to 1`, this does not seem to work.

Would anyone know if there is a way to get this working?

(Drush it's self seems to be working ok as I can use `drush @mysite cc all`)

# Answer
> 21 votes
**Drush commands to control theme debugging:**

**Drupal 7**

* To turn it on: `drush variable-set theme_debug 1`
* To turn it off: `drush variable-set theme_debug 0`

**Drupal 8+**

* To turn it on: `drush state-set theme.debug 1`
* To turn it off: `drush state-set theme.debug 0`

Then clear your site cache and refresh the page in the browser.

# Answer
> 10 votes
You process is right but this another option you can check.

In your Drupal 7 installation simply add this line to your settings.php:

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

```

Clear your caches and refresh the page and you should see debug information in your mark-up which contains template suggestions.

Also go for Theme developer module.

# Answer
> -2 votes
> Step 1: Path :\sites\default\setting.php
>
> Step 2: Edit Setting.php: remove `#` from
>
> `#$conf['theme_debug'] = TRUE;`
>
> Step 3: Save setting.php file
>
> Step 4: Inspect your website then you seen that theme information is show.

---
Tags: 7, theming
---


# Question
Title: How to see the error messages when I get the white screen of death?
How can I see the error messages when the site I am working on gets a white screen?

# Answer
> 33 votes
Put this at the bottom of settings.php:

```
error_reporting(-1);  // Have PHP complain about absolutely everything
$conf['error_level'] = 2;  // Show all messages on your screen, 2 = ERROR_REPORTING_DISPLAY_ALL.
ini_set('display_errors', TRUE);  // These lines just give you content on WSOD pages.
ini_set('display_startup_errors', TRUE);

```

# Answer
> 17 votes
The White Screen of Death (Completely Blank Page) resource on drupal.org will step you through the steps to see the error message as well as common problems that cause them.

> ### "Invisible" Errors
>
> If error reporting is turned off, you could be getting a fatal error but not seeing it. On a production site, it is common to have error reporting turned off. If that is the case and PHP has hit an unrecoverable error, neither an error nor content will be displayed, therefore you end up with a completely blank page.
>
> What you can do about this is either turn on PHP error reporting so it displays a message on the page itself, or check your log files (from the server) to look for the error. How to do both of these are explained below.
>
> ### Enable Error Reporting
>
> Although it may be turned off on commercial hosts and production sites (for good reason, so that users do not see the errors), these errors are one of your best tools for troubleshooting. To enable error reporting, temporarily edit your index.php file (normally located in your root directory) directly after the first opening PHP tag (do not edit the actual file info!) to add the following:
>
> ```
> error_reporting(E_ALL);
> ini_set('display_errors', TRUE);
> ini_set('display_startup_errors', TRUE);
>
> ```
>
> You will now be able to see any errors that are occurring directly on the screen. Memory problems may still not be displayed, but it's the first step in a process of elimination.
>
> If you are using a multi-site setup and only want errors to appear for one site, then check the name of the host first as in:
>
> ```
> if ($_SERVER['HTTP_HOST']==='some.domain.name.here') {
>   error_reporting(E_ALL);
>   ini_set('display_errors', TRUE);
>   ini_set('display_startup_errors', TRUE);
> }
>
> ```
>
> If the problem occurs while running update.php open update.php in a text editor and uncomment the following line:
>
> ```
> ini_set('display_errors', FALSE);
>
> ```

# Answer
> 10 votes
Have a look at Apache error log, in Ubuntu it's located in `/var/log/apache2/error.log` so you can do:

```
tail -f /var/log/apache2/error.log

```

# Answer
> 2 votes
I found easy way of tracking down the WSOD errors by running the whole site via `drush`, e.g.:

```
drush rs

```

After that access the site at the given new address (e.g. `127.0.0.1:8080`), then try to reproduce the problem, and you'll see all errors on the terminal screen. No need to reconfiguring your PHP, especially in cases when `display_errors` fails (e.g. MAMP).

---

Other tricky way I've found it by using debuggers, e.g.:

* OS X:

```
sudo dtruss -fn httpd 2>&1 | grep -i error

```
* Linux:

```
sudo strace -f $(pgrep -fn httpd) 2>&1 | grep -i error

```

Note: Change `httpd` into `php` if you're using `drush rs` as above.

Or installing `XDebug` PHP extension and generate a trace file (`xdebug.auto_trace=1`).

# Answer
> 1 votes
If you are using drush, you can see error messages using drush-ws command.

# Answer
> 0 votes
I just changed the variable $update\_free\_access value from FALSE to TRUE and executed the update.php file. It resolved my problem.

# Answer
> 0 votes
You can modify index.php and wrap up the code with a try / catch. Like this:

```
try {
    define('DRUPAL_ROOT', getcwd());
    require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    menu_execute_active_handler();
} catch (Error $t) {
    error_log('Error at Line:' . $t->getLine() . ' File: ' . $t->getFile() . ' Message:' . $t->getMessage() );
    print '<div>Message: ' . $t->getMessage() . '</div>';
    print '<div>File:' . $t->getFile() . '</div>';
    print '<div>Line:' . $t->getLine() . '</div>';
}

```

The Error message will show the file and line of code which caused the error.

---
Tags: wsod
---


title: Automated Rules Discount

text:
# Question
Title: Automated Rules Discount
I have installed 'Ubercart Discount Coupons' module and managed to add a rule to configure the automated discount. But now all the normal code type discounts have stopped working....

Only when I remove the automated discount rule the normal code discounts will works.

I am struck on the production site.

Screenshots:

# Answer
> 0 votes
I guess I figured out the problem.

This Issue was in the 'Coupon module settings'.

Solution: 1. Go to: admin/store/settings/coupon 2. Enable 'Allow multiple coupons to apply to a single order.' check-box. 3. Save.

This solved my problem.

Thanks, Anand

# Answer
> 0 votes
Previous answer of AnAnD worked for me as well.

As of 2018 (Drupal 7.59, Ubercart 3.11) I found the setting under `Administration > Store > Configuration > Coupon module settings`.

---
Tags: 7, ubercart
---


# Question
Title: Custom theme: variable not made available in menu template
I've created a custom theme, let's call it "mytheme" in the examples, with the "classy" theme as base. I use several templates, one is menu--account.html.twig, it's an override I made of the classy menu.html.twig template to display a menu. In that template I need the username and some other info from the currently logged in user.

I've tried different ways of getting it to output the username in the template, i.e. the preprocess functions like so:

```
<?php

function mytheme_preprocess(&$variables, $hook, $info) {
  $variables['current_user_name'] = $variables['user']->getDisplayName();
  var_dump($variables['current_user_name']); //ironically this does dump the variable
}

```

I've tried using the Bamboo Twig module and get the username like so:

```
<!-- Get Current User -->
{% set user = bamboo_load_currentuser() %}
<div>{{ user.name.value }}</div>

```

Both variants don't work for me. If I try to dump the username with

```
{{ dump(current_user_name) }} or {{ dump(user.name.value) }}

```

all I get is NULL in the template output. From searching online I'm sure that one of these variants should work, but they don't.

I've also cleared caches several times during the tests, so that can be ruled out too.

Do you have any other suggestions on how to output the variable in that template?

# Answer
> 3 votes
I think that it might work if you do like this,

```
function mytheme_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['current_user_name'] = $user->getUsername();
}

```

Remember to clear the cache.

After debugging, we found out this this code worked, in the case somebody runs into the same issue.

```
function themename_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['attributes']['uname'] = $user->getUsername();
}

```

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


# Question
Title: Show a sale price and discount percentage in Commerce 2
I want to show the **original/list price** and **sale price** (actual price) in my store as well as the discount percentage: **N% off!**

In Drupal 7, there is the excellent Commerce Price Savings Formatter module-- just install the module, set the prices, and you're done.

What can I do in Drupal 8? I have tried to use the built-in promotion feature in Commerce 2, but as far as I can tell the promotion UI can only be used to create coupons, not discounts that automatically apply to the relevant orders. (based on a reading of the documentation and experimenting with the module).

# Answer
Easiest way for me was to create my own FieldFormatter for the price and make it extend Drupal\commerce\_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter.

Once you did that, flush the cache of your website, go to the manage display of your Product variation type, select "My Custom price calculated formatter" for Price field and in the parameters, check "Apply promotions to the calculated price". And voilà!

Here is an example code for the custom FieldFormatter:

```
<?php

namespace Drupal\my_custom_module\Plugin\Field\FieldFormatter;

use CommerceGuys\Intl\Formatter\CurrencyFormatterInterface;
use Drupal\commerce\Context;
use Drupal\commerce\PurchasableEntityInterface;
use Drupal\commerce_order\AdjustmentTypeManager;
use Drupal\commerce_order\PriceCalculatorInterface;
use Drupal\commerce_price\Plugin\Field\FieldFormatter\PriceDefaultFormatter;
use Drupal\commerce_store\CurrentStoreInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter; // This is the FieldFormatter we want to extend

/**
 * Plugin implementation of the 'my_custom_price_calculated_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "my_custom_price_calculated_formatter",
 *   label = @Translation("My Custom price calculated formatter"),
 *   field_types = {
 *     "commerce_price"
 *   }
 * )
 */
class MyCustomPriceCalculatedFormatter extends PriceCalculatedFormatter implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   * This is the function we want to extend
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    if (!$items->isEmpty()) {
      $context = new Context($this->currentUser, $this->currentStore->getStore(), NULL, [
        'field_name' => $items->getName(),
      ]);
      /** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
      $purchasable_entity = $items->getEntity();
      $adjustment_types = array_filter($this->getSetting('adjustment_types'));
      $result = $this->priceCalculator->calculate($purchasable_entity, 1, $context, $adjustment_types);
      $calculated_price = $result->getCalculatedPrice();
      $number = $calculated_price->getNumber();
      $currency_code = $calculated_price->getCurrencyCode();
      $options = $this->getFormattingOptions();

      // Check if there is any adjustment for the price
      // If so, get the BasePrice (without adjustment) and format it
      if(!empty($result->getAdjustments())) {
        $adjustments = $result->getAdjustments();
        foreach($adjustments as $single_adjustement) {
          // Get the discount percentage off
          // NB: there could be many other discounts applied but this example catches percentage discounts only
          if($single_adjustement->getType() == "promotion" && $single_adjustement->getPercentage() !== NULL) {
            $discount = $this->t('@discount off', ['@discount' => $single_adjustement->getPercentage() * 100 . '%']);
          }
        }
        $base_price = $result->getBasePrice();
        $base_price_number = $base_price->getNumber();
        $base_price_currency_code = $base_price->getCurrencyCode();
        $base_price_formatted = $this->currencyFormatter->format($base_price_number, $base_price_currency_code, $options);
      }

      // This is our calculated price with the promotion
      $price_display = $this->currencyFormatter->format($number, $currency_code, $options);
      if(isset($base_price_formatted)) {
        // Set the base price (old-price), the percentage off and the calculated price within $price_display
        $price_display = '<div class="old-price">' . $base_price_formatted . '</div><div class="percentage-off">' . $discount . '</div><div class="new-price">' . $price_display . '</div>';
      }

      $elements[0] = [
        '#markup' => $price_display,
        '#cache' => [
          'tags' => $purchasable_entity->getCacheTags(),
          'contexts' => Cache::mergeContexts($purchasable_entity->getCacheContexts(), [
            'languages:' . LanguageInterface::TYPE_INTERFACE,
            'country',
          ]),
        ],
      ];
    }

    return $elements;
  }

}

```
> 4 votes

# Answer
I found a way to do this on my site by using Attributes. Each product variation has it's own MSRP attribute. Then on the display I chose Rendered Attribute as the display style, then I used some CSS to remove the border, the red asterisk, and made the variation unclickable. Also used CSS to put a red strike through it, and ultimately achieve exactly what I wanted. This is a method you would use if you have product variations. Just make sure when sorting the order of your variations, to make the MSRP field last. That way it won't show the other options, it only shows the MSRP related to the variation they are choosing. Works like a charm.
> 1 votes

# Answer
Here's a basic way to implement this in Commerce 2 if you don't need everything done automatically.

1. Go to the "product type" admin page for the relevant product type and choose **Manage fields**.
2. Add a **price** field, *list price*. Make sure to check the box for the right currency; I couldn't get the form to save without doing so.
3. Add an **integer** field, set the min value 0 and the max value 100, and then the suffix as **%**.
4. Use Views or a theme template to add some CSS classes to theme it nicely.
> 0 votes

---
Tags: 8, commerce
---


# Question
Title: cache_form has been truncated. Permanent error MYSQL Incorrect key file when a form is accessed
On a site I inherited, I can see cache\_form is empty. It has been truncated some time ago. I have got an error crashing my site when accessing many type of forms: views exposed forms, forms to edit Views and node edit forms. The error is a MYSQL Incorrect key file error and is triggered by clear\_cache\_all(). There is an attempt to DELETE FROM cache\_form, where a given form ID is found. However the table is empty so it does not work. I do not know why Drupal has to delete a cache entry from the table even for a new node. Is there a way to bypass the step where Drupal try to delete the cache entry?

# Answer
This sounds like someone tried to do some optimization to `{cache_form}` through a MySQL interface and did something that makes it incompatible with Drupal, or the table is damaged due to a dull disk (see this happen before).

First make sure you have free disk space, and then do a `CHECK TABLE cache_form;` and see if there are any errors. If you see some, you can try the standard repair techniques, but it is often best to just re-create the table.

# These steps are dangerous and can destroy your site. Make sure you have backups.

To re-create `{cache_form}` I would

Start a MySQL interface , and delete `{cache_form}`, eg `DROP TABLE cache_form;`

Recreate the table from a known good Drupal 7 install. I think this is the default:

```
CREATE TABLE `cache_form` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the form system to store recently built...';

```
> 1 votes

---
Tags: caching
---


# Question
Title: On Imported content I am getting the error Text format field is required
I imported some content to a content type on a csv which imported fine but when I went to edit and same the content I get the error Text format field is required. Is there any known way to fix this? Thanks

# Answer
> 1 votes
You need to add default value for text format when you migrate content. Example body field

```
'body/format':
  plugin: default_value
  default_value: basic_html
'body/value': body

```

After update config migration you need update migration with command

```
drush mim MIGRATATION_ID --update

```

---
Tags: 8, nodes, forms, importing-exporting
---


title: Memcache interfering with Simpletest

text:
# Question
Title: Memcache interfering with Simpletest
Adding some tests to an older Drupal 7 site and a few of the tests check for the presence or lack thereof of custom cache items.

Having this in settings.php seems to interfere with Simpletest using default database cache (this is included to settings.php as a local settings override):

```
  $conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned no non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;

  $conf['memcache_servers'] = array('cache:11211' => 'default');

```

Is there any global flag I can look at at this point to determine whether or not to add these overrides in?

I tried checking the $GLOBALS for a test id and `drupal_valid_test_ua` but in both cases the memcache information was still used.

If I comment out the memcache settings, I can see the cache tables in simpletest are populated as expected. How can I get around this?

edit: looks like testing specific settings.php is not possible in 7.

# Answer
I wound up creating a new site in Lando and a new site folder just for simpletest. I created a site directory for my main site and moved settings.php into that, and installed a minimal Drupal site to the other.

This resolved my issue, since the site/db specifically for SUT does not use memcache.
> 0 votes

---
Tags: 7, caching, testing
---


# Question
Title: Linking an action to the button in the view
I'm looking for some tips how to achieve following functionality in Drupal 8.

I have a simple view where I list filds, nothing special. One of the fields is a custom text which is rendered as a button html element. Now, I want to assign a special action to this button, it is a automatic creation of new node.

Any help will be appresated.

# Answer
You can do this with the help of the Rules module. You'll probably want to create a Component (they don't have Events that trigger them, as opposed to full Rules) and connect them to your Views custom field.

Views Bulk Operations (VBO) is a better option though. It's also well integrated with Rules so you can use that instead of a Custom text Field. With VBO you get checkboxes for each Views row and a button for each action you want to perform on a Views row, so you can select more than one row at the same time.
> 0 votes

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


# Question
Title: How to pass a parameter into a form upon creating?
I have a form, which contains an additional field. And I want to initiate the field via the form constructor.

```
class ServicesForm extends FormBase {

    private $service_type;

    public function __constructor($_service_type){
        $this->service_type = $_service_type;
    }

```

The form is created in a controller.

```
class ServicesController extends ControllerBase {

    public function getServices($service_type){
        $data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm');

        return $data;
    }

```

Could you clarify me, how to pass the parameter $service\_type to the form inside the controller method ?

Maybe, should I do it without FormBuilder and getForm ?

# Answer
Just add it to your form's `buildForm` method signature:

```
public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) {
  // Use $arg
}

```

Then literally pass it to the form builder's `getForm` method:

```
$data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm', $service_type);

```
> 7 votes

# Answer
I have tried the Clive's solution, however, it breaks the interface of `FormInterface`.

In the `\Drupal::formBuilder()->getForm()` method, the code is the following:

```
  public function getForm($form_arg) {
    $form_state = new FormState();

    $args = func_get_args();
    // Remove $form_arg from the arguments.
    unset($args[0]);
    $form_state->addBuildInfo('args', array_values($args));

    return $this->buildForm($form_arg, $form_state);
  }

```

So you don't need to modify the signature of `buildForm()`, you should access these values from `$form_state`.

It should be usable this way: `$form_state->getBuildInfo()['args']`
> 7 votes

---
Tags: 8, forms
---


# Question
Title: Which table stores info about hook_update_N?
I want to re run same hook\_update again. For example hook\_update\_8005. I am not sure where Drupal put info to track.

# Answer
The schema version for the update hook is stored in the `key_value` table.

You can set it with the global function `drupal_set_installed_schema_version($module, $version)`.

For example:

```
drupal_set_installed_schema_version('my_module', 8005);

```

If you want the check the schema version number:

```
$schema_version = drupal_get_installed_schema_version('my_module');

```
> 7 votes

# Answer
To find the row in the *key\_value* table where the *value* (value column) is stored for the number in *hook\_update\_N*, look for the *module machine name* in the *name* column.

For example to get the `N` value for the *block* module, you would run:

```
SELECT value FROM key_value WHERE collection="system.schema" AND name = 'block';

```

Result on a Drupal 8.6 instance is value: `s:4:"8003";`
> 5 votes

---
Tags: 8, updating
---


title: How can I toggle required field?

text:
# Question
Title: How can I toggle required field?
Using Drupal 7.

I'm trying to toggle required field based on the click of a radio button.

I already tried the proposed solution in this post but it did not work.

Here is my code:

```
        $(context).find('.field-name-field-stop-displaying-after').hide();
        $(context).find('.field-name-field-stop-displaying-after').removeClass('required');
        $(context).find("input[name='field_status[und]']").click(function() {
          var radioSelect = $(this).val();
          if (radioSelect == 0) {
            $(context).find('.field-name-field-stop-displaying-after').hide();
            $(context).find('.field-name-field-stop-displaying-after').removeClass('required');
          } else {
            $(context).find('.field-name-field-stop-displaying-after').show();
            $(context).find('.field-name-field-stop-displaying-after').addClass('required');
          }
        });

```

Note that the hide/show toggle works properly.

For the required class, I am targeting the element that the system targets when I set it as required in configuration. The required class is toggled on the element, but does not actually toggle the requirement. In other words, if the field is hidden, it should not be required, but it remains required. The only difference I can see with the system setting is that it adds a legend element that describes the field as required.

What am I missing here? How can I toggle the requirement of the field?

# Answer
In my case, I actually didn't need server-side validation; I just needed validation to serve as a reminder to fill out an exposed field. Instead, I added field-level validation with required.

```
$(context).find('.field-name-field-stop-displaying-after').hide();
$(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',false);
$(context).find("input[name='field_status[und]']").click(function() {
    var radioSelect = $(this).val();
    if (radioSelect == 0) {
        $(context).find('.field-name-field-stop-displaying-after').hide();
        $(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',false);
    } else {
        $(context).find('.field-name-field-stop-displaying-after').show();
        $(context).find("input[name='field_stop_displaying_after[und][0][value][date]']").prop('required',true);
    }
});

```
> 0 votes

---
Tags: 7, forms, javascript
---


title: Year-end Commerce receipts

text:
# Question
Title: Year-end Commerce receipts
I've just stepped in to help work on a half-built Drupal 7 Commerce site for a non-profit who needs to provide year-end receipts to their donors.

Ironically, I can't locate a module which summaries a year's giving. Views is proving problematic.

Any ideas? Thanks.

# Answer
Using: https://www.drupal.org/project/views\_field\_view, https://www.drupal.org/project/views\_merge\_rows, and https://www.drupal.org/project/views\_aggregator

I built a view (Commerce Order) which used the Commerce Order: Uid as a contextual filter and returned line items, using Views Aggregator to tally the item totals and return a yearly total.

I built another view (User), adding the first view as a field; merging rows when necessary, using User: Uid as the merged row's filter.

Things like the address block and thank you paragraph were placed in the User view and rendered above the line items.

Feels kludgy, but seems to work.
> 0 votes

---
Tags: commerce
---


# Question
Title: How do you store webform submits to a different database?
I have a client requirement where "user generated content", in specific, webform submissions from the public, need to be stored in a different database from the normal 'one' database approach.

How do I configure the site to store webform submissions in a different database?

# Answer
General the most secure way is to push a webform submission into a different 'external' database is to create a webservice to populate the external database. Then you can use the 'Remote post' handler to push the submission data via the webservice into the external database.

@see https://www.drupal.org/docs/8/modules/webform/webform-videos#handlers

To disable the saving of submissions…

* Goto /admin/structure/webform/manage/WEBFORM\_ID/settings
* Check 'Disable saving of submissions'
> 1 votes

---
Tags: 8, webforms
---


title: How to customize the shopping cart?

text:
# Question
Title: How to customize the shopping cart?
This is a real puzzle, if I disable the image field of the display mode of variations, it is still displayed in the shopping cart.

Can someone explain to me how to customize the shopping cart ?

I do not understand. The "Teaser" display mode does not exist and the other display modes are not listed in the view. Why ?

# Answer
In the last screenshot it looks like you're using the teaser view mode in the cart view. However, in your first screenshot, it looks like you haven't enabled and configured the teaser view mode on the variations. Scroll down on that page, open the *Custom display settings*, select *Teaser*, and click *Save*.

Afterwards, hide the image from the teaser view mode by clicking on the `Teaser` link below the `Manage Display` tab.

Finally make sure to do this for all variation types you got, if you do it only on one bundle and add a product (variation) of another type to the cart, the change won't be reflected in the cart view.

It seems the above solution doesn't work as expected, although it used to work for me at some point.
Another solution you can try is removing the rendered order item completely from the view, then adding a new relationship from the order item to the product variation and eventually add only the specific fields of the product variation you want to display to the view's fields.
> 0 votes

---
Tags: 8, theming, commerce
---


# Question
Title: How can I disable image resizing in CKEditor?
Our site is responsive and when editors use the resizing handles after uploading an image into the editor, it puts in fixed width and height on the image. We don't want them resizing images at all, due to the responsive nature of the site. Is there a way to disable image resizing in the editor?

If I can write a simple Drupal custom module to get the job done, that would be preferable. I can't seem to find any clear instructions on modifying the CKEditor's configuration dynamically in Drupal, though.

# Answer
> 1 votes
According to How to disable the image resize handles ? this is supposedly solved with `CKEDITOR.config.disableObjectResizing = true;`.

But even when I change it directly (for testing purposes) in /core/assets/vendor/ckeditor/ckeditor.js

`CKEDITOR.config.disableObjectResizing=!1` to

```
CKEDITOR.config.disableObjectResizing=!0
// OR
CKEDITOR.config.disableObjectResizing=1
// OR
CKEDITOR.config.disableObjectResizing=true

```

It doesn't make a difference, I can still resize.

---

So I guess you will have to solve this via CSS.

If you want them to still be responsive, you could do:

```
.some-div img { max-width: 100% !important; }

```

OR

```
.some-div img { max-width: 400px !important; }

```

Obviously, this would mean the size in the editor *may* not reflect the size on the page, but this will do at least in the meantime if you're not satisfied with this answer/approach.

---
Tags: 8, media, wysiwyg
---


# Question
Title: Quiz Module persistance implementation details
In which part of the code is a new quiz stored in the database? What are the functions responsible for storing a new quiz in the database upon the submission of the form for creating a new quiz?

I'm trying to accomplish two things:

1. Timer per question
2. Dynamic question selection strategy

Quiz Module Version: 7.x-5.3

# Answer
You need to be familiar with Drupal concepts like *Nodes* and *Entities* because they are used to model a *Quiz*.

The logic to keep the pieces synchronized is implemented via *Hooks*, like \_hook\_insert\_ and \_hook\_update\_, located on the *quiz.module* file.

### Quiz 2.0 Architecture Information

> A Quiz is a Drupal node, and thus the node table contains a row for each Quiz. Similarly, a Question is also a Drupal node, so it too has an entry in the node table. Additional properties for Quizzes can be found in the rows of the quiz\_node\_properties table. Similarly, all question-types have a table called quiz\_node\_question\_properties to store additional data. Each question-type also makes it's own set of tables to hold answers and user feedback. That means the multichoice.module question-type gets a quiz\_multichoice\_answers and a quiz\_multichoice\_user\_answers.

### hook\_insert

```
/**
 * Implements hook_insert().
 */
function quiz_insert($node) {
  // Need to set max_score if this is a cloned node.
  $max_score = 0;

  // Copy all the questions belonging to the quiz if this is a new translation.
  if ($node->is_new && isset($node->translation_source)) {
    quiz_copy_questions($node);
  }

  // Add references to all the questions belonging to the quiz if this is a
  // cloned quiz (node_clone compatibility).
  if ($node->is_new && isset($node->clone_from_original_nid)) {
    $old_quiz = node_load($node->clone_from_original_nid);

    $max_score = $old_quiz->max_score;

    $questions = quiz_get_questions($old_quiz->nid, $old_quiz->vid);

    quiz_set_questions($node, $questions);
  }

  _quiz_common_presave_actions($node);

  // If the quiz is saved as not randomized we have to make sure that questions
  // belonging to the quiz are saved as not random.
  _quiz_check_num_random($node);
  _quiz_check_num_always($node);

  quiz_update_defaults($node);
  _quiz_insert_resultoptions($node);
}

```

### hook\_update

```
/**
 * Implements hook_update().
 */
function quiz_update($node) {
  // Quiz node vid (revision) was updated.
  if (isset($node->revision) && $node->revision) {
    // Create new quiz-question relation entries in the quiz_node_relationship
    // table.
    quiz_update_quiz_question_relationship($node->old_vid, $node->vid, $node->nid);
    drupal_set_message(t('Some of the updated settings may not apply to quiz being taken already. To see all changes in action you need to start again.'), 'warning');
  }

  // Update an existing row in the quiz_node_properties table.
  _quiz_common_presave_actions($node);

  quiz_update_defaults($node);
  _quiz_update_resultoptions($node);

  _quiz_check_num_random($node);
  _quiz_check_num_always($node);
  quiz_update_max_score_properties(array($node->vid));
}

```
> 1 votes

---
Tags: 7, quiz
---


# Question
Title: How to fetch the content author name with views in twig?
I am unable to fetch the content author name inside the twig template thorough views.

Below is what i did so far : \- Created a relationship under the advanced tab in views and added the Authored by field.

I can see the author in the preview section of the view but since i have overridden the template with views-view-filed i cant fetch it in twig with `{{ fields.author.user.name}}`

Kint is not of much help as its freezing the browser.

# Answer
> 0 votes
Better way to answer this is through debugging the views fields by enabling the page\_array check under the devel module settings.We get each and every fields that are available for the twig template.

There are two steps to get this working

Follow the steps mentioned in the comment:

1. https://www.drupal.org/forum/support/post-installation/2011-06-26/drupal-72-views-adding-authors-name-of-a-node#comment-4919120
2. You have to be careful while selecting the field .Please select the field marked in the attached image.
3. Then in the twig template views-view-fields--VIEWNAME.html.twig the variable to be used is `{{fields.nane.content}}`

In addition to the above while researching for the variable name i found that most of the field names commonly used are available under `admin/reports/fields` in the backend of Drupal 8

# Answer
> 0 votes
You can custom views, as you can see in views-view-unformatted.html.twig

> Available variables:
>
> * title: The title of this group of rows. May be empty.
> * rows: A list of the view's row items.
>     + attributes: The row's HTML attributes.
>     + content: The row's content.
> * view: The view object.
> * default\_row\_class: A flag indicating whether default classes should be used on rows.

If you want to use fields in a view template, use `views-view-fields--[view-name]--[machine-name].html.twig`. There, you can print your fields like this:

```
<span>{{ fields.title.content }},</span><span>{{ fields.body.content }}</span><span>{{ fields.author.content }}</span>

```

---
Tags: views, 8
---


# Question
Title: \Drupal::request() vs $request_stack->getCurrentRequest()
These seem to return the same thing:

`\Drupal::request()`

`$request_stack->getCurrentRequest()`

Which is the preferred way to get the current request and why? Is one of these to be deprecated? Any other advantages/disadvantages?

Thanks!

# Answer
> 23 votes
How to get the current request object:

**Procedural**

In procedural code get the request from the static wrapper `\Drupal`:

```
$request = \Drupal::request();

```

**Service**

In a service get the current request from the injected argument `@request_stack`:

The `module_name/module_name.services.yml` file :

```
services:
  custom.service:
    class: Drupal\module_name\Service\CustomService
    arguments:
      - '@request_stack'

```

The `module_name/src/Service/CustomService.php` file :

```
use Symfony\Component\HttpFoundation\RequestStack;

/** @var \Symfony\Component\HttpFoundation\RequestStack */
protected $requestStack;

class customService
{
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  public function doSomething() {
    // use $this->requestStack->getCurrentRequest()
  }
}

```

**Controller**

In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from `UserController`:

```
use Symfony\Component\HttpFoundation\Request;

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    // use $request
  }

```

It's not necessary to define the route parameter in the route definition. The request is always available.

**Form**

In a form method get the request from `getRequest()`:

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $request = $this->getRequest();
    ...
  }

```

Don't use the injected requestStack property directly, because it is not available for all Form API callbacks.

---
Tags: 8
---