title: How to get the fields of the entity?

text:
# Question
Title: How to get the fields of the entity?
I need to get all the names of the entity, my entity is called 'a\_process'? How can I write such query in Drupal 8?

```
$nodes = entity_load_multiple('a_process', $name);

```

# Answer
You can use the entity type manager to load entities of any type:

```
$entities = \Drupal::entityTypeManager()
  ->getStorage('a_process')
  ->loadMultiple();

foreach ($entities as $entity) {
  // ...
}

```

If your code is in a container aware context, be sure to inject the entity manager as a service instead of referring to `\Drupal` explicitly.

Of course if you always know the entity type up-front you can use the method on the entity class itself, eg

```
$entities = \Drupal\foo\Entity\AProcess::loadMultiple()

```
> 3 votes

---
Tags: entities, 8
---


title: Cannot install any theme

text:
# Question
Title: Cannot install any theme
I am new to Drupal and am facing an issue where any theme that I try to install will fail with the following message:

```
Installing light_skeleton
An error has occurred.
Please continue to the error page

An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: /core/authorize.php/core/authorize.php?batch=1&id=4&op=do_nojs&op=do
StatusText: Forbidden
ResponseText:
403 Forbidden
403 Forbidden
nginx/1.9.10

```

The root folder is owned by `www-data:www-data` and I have given the directory 775 permissions. I have also tried to give it a full access using `chmod 777` but without success.

I have checked the logs of nginx and php but there are no errors displayed. The site itself, using the standard theme, works without any issues.

After getting the error, I get:

```
Notice: Undefined index: log in update_authorize_install_batch_finished() (line 291 of core/modules/update/update.authorize.inc).
Warning: Invalid argument supplied for foreach() in update_authorize_install_batch_finished() (line 291 of core/modules/update/update.authorize.inc).
Notice: Undefined index: log in update_authorize_install_batch_finished() (line 332 of core/modules/update/update.authorize.inc).
Notice: Undefined index: tasks in update_authorize_install_batch_finished() (line 333 of core/modules/update/update.authorize.inc).
Installation failed! See the log below for more information.

```

# Answer
> 17 votes
This is an nginx configuration issue and discussed intensely on this page Yet curiously no solid solution could be offered. Some guy on an other page proposed a solution. I applied that proposed solution and can confirm that in works!

To apply proposed solution go to your nginx configuration file under

**/etc/nginx/sites-available/** directory on Ubuntu and add

```
rewrite ^/core/authorize.php/core/authorize.php(.*)$ /core/authorize.php$1;

```

**just above the**

```
location ~ \..*/.*\.php$ {
    return 403;
}

```

block. Location does matter!.. Restart your server:

> sudo service nginx restart

and that's it. The problem solved!

# Answer
> 2 votes
Since you are getting a 403 response, it seems that Drupal is not giving you access for some reason. I haven't had any practical experience with this, but looking in the `authorize.php`, file I found this:

```
function authorize_access_allowed(Request $request) {
  $account = \Drupal::service('authentication')->authenticate($request);
  if ($account) {
    \Drupal::currentUser()->setAccount($account);
  }
  return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
}

```

It seems that you could get an access denied response if:

* You don't have `administer software updates` permission.
* `allow_authorize_operations` is set to false. This would exist in your `settings.php` file AS `$settings['allow_authorize_operations'] = FALSE;`

Best guess is that it's the latter that might be your problem.

# Answer
> -2 votes
I have similar error, any solution?
update i just finally fixed it just add this: rewrite ^/core/authorize.php/core/authorize.php(.\*)$ /core/authorize.php$1; to my server{} block of my nginx conf

---
Tags: 8, installation
---


# Question
Title: Weird gibberish characters appearing on bottom of Drupal 7 pages
What are some reasons to why there would be weird gibberish characters appearing on the bottom of a Drupal 7 site? I work in a linux environment, but sometimes I copy the files over from windows. I'm not sure if that is the culprit, but how would one even debug something like this?

# Answer
> 1 votes
Since these characters appearing within certain section of the website, you need to identify the source of it and which rendering element is responsible for it (either template file or some function).

The easiest way would be to track it down by enabling `theme_debug` variable in your settings file which enable you to debug the output of the rendering engine.

So please add this line into your settings file:

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

```

then refresh the page and check the source code to see which rendering element is outputting this.

---

For more advanced solution, use PHP debugger such as `phpdbg` (in PHP \>=5.6 core) or XDebug (which allows you to generate a trace file and find the source of the problem). Here is sample `xdebug.ini` config, so in your scenario you just need to enable `xdebug.auto_trace`, generate a trace file for single page load, then disable the setting (since it hugely impacts the overall performance). Then open a generated trace file, look for gibberish where they've started to appear and find out which code is generating it.

---
Tags: 7, debugging
---


# Question
Title: How to get the selected value of a dropdown inside panel?
I have an exposed filter inside the panel.

I want to filter the taxonomy term. For that I add "Content: Has taxonomy term (exposed)" field.

I need to get the selected value in js.

```
Drupal.behaviors.mymodule = {
  attach: function (context, settings) {
    var tid = $('#edit-tid').val();
    alert(tid);

  }
};

```

In alert I am getting "All" rather than the selected `tid`, as shown in this image:

# Answer
> 2 votes
Apply little trick and my issue solved. Used default taxonomy search and hide it.

```
(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

```

Solved my issue.

---
Tags: 7, javascript, panels
---


title: Set module installed version

text:
# Question
Title: Set module installed version
In Drupal 7 we could edit the system table to set a module a version back to let the hook\_update\_n run again.

In Drupal 8 there is no system table.

Where can I find what version of the module is installed so I can change this and make sure the update hook is run again?

This is useful while developing `hook_update_N()` of my module so I can test this.

# Answer
> 8 votes
To store/get the version information for a module use the global functions:

```
drupal_set_installed_schema_version()
drupal_get_installed_schema_version()

```

For example set a new version for `mymodule` with drush:

```
drush ev "drupal_set_installed_schema_version('mymodule', '8123')"

```

Print the version with drush, in this example for the module `comment`:

```
drush ev "var_dump(drupal_get_installed_schema_version('comment'))"

```

The functions are defined in schema.inc. Here you can see how to access the key\_value table through the keyvalue api, if you want to use your own code:

```
/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')->set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}

```

# Answer
> 2 votes
Turns out there is now a `key_value` table

This table contains:

```
collection, name, value

```

Where `value` is the installed version.

---
Tags: 8
---


# Question
Title: How does Drupal know when to run an update script?
How does Drupal 8 know what module needs updating and to what version he needs to update?

I have build a module and I'm trying to update it (adding a table). I implemented a update hook numbered 8001, which is the first update, but when I go to update.php Drupal does not see any update for my module.

I expect there must be a place in my module where I can define the current version of my module and another place in the database where Drupal stores the latest installed update of my module. (I need this for debugging the update script later on.)

# Answer
To store/get the version information for a module use the global functions:

```
drupal_set_installed_schema_version()
drupal_get_installed_schema_version()

```

For example set a new version for `mymodule` with drush:

```
drush ev "drupal_set_installed_schema_version('mymodule', '8123')"

```

Print the version with drush, in this example for the module `comment`:

```
drush ev "var_dump(drupal_get_installed_schema_version('comment'))"

```

The functions are defined in schema.inc. Here you can see how to access the key\_value table through the keyvalue api, if you want to use your own code:

```
/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')->set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}

```
> 2 votes

# Answer
> I expect there must be a place in my module where I can define the current version of my module

When you install a module, Drupal checks the update hooks, and stores the higher number your update hooks have (e.g. 8004). That value is then stored in `\Drupal::keyValue('system.schema')`. Drupal then uses that value when it checks again the higher value associated with the update hooks of your module; if that number is higher than the number it stored, it knows there is an update for your module.

You can use `\Drupal::keyValue('system.schema')->getAll()` to get an array of latest versions for all the modules, stored using the module short name as index. You can use `\Drupal::keyValue('system.schema')->setMultiple()` to save the array once you changed it.
> 0 votes

# Answer
SELECT * FROM key\_value WHERE collection = "system.schema"

The schema value stored in BLOB format.
> -1 votes

---
Tags: updating
---


# Question
Title: how to upload multile user profile pics at a time?
I have used **user reg with picture** module for uploading user profile picture on registration page but there is option for uploading only one picture at a time .

I am developing social network website there is requirement of uploading multiple user profile pics.

but how its possible?

# Answer
> 0 votes
You can use something like profile2 module and create image upload filed that allows multiple files.

---
Tags: 7
---


title: Add class of user role to page?

text:
# Question
Title: Add class of user role to page?
I need to add a class of the user's role to my page. Ive tried the following but it doesn't work, and it seems from the comments its not working for others aswell.

```
function THEMENAME_preprocess_page(&$vars) {
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $vars['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}

```

http://grasmash.com/article/drupal-add-current-users-role-body-classes

# Answer
> 6 votes
Use the hook\_preprocess\_html:

```
function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

```

# Answer
> 2 votes
This worked for me using the Omega 3.x theme on Drupal 7. Just add it to your template.php file and it will work. Rename THEMENAME with your theme's name.

Will result in the following format:

```
<body class="html front logged-in page-home toolbar role-authenticated-user role-administrator">

```

===========

```
<?php
function THEMENAME_preprocess_html(&$vars) {
  $body_classes = array($vars['classes_array']);
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $role_class = 'role-' . str_replace(' ', '-', $role);
      $vars['attributes_array']['class'][] = $role_class;
    }
  }
}
?>

```

# Answer
> 0 votes
For non-omega themes, I used duckx's approach and ended up with:

```
function THEMENAME_preprocess_html(&$vars) {
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $role_class = 'role-' . str_replace(' ', '-', $role);
      $vars['classes_array'][] = $role_class;
    }
  }
}

```

---
Tags: 7, theming
---


# Question
Title: Should QA engineers directly update Drupal database tables via SQL?
Is it generally accepted that it's ok in the Drupal community for QA testers to directly update and delete data in Drupal core tables via SQL? Or is it considered a bad practice? I'm talking about non-production environments--Production is definitely a no-no.

We are fortunate enough to have dedicated Quality Assurance engineers. I'm a developer and am very cautious about writing SQL update and delete statements on our Drupal tables (again, non-production). We usually script things in drush or use Drupal's API.

I think our QA engineers are great, but it seems like a very risky venture to directly update and delete data in core Drupal tables with SQL, even in non-Prod. I would think using tools such as Selenium or scripted solutions that use an API would be preferred, as long as they provide the same functionality.

Your input would be greatly appreciated. Any links with guidelines on this topic would be extremely helpful too.

# Answer
If you directly update and delete data in Drupal tables via SQL, you don't allow Drupal core and third-party modules to detect such changes.

Instead, I suggest you have a look at some (common used) modules that may help updating/deleting such data, in "the Drupal way". Just to mention a few:

* Flag \- eg to "mark" nodes, users, etc for anything that's relevant for testing purposes.
* Rules \- eg to automagically make all sorts of things happen (eg after something like a node or user got flagged with the Flag module).
* Views Bulk Operations (VBO) \- to perform mass updates/deletes on a "list" (created with the Views module) of nodes, users, etc, whereas the actual operations to be performed can be "specified" with custom rules (created with Rules), or the other way around where you create such VBO-list and use it as input for creating ***lists*** and ***loops*** using Rules.

By using the "Drupal way", you also respect its permissions/roles architecture while performing testing (instead of getting around all that via direct updates/deletes). Wouldn't you rather want to discover security holes in testing areas?

Apart from that, there is also the Devel module to facilitate automatically generating nodes, comments, terms, users, and more (for testing purposes).
> 1 votes

---
Tags: database, testing
---


title: Permanent Views Pages

text:
# Question
Title: Permanent Views Pages
Something I've been battling for some time: Is there any way to make the results of a views page permanent?

For Instance: There is a club racing website that inputs Entrants as nodes, to events, which are also nodes. The entrants get scores based upon their performance at the event. However, Entrants come and go in the club, and as they come and go so should their nodes.

Is there any way to make their scores still appear on a views page, even if I happen to delete or unpublish their node? Is there a, 'print as static' option?

# Answer
The views module actively queries (and caches) a database table for results; trying to make the results static or somehow retrieving deleted content would be much work fighting against views' design. I'd say if you're already using unpublishing to designate former entrants, you're better off using the View Unpublished module to give roles the ability to see unpublished entrants.
> 1 votes

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


# Question
Title: how to change the weight of a moderation state transition outside the database
how can I change the weight of a Moderation state transition in code? is it possible? This is for Drupal 8

# Answer
> -1 votes
Change the weight in the admin panel, then export the yaml files with drush config-export

---
Tags: 8, workbench
---


# Question
Title: How to remove Neighborhood and Address 2 fields in commerce kickstart?
In shipping information form there is these 2 fields( Neighborhood and Address 2 ) which I need to remove but I can not find the solution. Any help?

# Answer
> 1 votes
If you log in as admin:

1. Got to: admin/commerce/customer-profiles/types
2. Select the "manage fields" for the correct profile
3. Edit the Address field
4. Under "Format handlers" there should be checkboxes to hide the fields you do not want to show.

To do via code, see Use only one address field

---
Tags: 7, commerce
---


# Question
Title: Unable to get my ContentEntity base field definition to appear as checkboxes
I am trying to implement a base field with multiple selections as checkboxes I have had a go at implementing it but it stills appears as a select even after clearing the cache. I'm sure I'm doing this wrong but this is what I have:

```
$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'checkboxes',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

```

# Answer
> 5 votes
Try with `options_buttons` because this is the ID if the OptionsButtonsWidget widget.

```
$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

```

---
Tags: 8, entities
---


# Question
Title: Revision tab is not listing any revision
I have the Node revision module (**diff**) installed, and I have many revisions for a node, but the *Revision* tab is not showing any of them, even though the database table contains the data for those revisions.

What may the reason be?

>

# Answer
A core issue related to languages was just fixed today: NodeController::revisionOverview() shows no revisions if node has no translation for current language

However, since you use diff, which replaces that patch and does its own thing, it might be the same or a similar bug there. Create an issue, possibly reference to the core issue.
> 2 votes

---
Tags: nodes, 8
---


# Question
Title: How to limit access to content to only users with the same role as the content author?
I'm having trouble in my Drupal the Views and I don't really know how to solve it.

Let's suppose that we have two roles named Org1 and Org2. We can have more than one user per role so for example:

* A and B belong to Org1.
* C belongs to Org2.

The trouble I'm having is that I want that the content posted by A is seen by all the users in Org1 (in this case A,B) but not the users that are in Org2 (C).

How could be this made? I'm new to Drupal but not to programming in general. I've tried several modules but maybe due to my ignorance I have not been able to make it work (so any suggestion would be great). Any programatically suggestion also would be great (but it will be first time programming in Drupal 7).

What I have currently in mind and would probably solve my problem I think that is to filter by the user is logged in (if I'm user A for example filter by Org1). How could this be done?

# Answer
> 2 votes
# Option 1 - Group module

You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

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

# Resources

# Option 2 - Possible alternatives

Refer to my answer to "Recommended modules for managing Content access?" for some other modules that you might want to consider as a possible alternative. Even though it's not part of your question (today), I don't think any of them have a D8 version already.

---
Tags: 7, users
---


title: How do I fix this error?

text:
# Question
Title: How do I fix this error?
I am getting an error right after creating the tweet.libraries.yml file as per istructions given from a book about Drupal 8 theming. Can anyone help me fix this error?

> The website encountered an unexpected error. Please try again later. Error: Cannot use assign-op operators with overloaded objects nor string offsets in Drupal\Core\Asset\LibraryDiscoveryParser-\>buildByExtension() (line 138 of core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php). Drupal\Core\Asset\LibraryDiscoveryParser-\>buildByExtension('tweet') (Line: 87) Drupal\Core\Asset\LibraryDiscoveryCollector-\>getLibraryDefinitions('tweet') (Line: 66) Drupal\Core\Asset\LibraryDiscoveryCollector-\>resolveCacheMiss('tweet') (Line: 148) Drupal\Core\Cache\CacheCollector-\>get('tweet') (Line: 44) Drupal\Core\Asset\LibraryDiscovery-\>getLibrariesByExtension('tweet') (Line: 58) Drupal\Core\Asset\LibraryDiscovery-\>getLibraryByName('tweet', 'bootstrap') (Line: 54) Drupal\Core\Asset\LibraryDependencyResolver-\>doGetDependencies(Array) (Line: 31) Drupal\Core\Asset\LibraryDependencyResolver-\>getLibrariesWithDependencies(Array) (Line: 104) Drupal\Core\Asset\AssetResolver-\>getLibrariesToLoad(Object) (Line: 116) Drupal\Core\Asset\AssetResolver-\>getCssAssets(Object, ) (Line: 291) Drupal\Core\Render\HtmlResponseAttachmentsProcessor-\>processAssetLibraries(Object, Array) (Line: 161) Drupal\Core\Render\HtmlResponseAttachmentsProcessor-\>processAttachments(Object) (Line: 45) Drupal\Core\EventSubscriber\HtmlResponseSubscriber-\>onRespond(Object, 'kernel.response', Object) (Line: 111) Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-\>dispatch('kernel.response', Object) (Line: 179) Symfony\Component\HttpKernel\HttpKernel-\>filterResponse(Object, Object, 1) (Line: 161) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 62) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 48) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 98) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 77) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 628) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

This is the content of the tweet.info.yml file.

```
    name: tweet
    type: theme
    description: 'A twitter Bootstrap starter theme'
    core: 8.x
    base theme: false

    libraries:
      - tweet/bootstrap

```

This is the content of the tweet.libraries.yml file.

```
    bootstrap:
      version: 3.3.6
      css:
        theme:
          css/bootstrap.min.css: {}
          css/bootstrap-theme.min.css: {}
      js:
        js/bootstrap.min.js
      dependencies:
        - core/jquery

```

# Answer
Change the `tweet.info.yml` file as follows.

```
name: 'tweet'
description: 'A twitter Bootstrap starter theme'
core: 8.x
type: theme
base theme: false

libraries:
  - 'tweet/bootstrap'

```

Put the following in the `tweet.libraries.yml` file.

```
bootstrap:
  version: 3.3.6
  css:
    theme:
      css/bootstrap.min.css: {}
      css/bootstrap-theme.min.css: {}
  js:
    js/bootstrap.min.js: {}
  dependencies:
    - core/jquery

```

Also, be sure you have a `tweet.theme` file in the same directory. This file is necessary for Drupal to recognize the directory contains a theme.
> 5 votes

# Answer
I needed a tweet.theme file. I grabbed it from the data files and pasted it into the directory. The book doesn't say to add a .theme file in the beginning of the corresponding chapter.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Pasting from google docs removes the styles
When I copy text from a google doc and paste it to the ckeditor using the paste from word button it removes all the styling (bold, italics, ...).
How can I fix that?

**update**
*Steps to reproduce* :
Copy one word from a google doc that is both underlined and italicized Paste it into editor
*Expected result* :
The word is pasted in italicized and underlined.
*Actual result*:
The word is bolded, no underlines or italics to be found.

# Answer
I'm not sure what Google docs formatting code is like, it's possibly just HTML. If it is HTML you should be able to directly paste into CKeditor which should paste the formatting.

If you don't get the formatting as you expect and if you don't know how to format in HTML/CSS you have 2 options:

You can try paste into Microsoft Word and then use the "paste from word" button, but not sure if it will keep or remove the formatting, just worth a try.

Alternatively, sometimes it's best to paste plain text and do the formatting in the CKeditor. I know it can be time consuming if it's a lot of text.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Front page works; the rest returns "URL not found"
I have been trying to migrate a Drupal site to do some development locally. After moving the code, restoring the DB and doing some settings, I got the front page of the site to show up (minus some images). However, when I click on any of the menu links, I get the following error:

> Not Found
>
> The requested URL was not found on this server.

Now, I made sure that my base\_url is set properly in settings.php. No trailing slash and all that. Currently it is of the type: http://example.com/drupal\_directory, where drupal\_directory is the directory with the site within Apache's /html folder.

What can I do to fix this? Is there some kind of a setting I am missing? There are no errors in PHP error log.

# Answer
> 0 votes
> **Note:** This answer tells you how I fixed it in Ubuntu. I don't know about other operating systems, but you might wanna look up if mod\_rewrite exits there too. If yes, you probably need to enable it there too.

I had that happen to me. I fixed it by enabling mod\_rewrite.

In your terminal, type:

```
sudo a2enmod rewrite

```

```
sudo service apache2 restart

```

# Answer
> 0 votes
Check if the .htaccess file is ok. Sometimes that gets missed when you do a tar or compress your files.

Please reply what happens if you put yourwebsite.com/?q=admin in your browser.

---
Tags: migrations
---


# Question
Title: Drupal 7 "The form has become outdated. Copy any unsaved work in the form below and then reload this page."
I have a problem. When I put this code in my module checkboxes work great but form throws an error:

```
"The form has become outdated. Copy any unsaved work in the form below and then reload this page."

```

Alert one add node form.

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

  $form['add_phone'] = array (
    '#type' => 'fieldset',
    '#title' => t('Adauga telefon'),
    '#weight' => 6,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['add_phone']['phone'] = array(
    '#type' => 'phone',
    '#title' => t('Phone Number'),
    '#required' => TRUE,
  );

  $form['add_phone']['phone_submit'] = array (
    '#type' => 'button',
    '#value' => 'Add',
    '#prefix' => '<div class="col-md-6 text-left">',
    '#suffix' => '</div>',
    '#ajax' => array(
      'callback' => 'automobil_add_phone_callback',
      'wrapper' => 'add-new-phone',
      'effect' => 'fade',
    ),
  );

  if(isset($form_state['values']['phone']['prefix'])) {
    $upload_users_phone = _upload_users_phone($form, $form_state, 'add');
  } else {
    $upload_users_phone = _upload_users_phone($form, $form_state, '');
  }

  $form['field_temporary_phone'] = array(
    '#prefix' => '<div id="add-new-phone">',
    '#suffix' => '</div>',
    '#title' => t('Telefon'),
    '#type' => 'checkboxes',
    '#weight' => 5,
    '#options' => $upload_users_phone,
  );
}

```

Ajax Callback

```
function automobil_add_phone_callback(&$form, &$form_state) {
  return $form;
}

```

Function that returns a list of user\_phone that is stored in user profile. If a user adds new phone it adds it and return the updated list.

```
    function _upload_users_phone($form, $form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

```

What is a problem (why is the 'form outdated form' error thrown)?

# Answer
> 1 votes
The reason you get the "The form has become outdated." error is because the token fails validation (meaning the old string doesn't match the new string). The token is determined by running a hash on several things including the `session_id()`. When you call `user_save()`, the session is changed/invalidated/whatever. Hence, when the token is tested next time around, it generates a different token because you have a different `session_id()` and therefore fails, thinking you were using an old form.

I have the same issue after calling `user_save()` from within my form processing. The way I fixed it feels like a pretty big hack, but I don't know that there's a clean way around it. The form code doesn't seem to expect that you would ever change/invalidate the session whilst in the middle of handling a form (in this case, a multi-part form).

Once you call `user_save` you must modify the form state manually to insert the updated token. Then, when it checks tokens your new token will match since you generated it after the 'session\_id()' was updated.

So the resulting code looks like this. Notice that the input element is changed for `$form_state` to pass by reference so that the modification gets propagated up.

```
function _upload_users_phone($form, &$form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
    $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

```

You might also need to set `$form_state['values']['form_token']`, but I'm pretty sure it's unnecessary. Again, don't forget the `&` in front of the declaration of the function variable `$form_state` or the value won't make it into the real array.

# Answer
> 0 votes
The reason you get the "The form has become outdated." error is because the token fails validation (meaning the old string doesn't match the new string).

use unset($form\['#token'\]);

# Answer
> -1 votes
This happens, because somehow you're not using Form API correctly.

As for workaround, try adding form\_token into your form, for example:

```
$form ['#token'] = $form_id;
$form ['form_token'] = array(
  '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
  '#type' => 'token',
  '#default_value' => drupal_get_token($form['#token']),
  '#parents' => array('form_token'),
);
}

```

and see if that works.

See also: Getting “The form has become outdated” error

---
Tags: forms, users
---


title: How do I create tabs in an admin page?

text:
# Question
Title: How do I create tabs in an admin page?
How do I create a tab in the admin page using a custom module?

The files defining the routes, links and task are the following.

## cst\_core.routing.yml

```
cst.admin:
  path: '/admin/MyCustomModule'
  defaults:
    _controller: '\Drupal\cst_core\Controller\CstController::content'
    link_id: 'cst.admin'
    _title: 'MyCustomModule Management'
  requirements:
    _permission: 'cst admin'

cst.admin_menu:
  path: '/admin/MyCustomModule/menu-mgmt'
  defaults:
    _controller: '\Drupal\cst_core\Controller\CstController::content'
    link_id: 'cst.admin_menu'
    _title: 'MyCustomModule Menu Management'
  requirements:
    _permission: 'cst menu'

cst.admin_menu_menu:
  path: '/admin/MyCustomModule/menu-mgmt/menu'
  defaults:
    _controller: '\Drupal\cst_core\Controller\CstController::content'
    link_id: 'cst.admin_menu_menu'
    _title: 'MyCustomModule Menu Management'
  requirements:
    _permission: 'cst menu'

cst.admin_menu_menu_taba:
  path: '/admin/MyCustomModule/menu-mgmt/menu/taba'
  defaults:
    _controller: '\Drupal\arm_core\Controller\CstController::content'
    link_id: 'cst.admin_menu_menu_taba'
    _title: 'MyCustomModule Menu Management tabs'
  requirements:
    _permission: 'cst menu'

```

## cst\_core.links.menu.yml

```
cst.admin:
title: 'MyCustomModule'
description: 'MyCustomModule System'
parent: system.admin
route_name: cst.admin
weight: -20

cst.admin_menu:
title: 'Menu'
description: 'Menu Management.'
parent: cst.admin
route_name: cst.admin_menu
weight: 0

cst.admin_menu_menu:
title: 'Menu'
description: 'Menus.'
parent: cst.admin_menu
route_name: cst.admin_menu_menu
weight: 0

```

## cst\_core.links.task.yml

```
cst.admin_menu_menu_taba:
route_name: cst.admin_menu_menu_taba
title: 'tab-menu A'
base_route: cst.admin_menu_menu

```

With this, I should have:

-- MyCustomModule

--- Menu Management

---- Menu

+++++ **tab-menu A (as a tab)** --\> but this didn't happend T\_T

something like this:

# Answer
> 3 votes
The tab is actually appear in this path: /admin/MyCustomModule/menu-mgmt/menu/taba

but it didn't appear in: /admin/MyCustomModule/menu-mgmt/menu

the reason is:

you need to add menu\_menu in task as well, as follow:

```
cst.admin_menu_menu:
  title: 'Menu'
  route_name: cst.admin_menu_menu
  base_route: cst.admin_menu_menu

```

so your **cst\_core.links.task.yml** should look like:

```
cst.admin_menu_menu:
  title: 'Menu'
  route_name: cst.admin_menu_menu
  base_route: cst.admin_menu_menu

cst.admin_menu_menu_taba:
  title: 'sub-menu A'
  route_name: cst.admin_menu_menu_taba
  base_route: cst.admin_menu_menu

```

# Answer
> 2 votes
if I suppose `cst.admin_menu_menu_tabA:` is your sub-menu A then also add

> `cst_core.links.task.yml` for tabs or sub menu tabs in an admin page

then add the following code below

```
cst.admin_menu_menu_tabA:
  route_name: cst.admin_menu_menu_tabA
  title: 'sub-menu A'
  base_route: cst.admin_menu_menu

```

proceed so on for the rest of the tabs..

and also add a route for `cst.admin_menu_menu_tabA` in cst\_core.routing.yml

---
Tags: 8
---


# Question
Title: How To Rescue Content from a Corrupt Database
I have spent many weeks inputting content into a commerce system. The database is corrupt. (The website displays fine for an anonymous user, but if you log in you get a blank page. Backups/restore all yield same results) I have now set up a new version of the system, but would like to export/import content and content types from the old system to the new one. How can I do this? Which tables would I need to transfer?

# Answer
> 1 votes
The database isn't likely to be corrupt - unless you're coming up against a ridiculously unlikely scenario, it wouldn't work for any users at all if it was corrupt.

If the data was corrupt, you wouldn't be able to restore the backup, it would fail.

What you need to do is look into the server logs; you're currently seeing a WSOD (White Screen of Death), which is common in PHP applications.

Your server logs will contain details of the exact error your site is encountering, and you can use that information to decide on how to debug and fix it.

# Answer
> 0 votes
I installed Drupal, the template and files and the database to a different server and the whole thing worked. The only thing that changed on the old server between it working and not working is an upgrade of PHP. It must be the culprit. Thanks for helping me work through this issue.

---
Tags: database
---


title: Iterate over items in FieldItemList?

text:
# Question
Title: Iterate over items in FieldItemList?
In other words: How do I get the URI for each of the files in a file field that's on a custom content entity called 'listing'.

Right now I have:

```
$images = $variables['elements']['photos']['#items'];

```

Where $images is a FieldItemList

How do I iterate over my FieldItemList to grab the URI for each of the files referenced therein?

Ok figured first part out with:

```
 $images = $variables['elements']['photos']['#items'];
   $photos = $images->getIterator();
   foreach ($photos as $photo) {
     xdebug_break();
   }

```

Now the question is:

How to get the URI for each of $photo, and assign it as a variable...?

---

### Update

After Berdir's Comment and my own investigation this is what I went with.

```
  if (isset($variables['elements']['photos']['0'])) {
    $number_of_photos = count($variables['elements']['photos']['#items']);
    $listing_pics = [];
    for ($i = 0; $i < $number_of_photos; $i++) {
      $pic = file_create_url($variables['elements']['photos'][$i]['#file']->getFileUri());
      $listing_pics[] = $pic;
    }
  $variables['elements']['listing_photos'] = $listing_pics;
  }

```

This is in a Hook\_template\_preprocess\_HOOK(), and now all of the urls from my multi-value file field are available to the template like this {{ elements.listing\_photos }}

# Answer
PHP calls getIterator() for you, you don't have to do that. Also use $variables\['node'\], much easier to access.

File/Image references an extension of entity references, which means they inherit the computed -\>entity property, which automatically loads the referenced entity. Make sure you check if the file can be loaded, or inconsistent data (if, for some reason, the file gets deleted. Less likely for files but could happen for node or other references) would result in a fatal error.

```
foreach ($variables['node']->photos as $item) {
  if ($item->entity) {
    $uri = $item->entity->getFileUri();
  }
}

```

$uri is something like 'public://your\_file.jpg'. You can create a public url with file\_create\_url() or you can also pass it to an image style entity's buildUrl() method to get the URL for a given image style.

See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for common ways to access field values, what properties exist for each field type and much more.
> 13 votes

---
Tags: 8, files
---


# Question
Title: Entity Embed module not working as expected
I am wanting to use the Entity Embed module, and have installed this an it's dependent, Embed module, in Drupal 8.

There are no errors in the log, nor any javascript errors.

When I go to create the Entity Embed button, I get the follow UI feedback:  Is there something I need to do to allow entities to be embedable?

**Installed Modules:** Here is a list of all modules I have installed.

# Answer
> 2 votes
You only have the Embed module enabled, but not Entity Embed itself.

Embed is just the underlying API/framework on which Entity Embed and Url Embed build.

---
Tags: 8, entities
---


# Question
Title: How do I force a new module to inherit the file permissions the modules directory has, after update?
I'm using Drush 7 on Windows Server 2012 and IIS 8. Whenever I use `drush up` to update a third-party module, IIS can't access the files because during the update process, when drush is replacing the module files, the entire module folder contains permissions assigned to **only** the administrator, with **inheritance disabled**.

I need Drush to replace the module files with **inheritance enabled**; otherwise, Drupal will complain that it can't read the module files and break my site.

How can I achieve this?

# Answer
I know this is old but recently I stumble upon the same problem:

* Site installed on IIS 8 under Windows Server 2012 R2
* After updating with Drush core and modules, permissions of modules and updated files get messed up.

Solution I found is:

* right click on website folder\> Security \> Advanced
* check: *"Replace all child object permission entries with inheritable permission entries from this object"*
* Apply

If files don't shows navigate to `/sites/default/files` or whenever files are stored and change permission to this folder and subfolders.
> 1 votes

---
Tags: drush
---


title: How do I add a field in the toolbar?

text:
# Question
Title: How do I add a field in the toolbar?
How do I add a custom field in the toolbar?

# Answer
The examples module kinda does this:

it's not a drop down, but lists the links under. Take a look at `// Create the examples toolbar render array.` in examples.module to see how they do it.

---

**Now, I don't know if you can put an actual field in the toolbar with PHP code**. The only thing that I can think of is to use CSS. I tested this and it worked.

`.field-in-question { position: fixed; top: 10px; z-index: 999; }`
> 0 votes

---
Tags: 8
---


# Question
Title: How to call one file functions in other files in custom module?
I have created custom module in Drupal 7.

I want to create one file and in this file I want to create all functions that I need to use in this module. I want to call these functions in .module file. So for this what file and how can I use these functions?

# Answer
> 1 votes
It's PHP, so you use `require` or `include` to include functions from other files.

Drupal's wrapper around those is `module_load_include`. Examples from the docs:

```
// Load node.admin.inc from the node module.
module_load_include('inc', 'node', 'node.admin');
// Load content_types.inc from the node module.
module_load_include('inc', 'node', 'content_types');

```

Only use this function inside another function, not in global scope. If you need to unconditionally depend on a separate file for a whole module, just use `require_once` or whatever makes most sense for your use case.

---
Tags: 7
---


# Question
Title: How can I show the flag field using Twig?
I created a twig template for my node.

If I want to show the body field, I use `{{ content.field_body }}`. Similarly, how can I show the flag field?

# Answer
I found it.

Flag machine name: `bookmark`

Then we can use `{{ content.flag_bookmark }}` in `node.html.twig` to show bookmark flag .
> 8 votes

---
Tags: theming, 8, flags
---


# Question
Title: Best way to store not publicly viewable data?
I wanted to know what is the most suited to store not publicly viewable data? Here is an example what I want to achieve:

Imagine having a personal section about me. On this site I show the visitors an online CV which includes a section of my skills. In the section "skills" I have listed each skill with a specific rating like 8/10 depending on how good I'm in it.

For helping you to visualize it, here is a normal CV with a section skills:

https://creativemarket.com/GraphicsToll/492647-Resume

Now my question is how do I store this kind of data? I know that a normal custom content type would be an overkill because not one of the skills should be separately viewable, it should be only visible with all the other skills on my online CV. Further I looked into custom content entities but I think this also an overkill because you could also view each skill separately (canonical).

What other ways are there? Do I have to create a module which just interacts with the database abstraction layer?

I appreciate any kind of help!

# Answer
> 1 votes
The simplest way to do this is to put the two fields "skill name" and "rating" in a field collection:

Field collection

But I would suggest to use the new module Paragraphs. This will extent Drupal's flexibility to design content types for structured data a lot:

Paragraphs

Edit:

Changed module name (thanks to @Berdir).

---
Tags: forms, database, 8, entities
---


# Question
Title: How do you use drupal's devel krumo ddebug_backtrace()?
I've been trying to debug a weird bug on Drupal 7 for awhile. It happens randomly on my site as it's hard to reproduce. I'm able to finally get `ddebug_backtrace()` to run when the error happens. The error breaks all of my views on the site when it happens and throws the following error:

> Warning: include(/home/xxx/public\_html/.tpl.php): failed to open stream: No such file or directory in theme\_render\_template() (line 1534 of /home/xxx/public\_html/includes/theme.inc).

It's complaining that `theme_render_template()` can't find a template file as the variable given to the function is just .tpl.php.

I'm able to insert an if statement when this happens within that function as this:

```
  if($template_file == '.tpl.php') {
    ddebug_backtrace();
    print_r('<pre>xxxx');
    print_r('TEMPLATE FILE: ');
      print_r($template_file);
    print_r('</pre>');
  }

```

I'm able to get the debug output in krumo as shown below. I'm not exactly sure what I should be looking for. I just understand that each numbered line represents where that function was called within that order. But what I'm trying to look for is a blank variable of some sort which makes it output .tpl.php to give such an error.

Judging from the output, the culprit is the Views module, but I'm not sure where. What should I be looking for exactly?

# Answer
> 0 votes
This bug was quite annoying to solve. What I did was:

* Isolate the variable that was causing the issue.
* Setup a conditional to detect this variable when it happens.
* Add drupal's ddebug\_backtrace() to the conditional.
* Trace back to where the function was being called up.
* Find out how that problematic variable is being passed in.
* Keep following the backtrace to the point where that variable is assigned and not just passed along to another function. In my case it was in theme() that assigned the blank variable *$template\_file*.
* From there I needed to know when theme() was being called. The original backtrace didn't leave any clues to which module was calling it aside from views, but views gets called all over the place. Now I needed to find the module that was calling views.
* In theme() there were a bunch of hook variables that gave the hint of where it was coming from. I dpm() all the $hook and $hooks variables and it showed the error was happening when a "display suite" hook was being called.
* In the end all I needed to do was uncheck this box. I still don't know why it caused the issue randomly... -\_-

My debug code to get the output I needed:

---
Tags: views, debugging
---


# Question
Title: How to create a rule to remove a product by sku, or remove a product to the cart
I searched, and searched in many, many articles and and I have not found a solution. What I want to do is to create a rule to delete a product by sku? Or a rule to delete products.

I show you my problem:

In my installation of commerce, I have two products. The first (the mother) is a "course". The second is a "enrollment". When you buy a course, the enrollment is added by a rule.

Well...but what if the user wants to delete the enrollment? What I want is that, if a user removes the enrollment, the "course" is removed too and vice-versa.

# Answer
You are making the assumption a commerce order in cart status contains products. In fact a commerce order consists of line-items that in turn link to products. These line items also contain also the unit price and the amount of the product (and some other details). It can be done but it requires some juggling with Rules as there is not a remove from cart rules.

So your Rules should fire on the event `A product is removed from cart`. Your condition should be to check for the product SKU, and in the actions you will have to run through all line items and delete the right one.

So you need to add a Loop through each line item on the commerce order to find the right product.

This is the easiest if you create a Rules component where you send the current line-item and the SKU to remove. Then in that Rules component add the following conditions:

* Entity had field. (Make sure the line item has a product field)
* Data comparison. (Make sure the product SKU matches the input SKU)

Action:

On the main Rule, use the following actions:

* `Set a data value` (to set your SKU to remove, this will be sent to the component).
* Add a loop (Provide it with the commerce-order:line-items to loop over those)
* In the loop, add your component as an action and provide it with the loop's current item and the SKU to remove.

**Final note**: As it appears you will always be selling these products in pairs, you might find the Commerce Product Bundle interesting. It allows you to combine two products into one. I suppose it will remove both products also when removed from the cart.
> 1 votes

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


# Question
Title: Content entity form not displaying the previously selected value
Even though I can see that my data is being saved it doesn't ever appear to be set when I go back to edit my entity via a form. Am I missing something in my setup?

Here's what I have:

```
      $fields['content_display'] = BaseFieldDefinition::create('list_integer')
          ->setDisplayOptions('form', [
              'type' => 'options_buttons',
              'weight' => -4,
          ])
          ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
          ->setSetting('allowed_values', $values)
          ->setDisplayConfigurable('form', TRUE);

```

# Answer
> 0 votes
You need to set a default value for the field. Drupal's field system by default assumes a field is empty, you will have to manually add a default value to the field definition.

This default value should be based on your entity's value, or be an empty string or NULL in case there is no value yet. Try something like this:

```
// Use the entity value if available, or NULL otherwise.
$default_value = !empty($entity->my_value) ? $entity->my_value : NULL;
$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', [
    'type' => 'options_buttons',
    'weight' => -4,
   ])
  ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

  // Set the default value on the field.
  ->setDefaultValue($default_value);

```

---
Tags: entities, 8
---


# Question
Title: How to assign content to user for manage turns?
I need to create a system to assign turns to a people register in the site, for this need contemplate:

1. The administer assign turn to user in specified place.ex(turn 1, place 1, user 1)
2. There are two turns, morning and afternoon in one day.(turn 1 and turn 2)
3. The administer cannot assign a turn to user that have turn 1 in place 1 and later turn 1 in place 2, need show only the users that no have turn 1.
4. The system need show the turn to user in calendar, only need show the turns in the week, ex (Monday: turn 1 place 1, Tuesday: turn 2 place2, Wednesday: turn 3 place 3, etc).

I think make

content type of turns that have

```
- field date, end and start for statistics support and classify the week.
- turn select: turn 1 or turn 2.
- zones select: place 1, place 2, place3 etc.
- user to assign: user reference field that have all user that i can assign turns.

```

I want use drupal fields and contrib modules (if exist) to make this, or how to make better with drupal, any suggestions?

# Answer
You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

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

# Resources
> 2 votes

---
Tags: 7, nodes, entities, datetime
---


# Question
Title: Content type access permission by user role
I have created 4 different content types and all except only one content type are visible to every user. Here, I am not using any type of access module like content access, field permission or organic groups even I have also uninstalled my custom module but still could not able to find out the root cause .

In the attached screen shot 1) The above section is permission on a node created in that content type as per user roles. 2) The below section is what, which is visible to user other than site admin.

I have also gave "View published content", "View own published content" and "View content revision" permissions (and cleared the cache) but it still not fixed.

Appreciate any guess or suggestion !!

# Answer
> 1 votes
Yes, I have got the issue. This was a silly mistake, the nodes in that content types were not published.

I just published them and they are now visible to allowed roles.

Thanks

---
Tags: 7, nodes, hooks
---


# Question
Title: How to make a popup appear on the side/bottom of the page instead of the center?
I'm still very new to Drupal and I've been trying to get a popup to appear on my page in a specific location. Popup on load (https://www.drupal.org/project/popup\_onload) does pretty much everything I want, except that it appears in the middle of the screen. Anyone know what I can do so that it'll appear on the side or bottom of the screen? Or know another module out there that has this kind of configuration?

# Answer
> 1 votes
The Popup on Load module leverages the Colorbox module, and its jQuery plugin dependency, to style the pop up. The module allows for your own custom style which will let you adjust the popup position to where you want it. This is covered in its documentation.

> **Add a custom Colorbox style to your theme**
>
> The easiest way is to start with either the default style or one of the example styles included in the Colorbox JS library download. Simply copy the entire style folder to your theme and rename it to something logical like "mycolorbox". Inside that folder are both a .css and .js file, rename both of those as well to match your folder name: i.e. "colorbox\_mycolorbox.css" and "colorbox\_mycolorbox.js"
>
> Add entries in your theme's .info file for the Colorbox CSS/JS files:
>
> ```
> stylesheets[all][] = mycolorbox/colorbox_mycolorbox.css
> scripts[] = mycolorbox/colorbox_mycolorbox.js
>
> ```
>
> Go to "Configuration" » "Media" » "Colorbox" and select "None" under "Styles and Options". This will leave the styling of Colorbox up to your theme. Make any CSS adjustments to your "colorbox\_mycolorbox.css" file.

---
Tags: javascript
---


title: Template for custom content type

text:
# Question
Title: Template for custom content type
I created a module which creates a content type called **equipment**. Which includes multiple fields and a field collection. But now I want to style the template with those fields. As suggested from the HTML comments thanks to the Twig debugging, I created a file called **node--equipment.html.twig** which is located inside the **templates** folder of the module. Unfortunately this template won't show up, so it shows the default template.

Doesn't Drupal 8 recognize the Twig file? What is the reason for not showing the wanted template? How can I fix this?

# Answer
> 4 votes
To recognize a suggestion in a module, you need to explicitly specify it in hook\_theme() of your module.

`system_theme()` for example has this:

```
// Normally theme suggestion templates are only picked up when they are in
// themes. We explicitly define theme suggestions here so that the block
// templates in core/modules/system/templates are picked up.
'block__system_branding_block' => array(
  'render element' => 'elements',
  'base hook' => 'block',
),

```

Copy the original definition and then change the key and set the base hook.

# Answer
> 3 votes
I finally fixed the problem. As Berdir said, to recognize a template you need to explicitly specify a suggestion in the `hook_theme()` implementation of the module. My `hook_theme()` looks like this:

```
function equipment_theme(array $variables) {
  $theme = array();

  # Suggestion for the template
  $theme['node__equipment'] = array(
      'render element' => 'content',
      'base hook' => 'node',
      # template file
      'template' => 'node--equipment',
      # location of the template file
     'path' => drupal_get_path('module', 'equipment') . '/templates',
  );

  return $theme;
}

```

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


# Question
Title: What hook for triggering an action after saving a new node?
I'm running Drupal 7 and I want to re-save the user account of the node author after deleting a node of content type picture. I want to do this because I have some code called in hook\_user\_presave() that counts the number of pictures a user has added and saves it in an integer field in the user.

I looked at hook\_node\_submit() and hook\_node\_update(), but when then are invoked, the node is not yet saved, so if I save the user at that point, the int value is one less than it should be (because the added node has not actually been saved yet).

Is there a hook for reacting after a node has been added?

Related question: Hook for reacting after deleting node

# Answer
You can use ***Hook Post Action*** module which will provide you hooks like:

* hook\_entity\_postsave
* hook\_entity\_postinsert
* hook\_entity\_postupdate
* hook\_entity\_postdelete
* hook\_node\_postsave
* hook\_node\_postinsert
* hook\_node\_postupdate
* hook\_node\_postdelete

These hooks are fired after node is saved to the database. So the process you want to do after node save can be done using these hooks which comes with ***Hook Post action*** module.
> 4 votes

# Answer
A site-building option, if you are already using the "Rules" module, is to have a rule that reacts to two events:

* After saving new content
* After updating existing content

and then perform the actions you need (for example *"Save entity" -\> site:current-user*). You could also put your custom code in a specific rules action if this is better for your use case.
> 2 votes

# Answer
**hook\_node\_insert** \- Respond to creation of a new node.

> This hook is invoked from node\_save() **after** the database query that will insert the node into the node table is scheduled for execution, **after** the type-specific hook\_insert() is invoked, and **after** field\_attach\_insert() is called.
> 0 votes

---
Tags: 7, hooks
---


title: Configuring Views into Features

text:
# Question
Title: Configuring Views into Features
I have inherited a complex website which has the Features and Views module installed. I can configure a Feature to include a View as you would expect.

However, I'm putting together a private website which also has Views and Features installed. My problem is Views does not appear as an option to select data from when configuring the Feature.

**Is there a setting or module which is responsibly for exposing Views in Feature create/edit mode ????**

The image on the Feature project page seems to suggest Views should be there by default.

Any help, please !

# Answer
Perhaps all the available views have been added to other features? Try enabling the checkbox "Allow conflicts to be added" in the 'Advanced Options' section of the 'Create' page. If you can see the views then, it means they are already assigned to other features.
> 0 votes

---
Tags: 7, views, features
---


title: look up page View by its path

text:
# Question
Title: look up page View by its path
We can search all the default views on our relatively new Drupal 8 site, to see what view resides at a particular path, with a query like:

```
$view_trim_path = 'blog';
$query = $this->entityQuery->get('view')
  ->condition('display.page_1.display_options.path', $view_trim_path)

```

Unfortunately, this relies upon a hardcoded display name of `page_1`, which will not hold true in general. In my dreams I would use a wildcard query like

```
  ->condition('display.page*.display_options.path', ...)

```

Is there a way to do either of the following?

1. create a set of entityQuery conditions to find views that have `display.*.display_options.path` equal to a certain value, no matter what the value of `*` ... preferably when `*` begins with the `page_` prefix
2. use another Drupal / View function to look up a view ID from its path (I can't find one)

I can see how to find this by loading the config entities for all views and traversing all those arrays, but my guess is that Drupal has provided a simpler means for this. Also it seems the database abstraction layer would be of use, and if that's the best practice then it would really help me to have an example of how to use it for the above query.

# Answer
The page prefix is meaningless, it can be changed by the user and can be anything.

So you just want `display.*.display_options.path`.

It would match on other displays that have a path setting (e.g. REST or feed). If you want to avoid that, you add a second condition on display\_plugin = page.
> 0 votes

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


title: Controller and Form

text:
# Question
Title: Controller and Form
What's the key difference between:

```
amazing_forms_contribute:
  path: 'amazing-forms/contribute'
  defaults:
    **_form: '\Drupal\amazing_forms\Form\ContributeForm'**
    _title: 'Conribute page'
  requirements:
    _permission: 'access content'

```

and

```
amazing_forms_contribute:
  path: 'amazing-forms/contribute'
  defaults:
    _**controller: '\Drupal\amazing_forms\Controller\ContributeForm::content'
link_id: 'arm.admin_product_variants_create'**
    _title: 'Conribute page'
  requirements:
    _permission: 'access content'

```

When I should use a controller? And when I should use a form?

Can I combine both (use controller and form)?

What is their limitation?

# Answer
`_form:` We use this explicitly when one expects a classname implementing FormInterface.

`_controller:`It is used when one needs to return a renderable array or an object. Hence, here we call a method from its class (classname::method)

And **NO** you cannot use `_form and _controller` at the same time under defaults: since one routing only provides **one functionality at a time**.

> See here to understand how the structure of routes are used and why they were used.Also see routing api for a more detailed understanding.
> 4 votes

---
Tags: 8
---


# Question
Title: Problem with the schema structure produced by Schema module
I am using the Schema module (7.x-1.2) on Drupal 7.34. This is the code I am using for a module I created.

```
function myid_schema(){
  $schema = array();

  $schema['myid_templates'] = array(
    'description' => 'TODO: please describe this table!',
    'fields' => array(
      'template_id' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'template_name' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'varchar',
        'not null' => FALSE,
      ),
      'portrait' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'boolean',
        'not null' => TRUE,
      ),
      'template_width' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'numeric',
        'not null' => TRUE,
        'default' => 0,
        'precision' => 0,
        'scale' => 0,
      ),
      'template_height' => array(
        'description' => 'TODO: please describe this field!',
        'type' => 'numeric',
        'not null' => TRUE,
        'default' => 0,
        'precision' => 0,
        'scale' => 0,
      ),
    ),
    'primary key' => array('template_id'),
  );

  return $schema;
}

function myid_install() {
  drupal_install_schema('myid_templates');
}

```

After installing the module, it throws this error.

> Notice: Undefined index: boolean:normal in DatabaseSchema\_pgsql-\>processField() (line 229 of C:\xampp\htdocs\drupal-7.34\includes\database\pgsql\schema.inc).
>
> PDOException: SQLSTATE\[42601\]: Syntax error: 7 ERROR: syntax error at or near "NOT" LINE 4: portrait NOT NULL, ^: CREATE TABLE {myid\_templates} ( template\_id serial, template\_name varchar NULL, portrait NOT NULL, template\_width numeric(0, 0) NOT NULL default 0, template\_height numeric(0, 0) NOT NULL default 0, PRIMARY KEY (template\_id) ); Array ( ) in db\_create\_table() (line 2720 of C:\xampp\htdocs\drupal-7.34\includes\database\database.inc)

Why does it throw an error? How do I fix it?

# Answer
> 1 votes
Drupal doesn't have a `boolean` type for DB schema, and there's no automatic fallback for a type it doesn't know about, so you end up with the invalid `portrait NOT NULL` instead of `portrait boolean NOT NULL` in the create statement.

To fix, just add a `pgsql_type` to the column. `DatabaseSchema_pgsql::processField()` knows what to do with it.

```
'portrait' => array(
  'description' => 'TODO: please describe this field!',
  'type' => 'int', // Keep it portable
  'pgsql_type' => 'boolean',
  'not null' => TRUE,
),

```

---
Tags: 7, database, installation
---


# Question
Title: SQLSTATE[23000]: Integrity constraint violation
I am using Commerce Kickstart 2 to build a store. I have several Feeds importers working well. I duplicated a working importer and updated the mapping for the "product variation" and "product display".

When trying to import, I now receive the following error:

> SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'commerce\_product-236' for key 'PRIMARY' SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'commerce\_product-237' for key 'PRIMARY' SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'commerce\_product-238' for key 'PRIMARY'

I have re-run the working importers and do not have this problem. Reading other posts, it sounds like the importer is trying to import the same item twice, but I don't see why.

I checked the log and see that it isn't grabbing "SKU" from my csv and is assigning it something else. How do I deal with this?

> SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'commerce\_product-236' for key 'PRIMARY'
> Original item
>
> ```
> array(
>   'title' => 'model',
>   'brand' => 'brand',
>   'product category' => 'prod',
>   'primary use' => 'MTB',
>   'intended use -alt' => '29+',
>   'frame material' => 'Steel',
>   'brake type' => 'Disc',
>   'rohloff' => 'Yes',
>   'rohloff axle plate' => 'OEM',
>   'belt compatible' => 'Yes',
>   'tensioning method' => 'Pivoting Dropouts',
>   'build kit img' => '',
>   'body' => 'Customized for Cycle Monkey: Rohloff-optimized designed for trail riding and versatile enough for...',
>   'sku' => 'VN001',
>   'price' => '738000',
>   'dealer price' => '627300',
>   'color' => 'Orange',
>   'frame size' => 'XS',
>   'wheel size' => '29+',
>   'build kit' => 'Signature',
>   'images' => '',
> )
>
> ```
>
> Entity
>
> ```
> (object) array(
>   'type' => 'bikes',
>   'product_id' => '236',
>   'sku' => 'Bikes-236',
>   'revision_id' => '233',
>   'title' => 'model',
>   'uid' => '1',
>   'status' => 1,
>   'created' => 1463278774,
>   'changed' => 1463278774,
>   'log' => 'Created by FeedsCommerceProductProcessor',
>   'revision_timestamp' => 1463278774,
>   'revision_uid' => '1',
>   'language' => '',
>   'is_new' => TRUE,
> )
>
> ```

# Answer
When setting up this product variation, I selected for the SKU to be automatically generated. In doing so, it was tripping up the feeds importer. Not sure if this was a timing issue, but I reviewed the importer set up and product variation fields for the importers that were working vs. not.

This SKU setting was the only difference. Since this field is unique ID, this seemed like the most likely culprit.

I would appreciate an explanation of why this was triggering an issue, but am happy to be able to move on.
> 0 votes

---
Tags: commerce, feeds
---


# Question
Title: View item duplicates based on total views
I have a view that simply loads all the latest articles but I ran into some strange problem. Each time I visit an article, the `view count` increases but this also means that a certain article will appear in the as much as the count shows.

For example:

```
View:
- Article 1
- Article 2

```

When I click on Article 1 my `view` updates to:

```
View:
- Article 1
- Article 1
- Article 2

```

I hope this is clear enough to understand.

Note: maybe worth mention I'm setting up a `service` so in my `json api` I get the same results

# Answer
> 0 votes
Solved it by removing `Node count: node id` I used the wrong `field`to display the `id`

---
Tags: views
---


title: Change catalog taxonomy URLs

text:
# Question
Title: Change catalog taxonomy URLs
How do I change the Ubercart catalog taxonomy URLs in Drupal 8? When I view my catalog, I have URLs like catalog/1 and catalog/2. How do I change them into catalog/taxonomy-term-name?

(I can't find in view settings something like *Convert term name to ID*.)

# Answer
The source for the header of (Catalog views) is from a second view (catalog terms view) you can make changes there

make term id hidden and term name visible
> 0 votes

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


# Question
Title: Prevent WYSIWYG inline images from showing in Teaser Display
Is there an easy way to stop inline images placed through the WYSIWYG editor from showing on a teaser display? Obviously if I use the summary field the problem is solved, but the client may not be conscious enough to always do that. I am currently outputting a featured image through an image field on the teaser display, so when the inline image also shows up it not only blocks the teaser text, it looks pretty weird.

# Answer
Perhaps you could try https://drupal.org/project/advanced\_text or https://drupal.org/project/smart\_trim?

I think they both have the ability to strip html from teasers.
> 2 votes

# Answer
Check you own page code, but something like the following in your css will work:

```
body.front div.field-item img {
  display: none;
}

```

This will allow the teaser to include the inserted image, and suppress the image display on the front page.
> 0 votes

# Answer
body.front img\[data-entity-type="file"\] { display:none; }

Or maybe more specific for the teasers only:

.view-mode-teaser img\[data-entity-type="file"\] { display:none; }

This should solve the problem with the text in the WYSIWYG.

The field-items are still being displayed, including the text inside the p-tag. Only the inline images are not displayed.
> 0 votes

---
Tags: media, wysiwyg, display-suite, nodes
---


title: Services for Privatemsg module

text:
# Question
Title: Services for Privatemsg module
I am using privatemsg services module to create REST API of privatemsg using Services Module in Drupal 7.

If I send GET request to this url : http://example.com/rest/privatemsg/ I get all messages including messages in Inbox and Sent. Is there any way to Get messages from Inbox and Sent separately ? OR is there any way i can differentiate messages from Inbox and Sent ?

# Answer
That resource has an optional type parameter, so you should be able to get away with requesting:

http://example.com/rest/privatemsg/?type=inbox

Or ?type=sent, etc
> 0 votes

---
Tags: services, 8, privatemsg
---


# Question
Title: How to create multiple node at a same time programatically?
I am creating a node via code

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

        if($form_id=='article_node_form'){
            $form['#submit'][] = 'newApp';
        }
}

functin newApp($form,$form_state){
        $node = new stdClass();
        $node->type = 'application';
        node_object_prepare($node);
        $node->title = $prductData->title;
        $node->language = LANGUAGE_NONE;
        node_save($node);
        }

```

It's creating the application node. I also alter content type node form for article. When I click save button of article content type it's creating my application type node, but it's not creating the article type node. I need the site to create one node create of article type and second application when I save a new article.

# Answer
> 2 votes
I guess it is because you overriding node variable.

In my opinion the more Drupal way is to use Rules module. There you can create application node after article is created.

---
Tags: 7, nodes
---


# Question
Title: How to add CSS classes to buttons of Drupal Commerce checkout forms?
How can I add a bootstrap `btn-success` class to the Drupal Commerce Checkout button in the cart form?

The *Update cart* button already has `btn-info` but I can't find `btn-info` anywhere in the code.

If would also like to adapt buttons in other parts as I expect `btn-success` buttons to lead to higher conversion.

Bootstrap has great classes, I don't want to fiddle with CSS to try and recreate that, I just want to use the Bootstrap classes.

I'm okay with adding some PHP code to my theme's `template.php`, probably `_form_alter()` and this is probably the way to do it. But how exactly?

# Answer
According that you have default `views_form_commerce_cart_form_default` form for your cart, this should do the job. Put the following lines in a custom module:

```
function MYMODULE_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  $form['actions']['checkout']['#attributes']['class'] = array('btn-success');
}

```

If not ok, check the ID of your form with

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message("Form ID is : " . $form_id);
}

```

and apply the same above snippet with function `MYMODULE_form_FORM_ID_alter`.

**EDIT :** to apply `btn-success` to *Continue* buttons of the cart, checkout, review pages:

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

  switch ($form_id) {

    case 'views_form_commerce_cart_form_default':
      $form['actions']['checkout']['#attributes']['class'] = array('btn-success');
      break;

    case 'commerce_checkout_form_checkout':
    case 'commerce_checkout_form_review':
      $form['buttons']['continue']['#attributes']['class'] = array('btn-success');
      break;
  }
}

```

To do it yourself next time : in your `hook form alter()` module, check the `form_id`, `dsm($form);` and browse the *dsm tree* to find your needle...
> 7 votes

# Answer
It is difficult to add classes to generated content like that. It is doable but generally not necessary. See this related post and comments for some light on this subject.

You can target the buttons with CSS using a cascade.

The cart page has the body class `.page-cart` and the form buttons has a class `.form-actions`. So, target the buttons with `input`like so:

```
.page-cart .form-actions input { some css here }

```

If you are being overridden, let me know in a comment and I can help with that. A link would be useful.
> 0 votes

# Answer
adding css to the buttons on the cart is the same as adding css to anything else. look at the page where the button is. right click on the button and select inspect element. The browser will display the DOM tree at the position of that element. Look for a point in that element or its parent elements that you can use to target that element. type up your css in your style sheet to target that element. This is how you should do it for anything in drupal. let drupal do the hard work of rendering the page then look at what it makes and style from the output.
> 0 votes

# Answer
With COMMERCE Version: 7.x-1.13 :

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

   if ($form_id = 'form_commerce_cart_add_to_cart') {
         $form['submit']['#attributes']['class'][] = 'btn-success';
   }

}

```
> 0 votes

---
Tags: commerce, theming
---


title: Set node view count manually

text:
# Question
Title: Set node view count manually
This might be not the smartest way to do, but is it possible to set the node view count per node manually?

I'm manually exporting my nodes to another Drupal without using modules; basically, I'm copy-pasting everything since there are things that are changed. The only thing that bothers me is that the number of times a node has been viewed will be lost.

Is there a way to manually change the number of times a node has been viewed?

# Answer
> 1 votes
The best way to change this would be by editing each record in your database using a tool such as PHPmyAdmin. Once you have migrated to the new website, and enabled the Statistics module you will see the column added in your database table.

Hope it all goes well.

Chandeep

---
Tags: nodes
---


# Question
Title: How do I split a contact form into multiple pages?
I have a huge form that's way too large for a single page. I would like to split this form up into a few separate pages. What are my options?

Edit: Still haven't figured out how to do this with Drupal 8.

# Answer
I recommend you build your contact form using the Webform module over the Contact module. It allows you to have a lot more control and flexibility.

Once you're using this, you need to add 'pagebreak' components each time you'd like to add a new page. This tutorial shows you how to do this.
> 1 votes

# Answer
You can use the Field Group module. This works for Drupal 7 and 8.

If you use Drush you can use the following command line.

```
drush dl field_group

drush en -y field_group

```
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Problem with Three hierarchical dropdown for country, state city
I am new in drupal and I am working on one form where I need to create Country, State and city interdependent,hierarchical ajax dropdowns. So far I could achieve country and state dropdown but while making city dynamic on change of state is not working. It calls same callback and wrapper which I used for country even if I kept them separate. Please check below code

```
$form['account']['country_id'] = array(
    "#type" => "select",
    "#title" => t("Select your country."),
    "#options" => $countryArray,
    '#ajax' => array(
        'event'=>'change',
        'callback' =>'my_module_ajax_dropdown_state',
        'wrapper' => 'state-wrapper',
    ),
    '#id' => 'country',
    '#required' => true
);

 if (isset($form_state['values']['state_id'])) {
    // Pre-populate options for city dropdown list if province id is set
    $cityOptions = _load_city($form_state['values']['state_id']);
 }

// Options for city dropdown list
$stateOptions = array('- Select state -');
if (isset($form_state['values']['country_id'])) {
    // Pre-populate options for city dropdown list if province id is set
    $stateOptions = _load_state($form_state['values']['country_id']);
}

$form['account']['state_id'] = array(
    "#type" => "select",
    "#title" => t("Select your county/State."),
    '#prefix' => '<div id="state-wrapper">',
    '#suffix' => '</div>',
    "#options" => $stateOptions,
    "#ajax" => array(
        'event'=>'change',
        'callback' =>'my_module_ajax_dropdown_city',
        'wrapper' => 'city-wrapper',
    ),
    '#default_value' => '--Select State--',
    '#id' => 'state',
    '#required' => true
);

$form['account']['city'] = array(
    "#type" => "textfield",
    "#title" => t("Enter your city."),
    '#id' => 'city',
    '#prefix' => '<div id="city-wrapper">',
    '#suffix' => '</div>',
    '#required' => true,
    '#default_value' => $account->city
);

```

These are my callback functions which are returning form element

```
function my_module_ajax_dropdown_state($form, $form_state){
  return $form['account']['state_id'];
}

function my_module_ajax_dropdown_city($form, $form_state){
 return $form['account']['city_id'];
}

```

I am trying to figure it out but no success yet. Please help me.

Thanks

# Answer
> 1 votes
I was facing the similar issue in my drupal site. The other issue was the performance especially for IE where it took too much time in rendering the new item.

After some experiments, I made the following module that can help in making three hierarchical dropdown for country state and city. Its developed in a generic way that it can be used for n number of dependent dropdowns and can be used for other dependent data as well.

https://www.drupal.org/project/ajax\_chain\_select

---
Tags: ajax
---


# Question
Title: Multiple dates token for auto node title
I am using this token to create node title \[node:field-date-concert:custom:j-m-Y\] and it works fine if there is one value for date in node.

Problem is that if there are 2 or more values i only get first one displayed but would like to get them all. So instead of just showing 05-05-2016 as node title, i would like to have 05-05-2016, 15-06-2016, 28-07-2016.

# Answer
> 0 votes
You could use the following code snippet in your auto\_nodetitle configuration. Don't forget to select the option "Evaluate PHP in pattern.".
And replace the field\_date\_multiple with your own field's machine name.

Hope this helps!

```
<?php

$dates = array();
foreach($node->field_date_multiple[LANGUAGE_NONE] as $date){
  $dates[] = date('j-m-Y', strtotime($date['value']));
}
echo implode(', ', $dates);

?>

```

---
Tags: 7, datetime, tokens
---


# Question
Title: How to drush enable a module only if is not installed
I would like to drush enable a bunch of modules in a certain environment via a shell script that runs EVERY TIME the environment rebuilds when new code is committed. (This saves me from having to have access to a drush terminal when I want to first install a module in an environment, but means I don't know if module is being enabled for the first time or if it was enabled long ago)

I'm concerned there might be consequences of repeatedly enabling already enabled modules. Is this true?

If yes, I'm trying to find a drush command to enable a module only if it's not already enabled.

For example, I have seen this page:

```
drush en `drush pm-list --status="disabled,not installed" --pipe`

```

which enables all disabled modules.

and

```
drush dis `cat tmp.txt` --yes

```

which disables all modules listed in `tmp.txt`

I want something like:

```
drush en `magicfunction(tmp.txt, `drush pm-list --status="disabled" --pipe`)`

```

where `magicfunction` is some linux command line magic that returns the names of modules listed in `tmp.txt` that are also in the list of not enabled modules.

Any ideas?

# Answer
> 1 votes
You can use grep command to filter out the modules from disabled list to only which are appearing to your list, e.g.

```
drush -y en $(drush pm-list --status="disabled" --pipe | grep -f tmp.txt)

```

---

Other way is to use SQL query:

```
drush -y en $(drush sqlq "SELECT name FROM system WHERE name IN ('$(cat tmp.txt | paste -sd, | sed "s/,/','/")');")

```

which may be more complex, but quicker (especially when you replace `drush sqlq` with `mysql -e` command.

---
Tags: drush
---


# Question
Title: File directory token - image field - node author
How to setup file directory where the images are saved to use tokens based on node author ? I have all setup with current user, but this is not good if moderator or admin needs to make a change with content made by user.

Strange is that for automatic node title i can use node author tokens, but not for image field.

# Answer
> 1 votes
Have a look at this issue that explains why you cannot use node tokens in Views: https://www.drupal.org/node/1788414

> This is a limitation of Drupal core - it does not provide any node context for token replacement aside from the global tokens that are available. You will need a module like http://drupal.org/project/filefield\_paths in order to use node tokens in the file upload directory tokens.

The File (Field) Paths module provides this functionality:

> The File (Field) Paths module extends the default functionality of Drupal's core File module, Image module and many other File upload modules, by adding the ability to use entity based tokens in destination paths and file names.
>
> In simple terms, File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

That should allow you to use the `node:author` token.

---
Tags: 7, files, tokens
---


title: Bootstrap level error

text:
# Question
Title: Bootstrap level error
When I attempt to use Drush 8.0.3 on a clean Drupal 8.1.1 install, I receive the following error:

> Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

This is on a Digital Ocean server running Ubuntu and nginx.

Drush status:

```
root@*********:/var/www/html/drupal/sites/default# drush status
Drupal version         :  8.1.1
Site URI               :  http://default
Database driver        :  mysql
Database hostname      :  localhost
Database port          :
Database username      :  drupal
Database name          :  drupal
PHP configuration      :  /etc/php5/cli/php.ini
PHP OS                 :  Linux
Drush script           :  /usr/local/bin/drush
Drush version          :  8.0.3
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :
Drupal root            :  /var/www/html/drupal
Drupal Settings File   :  sites/default/settings.php
Site path              :  sites/default
Sync config path       :  sites/default/files/config_JYMyTTYRsOD-Wxu0fI7lfugHI6rk2DbhO5g-jrfjsPyy46mmesB1aTpSuq2RAUIOUC4N2q_IkQ/sync

```

Oddly (to me, at least) I can clear caches:

```
root@***************:/var/www/html/drupal/sites/default# drush cr
Cache rebuild complete.

```

# Answer
I don't know if this always is needed, but I recommended keeping Drush in sync with Drupal - the same version or newer. The current (stable) version of Drush is 8.1.2.
> 0 votes

---
Tags: 8, drush
---


title: How to upload .tif image file?

text:
# Question
Title: How to upload .tif image file?
I want to upload image(.tif extension) to drupal website, but as per current we can upload only jpg/jpeg/png/gif only.

# Answer
> 4 votes
According to Display TIFF image in all web browser unless you're on Safari, you will not be able to render the `.tif` image on your site.

Therefore, this more like a file rather than an image. If you want to upload it, for your field type use file instead of image.

If you plan to display/render the `.tif` image, you will have to convert it to a known image file: `.png, .jpeg, .gif`, etc..

---

**Edit:**

> Do we have any drupal module that can convert .tif to other image extension? – Govind

According to Henk's comment in Upload tif using image API there is a way:

> I was looking for a similar solution and found a working solution in Drupal 7 to upload, scale and display tiff images.
>
> Install ImageMagick module and its dependencies **with ImageMagick tif support on the server**
>
> Install Media module
>
> Use the media module as the widget type for your image type field because the regular image widget type does not support TIFF's, with that you should be able to upload tiff images in Drupal
>
> And i forgot...add the "change file format to : png" for your image style because only Safari is capable of displaying tiff's directly

---
Tags: 7, media
---


# Question
Title: Hide the option of Payment method "No Payment Required" based on user role
I used module "No payment required" for giving extra payment method as per my client requirement.

I created a site with two user roles: 1. Merchant, 2. Customer.

Option "No payment required" should only display to users with "Customer" role, which is given permission by Merchant. I have searched in google but there is no luck.

# Answer
> 1 votes
In Drupal Commerce each payment method is essentially a rule. So just like with any rule, you'll need to add your required condition to that payment method rule.

Find Payment Method Configuration page - `admin/commerce/config/payment-methods`.

You'll see payment method **"No Payment Required (Payment)"** in the list of **"Enabled payment method rules"** (if it is enabled). If not enabled - enable that payment method.

Then click **Edit** next to that rule, and add condition "**User has roles**". Select the role "**Customer**", **save**, test and you're done.

---
Tags: commerce
---


# Question
Title: Cancel if condition not met, show status
I have the Mimemail module set up to send HTML mails out, after a form is filled in an email is sent to the user based on a custom template.

But the email should only be sent out if the user has previously filled in another form, if they haven't a message needs to be displayed and the email cancelled.

I'm simply using the following code to check that they have filled in the other form previously:

```
$query_result = db_query("SELECT MAX(sid) as max_id FROM webform_submitted_data WHERE data = '" . $email . "' AND nid = ###" )->fetchCol();

```

So if this returns an empty array then a message needs to be displayed and the email cancelled, but I can't seem to stop the email being sent, how do I do this?

# Answer
You can use `hook_mail_alter()` for that, e.g.

```
function MYMODULE_mail_alter(&$message) {
  if ($message['id'] == 'MYMODULE_foo' && any_other_condition()) {
    $message['send'] = FALSE;
  }
}

```
> 1 votes

---
Tags: 7, emails
---


# Question
Title: What are folders within sites/default/files for?
There is a quite similar question in What are all the directories for in the new Drupal 8 structure? about the Drupal directory structure, but it is not explained the content of the sites/default/files directory.

Within such directory there are all these folders:

* 2016-01/
* 2016-02/
* ...
* config\_nEjJjnck1\_CMDKmCKDLS9cd-CKD89cdsCD78cdsCNJD89/
* css/
* inline-images/
* js/
* languages/
* php/
* styles/
* translations/

First two folders contains user-uploaded content. What are other folders for and how/when their content is generated? Which of these folders should be included inside a Git repository?

# Answer
> 4 votes
They're created by different parts of the system, when they're required, for pretty much anything at all that a module needs to store file-wise.

It would be pointless to try to list them all, as core/contrib/custom modules can place files/folders there arbitrarily; Drupal doesn't place any restrictions on what can/can't be stored there, it's up to each bit of code as to how and when it uses that folder to read/write.

---
Tags: 8, files
---


# Question
Title: How to override title for exposed filter views under cache?
I want to override the title for Exposed Filter views.

I tried to use `hook_views_pre_view` `hook_views_pre_render` and `hook_views_post_render` and more. This doesn't help me because my views is under cache(if I clear cache then it works, but I have to do each and every time).

Is there any option to set title for cached views? I want searched field as page title.

# Answer
> 0 votes
> Is there any option to set title for cached views. I want searched field as page title.

Yes, you could use jQuery to grab the search field text and then change the title on page load. Probably, you will need to use cookies.

---
Tags: 7, views
---


title: background-image and sites.php

text:
# Question
Title: background-image and sites.php
I have a multisite configuration with Drupal7, my prod site is `mysite.example.mydomain.com` and dev is `mysitedev.example.mydomain.com` I have set in `sites/sites.php` :

`$sites = array('mysite.example.mydomain.com' => 'mysitedev.example.mydomain.com',
);` so searching for `sites/mysite.example.mydomain.com` would result as `sites/mysite.dev`. example `mydomain.com`, but I have a background Image Url:

`background: url("/sites/mysite.example.mydomain.com/files/myimage.jpg");`

if the Url is `/sites/mysitedev.example.mydomain.com/files` it works, otherwise with `/sites/mysite.example.mydomain.com/files` it don't! What am I missing???

Thanks.

# Answer
> 2 votes
It sounds like you're confusing hostnames with file system paths.

The array mapping in sites.php is:

```
Hostname => Instance Folder

```

So taking your example, requests for http://mysite.example.mydomain.com will use the folder /sites/mysitedev.example.mydomain.com.

In that scenario, the path /sites/mysite.example.mydomain.com/files doesn't exist, so requests for files under it will return a 404. That's to be expected.

You can always add an alias/redirect via your server config, but it might be best to just use the system as it was intended.

---
Tags: files, multi-sites
---


# Question
Title: Issue while modifying and importing the manually content type data
I have a scenario like this:

I am using Feeds Importer to import one content type data. I am using GUID field as the unique field. Also, I am exporting these all the nodes of this content type using Views into a .csv file.

My problem is that users can create nodes using the Feeds Importer and also manually in the Drupal admin console.

While I export the nodes of the content type, it contains all nodes (manually created nodes and Feeds imported nodes). There will be no GUID for the manually created nodes.

In this case, how can I resolve the issue of re-import of this data into the Drupal tool?

Is there a way to update the GUID field in the database whenever a new node of this type is created? This will resolve the issue.

# Answer
Install Universally Unique IDentifier and use it as GUID.it is not required you create GUID field in most of time `Nid` is good choice as GUID mapper.

**Universally Unique IDentifier** Description :

> This module provides an API for adding universally unique identifiers (UUID) to Drupal objects, most notably entities. Features in Drupal 7 version Automatic UUID generation
>
> UUIDs will be generated for all core entities. An API is provided for other modules to enable support for custom entities. UUID API for entities, properties and fields
>
> With this unified API you can load entities with entity\_uuid\_load() so that all supported properties and fields are made with UUID references. You can also save entities formatted this way with entity\_uuid\_save() (depends on Entity API). Export entities to use as default/demo content
>
> The integration with Features module provides the ability to export UUID enabled entities with intact dependencies and references to other entities. This functionality depends on Deploy module 7.x-2.0-alpha1 (soon to be released) and is probably the most robust way for installation profiles and distributions to provide demo content!
> 0 votes

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: Different "Asc" and "Desc" labels for different Views exposed sort fields
I have a view of Commerce products that, as is standard for e-commerce product listings, can be sorted by price or by date. I'm having trouble with the sort direction labels:

* In the context of dates, "Ascending" or "Descending" is confusing unless you are used to thinking about time in terms of UNIX timestamps. Labels like "Newest" and "Oldest" are much more user-friendly to average users.
* In the context of prices, labels like "Highest" and "Lowest" are most user-friendly.

"Newest"/"Oldest" is clearly nonsense in the context of price, while both "Ascending/Descending" and "Highest"/"Lowest" are confusing to average users in the context of dates. I need both highest and lowest options for the prices sort because it's a luxury goods store and some users want to browse the most premium options.

The trouble is, even with Better Exposed Filters module, I can only have one custom ascending or descending label.

Ideally, I'd like something like this:

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

...but I'd also accept something that switches the labels in the sort order based on the selection in sort type.

I could roll my own javascript, but surely I can't be the first person to have this use case. Is there an existing solution?

# Answer
> 2 votes
There's a feature for this in using the Better Exposed Filters module through certain combinations of BEF settings:

* Set "Display exposed sort options as" to anything except Toggle links, which seems to give strange results
* Under "Advanced sort options", tick "Combine sort order with sort by"
* Save, and see what strings it outputs by default for the labels. For example:

> + Price Highest
>     + Price Lowest
>     + Date listed Highest
>     + Date listed Lowest

+ Copy these into the "Rewrite the text displayed" field, then for each one put a `|` then the intended label, for example:

.

```
Price Highest|Price - Highest
Price Lowest|Price - Lowest
Date listed Highest|Date - Newest
Date listed Lowest|Date - Oldest

```

It then outputs as intended

> * Price - Highest
> * Price - Lowest
> * Date - Newest
> * Date - Oldest

---
Tags: 7, commerce, views
---