# Question
Title: How to display language switcher block as buttons, instead of simple links?
the language switch block looks like this:

I would like to display it as bootstrap buttons or whatever else is possible. At least not in plain links.

```
<button type="button" class="btn btn-primary">Primary</button>

```

Now in my D8 core, I found the PHP file for the language switcher, but I don't see where i can put my HTML code.

```
/**
 * Provides a 'Language switcher' block.
 *
 * @Block(
 *   id = "language_block",
 *   admin_label = @Translation("Language switcher"),
 *   category = @Translation("System"),
 *   deriver = "Drupal\language\Plugin\Derivative\LanguageBlock"
 * )
 */
class LanguageBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The path matcher.
   *
   * @var \Drupal\Core\Path\PathMatcherInterface
   */
  protected $pathMatcher;

  /**
   * Constructs an LanguageBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
   *   The path matcher.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LanguageManagerInterface $language_manager, PathMatcherInterface $path_matcher) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->languageManager = $language_manager;
    $this->pathMatcher = $path_matcher;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('language_manager'),
      $container->get('path.matcher')
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    $access = $this->languageManager->isMultilingual() ? AccessResult::allowed() : AccessResult::forbidden();
    return $access->addCacheTags(['config:configurable_language_list']);
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = array();
    $route_name = $this->pathMatcher->isFrontPage() ? '<front>' : '<current>';
    $type = $this->getDerivativeId();
    $links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));

    if (isset($links->links)) {
      $build = array(
        '#theme' => 'links__language_block',
        '#links' => $links->links,
        '#attributes' => array(
          'class' => array(
            "language-switcher-{$links->method_id}",
          ),
        ),
        '#set_active_class' => TRUE,
      );
    }
    return $build;
  }

  /**
   * {@inheritdoc}
   *
   * @todo Make cacheable in https://www.drupal.org/node/2232375.
   */
  public function getCacheMaxAge() {
    return 0;
  }

}

```

# Answer
Ok I found now what helped me. Two modules do this:

1. Language Switcher Dropdown \+ Language icon (the flags don't get displayed on D8 yet)

2. Dropdown language Module
> 1 votes

# Answer
***First choice***
If you wants some design related change you can easily achieve using **CSS**.

***Second choice***
Enable `twig.config: debug: true`

See some template file where you can made changes.

> FILE NAME SUGGESTIONS:
> links--language-block.html.twig
> links--language-block.html.twig
> links.html.twig

Changing markup of the language switcher

***Trird choice***
Alter `_language_switch_links_alter`. How do I alter a language item link?
> 3 votes

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


# Question
Title: Is there any way to "linux nice" a process to have less priority
We have some high resource views that would have less impact on the overall performance if they ran at a low priority, e.g. linux nice'd to a low priority.

# Answer
Well...

This is rather complicated to solve and probably not suitable for all available configurations. Given you don't reuse processes and the given php process terminates at the end of the request you can use proc\_nice().

Next thing will be to be at the right spot to nice the process, does the heavy loading occur before executing? while executing? Also nicing the php process probably won't take any load of the mysql server or whatever other backend this process is requesting.

Looking at view::execute there's no way to distinguish at this point between cached views and uncached ones - so going that route we also have to nice processes which have a cache - probably something to think about.

Drupal 7 Implementation using hook\_views\_pre\_execute().

```
/**
 * Implements hook_views_pre_execute().
 */
function mymodule_views_pre_execute(&$view)) {
  if($view->name=="machine_name_of_my_view") {
    // http://php.net/manual/en/function.proc-nice.php
    // Setting something higher would lead to idle only processing.
    // Please refer to the documentation of proc_nice and nice.
    proc_nice(9);
  }
}

```

Drupal 8 implementation using hook\_views\_pre\_execute():

```
/**
 * Implements hook_views_pre_execute().
 */
function views_pre_execute(ViewExecutable $view) {
  if ($view->id() == 'machine_name_of_my_view') {
    // http://php.net/manual/en/function.proc-nice.php
    // Setting something higher would lead to idle only processing.
    // Please refer to the documentation of proc_nice and nice.
    proc_nice(9);
  }
}

```

Keep in mind that this solution requires quiet some constraints to work for you:

* Heay load is actually in the php layer
* proc\_nice() is available (not all environments allow this)
* dedicated php processes which terminates at the end
> 0 votes

---
Tags: views, performance
---


# Question
Title: Removing the comma between Attribute Option and Attribute Price in Ubercart for Drupal 7
Discovering Product Attributes in Ubercart was quite a find. However, my client does not like the way the dropdown looks. Previously, all the prices had + in front of them, but I was able to remove them taking a clue from questions by other Drupal users (sites/modules/ubercart/uc\_attribute/uc\_attribute.module line 1361). But, finding where to get rid of the comma eludes me.

If you have any further clues, I would be most appreciative!

# Answer
`theme_uc_attribute_option($option, $price)` is what you're looking for. Override that theme function in your theme and you can eliminate the "," & the price adjustment amount.
> 1 votes

# Answer
For Drupal 7, Ubercart 3...

Go to: admin/store/settings/products \> Attribute settings

Tick "Display total price" and save.
> 1 votes

# Answer
Add span and Class in the file uc\_attribute.theme.inc under function theme\_uc\_attribute\_option like shown below..and apply your class or style to it $output .= ' ' . $variables\['price'\].'';
> 0 votes

---
Tags: ubercart
---


title: How do I find the search block form ID?

text:
# Question
Title: How do I find the search block form ID?
I added some search block in my theme, and I placed each of them in a custom place.
I want to edit each of theme by using function hook\_form\_FORM\_ID\_alter for this purpose.

> Provide a form-specific alteration instead of the global hook\_form\_alter().
>
> Modules can implement hook\_form\_FORM\_ID\_alter() to modify a specific form, rather than implementing hook\_form\_alter() and checking the form ID, or using long switch statements to alter multiple forms.

How can I find each search block form ID? How can I edit them in `ThemeName_form_search_block_form_alter()` to add special classes to each of them?

I used the Devel module for this purpose, but It seems that for the Devel module, all those forms have the same ID (search\_block\_form).

This is the code I used.

```
function ThemeName_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message(kint($form));
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#attributes']['class'][] = 'my-class';
}

```

# Answer
The first thing to do is extend SearchBlockForm so you can give it a custom ID. Put code in `mymodule/src/Form/MymoduleSearchBlockForm.php`

```
namespace Drupal\mymodule\Form;

use Drupal\search\Form\SearchBlockForm;

class MymoduleSearchBlockForm extends SearchBlockForm
{
  protected $formIdentifier;

  public function setFormIdentifier($formIdentifier)
  {
      $this->formIdentifier = $formIdentifier;
  }

  public function getFormId()
  {
    $form_id = 'search_block_form';
    if($this->formIdentifier)
    {
        $form_id .= '-' . $this->formIdentifier;
    }
    return $form_id;
  }
}

```

Then you can call your form like this:

```
$form = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\mymodule\Form\Mymodule\SearchBlockForm');
$form->setFormIdentifier('some_custom_value');

return \Drupal::formBuilder()->getForm($form);

```

The key line of code here is this one:

```
$form->setFormIdentifier('some_custom_value');

```

If you pass a different value each time you generate the form, each form will get a different form ID. The form ID will be:

```
search_block_form-some_custom_value

```

Which will then be available in hook\_form\_alter with a $form\_id of `search_block_form-some_custom_value`
> 4 votes

---
Tags: theming, forms, blocks, search
---


# Question
Title: How would one upload a list of users via a .csv file and have them blocked by default?
The user import modules exists for Drupal 7, but how would one import a list of user from a csv file into Drupal 8? And once they are imported, have them blocked by default.

Now when the users come to the site to register, they can only register with one of those imported accounts on the csv. So that means you cannot create a new account, but only unblock an existing account in the system. How would one accomplish this setup?

# Answer
> 2 votes
I suggest setting up a Migration using Migrate CSV. When Feeds is ready, it should be possible, but it looks incomplete at the time of posting.

Using the migrate code that you implement, set the accounts as blocked by calling `$user->block()` per User import.

Block any anonymous user registrations, this will make new user additions possible only by admins.

In place of the user reg form, create a new custom form using Webform module or core Contact module. You can replicate the fields from the reg form of use to you there. On form submission, using a custom module including a `hook_form_FORM_ID_alter`, do a check on the submitted form for email address and verify if it matches, then call `$user->activate()` to unblock the user account.

Or if Rules module provides you the necessary settings through the UI, you could try the email address check using that, but this module maybe incomplete for this type of check at present.

---
Tags: users, 8, importing-exporting
---


# Question
Title: How to get addressfield geocoded on import with Feeds?
I am using Drupal 7.10 with the Feeds module 7.x-2.0-alpha4. The data I'm importing has address data that will be imported into my content type's address field, and the content type is also using the field implemented in the Geofield module, which holds coordinates and it is set to be populated from the address field when a node is saved.

However, when I import the data into nodes, the nodes are not geocoded; if I then edit the node, and save it, the node will be geocoded, and my map will display.

How can I get the Feeds module to trigger geocoding upon data import?

I just found an issue about this: Feeds + Addressfield Integration.

**UPDATE**

Found the issue about "Creating Your First Map Using OpenLayers, Geocoder, and Feeds" which references a patch. I tried this patch and re-imported my nodes. However they still were not geocoded.

# Answer
> 1 votes
The way that your Geocoded data will populate after save indicates that there is some hook in the geocoding module that triggers after a save. Perhaps the initial save in feeds bypasses this.

I suggest you find in the Geocode module the point at which this save is triggered, but as a work around for you which should work, trigger another save once feeds has saved your node.

Create a custom module with a `hook_feeds_after_save`, then call `$entity->save()` on it again to issue a re-save and that should force your Geocoded values to populate.

---
Tags: 7, feeds, entities
---


# Question
Title: How do I create a full project from a sandbox project?
We have created a module for Drupal 8 on drupal.org, but it is a sandbox project. How do I make it a full project?

# Answer
You need to have your account elevated to be able to promote a project to full status, meaning you have to go through the project application process if you have not already.

https://www.drupal.org/node/1011698
> 1 votes

---
Tags: community-official-site
---


# Question
Title: Disable Drush backend messages by default
I am having a problem with drush backend message, how do I disable "--backend" by default ?

```
command:
$ drush make drupal-org.make drupal

result:
$ drush make drupal-org.make drupal
DRUSH_BACKEND:{"type":"notice","message":"Command dispatch complete","timestamp"
:1364518974.3749,"memory":6182608,"error":null,"packet":"log"}

 DRUSH_BACKEND:{"type":"memory","message":"Peak memory usage was 6.36 MB","times
tamp":1364518974.375,"memory":6183144,"error":null,"packet":"log"}drupal-7.21 do
wnloaded.    [ok]

```

everything is working properly but I do not want to see the "backend json" output on the console.

```
$ drush --version
drush version 5.0-dev

$ git --version
git version 1.8.0.msysgit.0

$ uname -a
MINGW32_NT-6.1 PC 1.0.12(0.46/3/2) 2011-07-20 17:52 i686 Win7

```

# Answer
Uninstall cleanly that version of `drush` as 5.0 is very old now. Uninstall using pear if you installed that way, using Composer, or manually checking `which drush` and remove symlinks, drush folder, backup and then remove `~/.drush`.

Look at the Drush install page to see what drush version you need for Drupal version you are working with. Then install drush using Composer which is the recommended way.

This message should be gone then. Good luck!
> 1 votes

---
Tags: drush
---


# Question
Title: How to mass copy the title of each node to a taxonomy term?
I need to copy the title of nodes to its taxonomy term. I have the following content type

* Title - text
* Body - text
* Taxonomy term - (currently empty)

I want to copy the "Title" ---\> "Taxonomy term" for each node.
How can I do this?

I understand that VBO with som php-snippet could solve this but I am no programmer. Any suggestions about a working snippet or other solution?

# Answer
> 1 votes
You could use a combination of the Rules module and the VBO module to create a custom rule component, which you then use as a custom VBO action.

For way more details on this combination, have a look at my answer to "How to bulk update select list fields?".

In your case, the custom Rules Component should look pretty similar to this:

```
{ "rules_set_an_initial_value_for_a_term_field" : {
    "LABEL" : "Set an initial value for a term field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_yourfield" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-yourfield" ], "value" : "HereGoesTheTitle" } }
    ]
  }
}

```

Some more details to further explain the above example:

* adapt the machinename of `field_yourfield` to the machine name for your taxonomy term field.
* replace the (hardcoded) `HereGoesTheTitle` value in the Rules Action by the token like `node:title` (which for sure wil be available).
* I'm assuming your taxonomy term is a single value field, if it is a multi value field, then replace the action with a similar one to "Add an item to a list" (related to your multi value field).

PS: no need at all for any custom PHP code when using this approach.

---
Tags: 7, taxonomy-terms, views, external-scripts
---


title: Get notification message in groups

text:
# Question
Title: Get notification message in groups
I created groups using Group module.

One group is a job poster(Group-A) and the other is a business owner(Group-B).

Group-B business is all about plumbing.

When Group-A posted a job about plumbing, Group-B should be able to get notified about the post as this is related to his business.

So, I use message stack as a method, but I still didn't get in the right way.

There is a message\_notify module example that displays details in a page about a certain actions.

So what I need is that a group should get a notification message whenever a related job post is created.

Thanks!

# Answer
What you need is to use the Message Subscribe module, also in the Message Stack. This will allow you to subscribe users to a particular entity, e.g. - your job post.

You need to be able to link your "plumbing" (taxonomy tag, or direct entity ref) to Plumbing Group. You need to use Rules if the functionality exists, or a custom module to hook into the submission of a new job posting with the reference or tag to pointing to plumbing group. If this tag exists, then subscribe all users in the Plumbing group to that new job posting and issue a notification using Message Notify.
> 0 votes

---
Tags: group
---


# Question
Title: How to message or invite a group without joining it?
I'm using the Group module. I created a group(Job Post) with linked content types (Job details).

Scenario: As a user, I created several jobs.

1. I want to be able to invite/message another group (Business) for them to be aware of my posting without joining this group.
2. Also, because I have more than one active jobs, I want to select a job to send the invite about.
3. Lastly, if I have already did an invitation to that group, I can no longer send twice.

Question: How can I achieve these three items above?

**Note**: a User is someone who creates or posts a job (example: electric power shortage). Businesses are created groups, like electricians. The user should invite this business to get notified about his job.

# Answer
As answered in Get notification message in groups, you use Message Subscribe based on your criteria.

You expose the Message Notify for users, but only difference is here you use a custom module to conditionally display that notification form. If the user has already issued a notification, don't display the form. You should be able to search back through the message log to check if the user has previously notified about this message. Be careful you are not clearing out your message log too often in this case.

If you need to clear out your message log, then you may need to use Flag module to flag that the user has already notified about this job post. i.e. - mark the message / job post as flagged whenever a notification has been sent. Only display the Message Notify form for non flagged entities.
> 0 votes

---
Tags: 8, group
---


# Question
Title: How to retrieve a term tree for a specific vocabulary given the machine name?
Retrieving a term tree for a specific vocabulary in Drupal 8 requires the vocabulary ID. I can find no function/method/service that will return the vocabulary entity given the machine name, in order to get the vocabulary ID.

How do I get a vocabulary ID from its machine name?

# Answer
*vid* is the vocabulary machine name, in Drupal 8. You just need to pass the the string you have to `TermStorage::loadTree()`, without changing it.

```
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree("myname");

```
> 12 votes

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


title: How to setup sitewide keyword search?

text:
# Question
Title: How to setup sitewide keyword search?
I am nearly finished with my website on **Drupal 8**, and one last thing I have to do is optimize the search function. At this moment the search function only searches for node titles.

What I want to achieve is that the visitor can search by words and that the node will be shown as the search result. **My website only has 7 seven pages at the moment, and will never grow beyond 10+ pages.**

Example : I have a page about motorbikes( lets call the page motorbikes), in this page are some text blocks with motorbike brands like : yamaha and harley davidson and kawasaki. Now if the user is on the homepage and searches for kawasaki it should return the page motorbikes.

At this point the user would have to search for the page name, which in this case is motorbikes, to find the page.

So in short: I want to have a search function that searches the whole site for 1 or multiple words and then displays the page in which the words are found.

Can you guys help me on how to approach this problem, I don't need any code, just a little bit of guidance. Thanks in advance for any help !

# Answer
You will need Search API and Search API Database for this - though I suggest setting up Apache Solr + Search API Solr instead of Search API Database.

and/or also:

Search API provides a lot more flexibility in terms of the types of search you want to configure and setup. Some functionality within say, Solr, allows for defining synonyms and abbreviations, as well as open you up to having facet based searches.
> 0 votes

---
Tags: 8, search
---


title: Alter module js for on custom page

text:
# Question
Title: Alter module js for on custom page
I have a small problem with altering js code loaded from custom module. I need to change the js script from a module for a custom page

Module code code :

```
function module_script_src($environment) {
  $script = '';
  $script_id = variable_get('script_id', '');
  $script_hash = variable_get('script_hash', '');
  switch ($environment) {
    case 'prod':
      if ($script_id && $script_hash) {
        $script = '//example.com/' . $script_id . '/lib-' . $script_hash . '.js';
      }
      break;

    case 'dev':
      if ($adobe_dtm && $site_hash) {
        $script = '//example.com/' . $script_id . '/lib-dev' . $script_hash . '.js';
      }
      break;

  }
  return $script;
}

```

The goal is to change $script just for one custom page, i try to add case for my custom page, simply new case to module

```
 case 'custom page':
       if ($node && $node->nid = "my_node_id"):
     $script = '//example.com/' . $script_id . '/custom-' . $script_hash . '-.js';
  }
      break;

```

But it does not work, if it possible in module to load custom is for the specific custom page?

# Answer
In the switch statement you provide, you are switching over `$environment` variable. It sounds like it will never be passed a URL or 'custom page' value.

You are also trying to use `$node` object but you have not loaded it from your code. You are also not passing `$node` as an argument. Also an `$adobe_dtm` variable is used but never defined. Plus, you are using `=` to do an equality check, you need `==` or `===`. `=` is assigning 'my\_node\_id' to your variable instead of compare it.

In order to have a `$node` object present in this function, you need to do one of two things to get it:

* `$node = menu_get_object('node');`
* `$node = node_load(arg(1));`

Then you can just add this after the switch statement:

```
function module_script_src($environment) {
  $script = '';
  $script_id = variable_get('script_id', '');
  $script_hash = variable_get('script_hash', '');

  switch ($environment) {
    case 'prod':
      if ($script_id && $script_hash) {
        $script = '//example.com/' . $script_id . '/lib-' . $script_hash . '.js';
      }
      break;

    case 'dev':
      if ($adobe_dtm && $site_hash) {
        $script = '//example.com/' . $script_id . '/lib-dev' . $script_hash . '.js';
      }
      break;

  }

  if ($node = menu_get_object('node')) {
    if ($node->nid == "my_node_id"):
      $script = '//example.com/' . $script_id . '/custom-' . $script_hash . '-.js';
    }
  }

  return $script;
}

```

You may need to think through the cases involved in building the script value. It looks like the switch statement is not even necessary, because `$script` value is basically the same - in which case you can clean up the code by simplifying it.
> 2 votes

---
Tags: 7, javascript, hooks
---


# Question
Title: How do I get all the referenced taxonomy terms without the field name?
I have been looking into entityQuery but haven't seen what I am trying to do yet.

If I have a node object, is it possible to get all taxonomy terms referenced by the node object, regardless of the field they are in?

Most of what I have seen would be getting the terms from a specific field, but I won't have access to the field name. I just need to find all terms in a specific vocabulary that are referenced by the node. Thanks!

# Answer
> 1 votes
You can iterate through all the fields on the node and add conditions to check that the field is an entity reference field, and that the target type is `taxonomy_term`:

```
// Iterate through each field on the node entity to get all the tagged
// taxonomy terms on the node.
foreach ($entity->getFields() as $field) {
  // Only look for fields that are entity reference fields.
  if ($field instanceof EntityReferenceFieldItemList) {
    // Get the field settings.
    $field_definition = $field->getFieldDefinition();
    $target_type = $field_definition->getSetting('target_type');
    // Check that the field targets are taxonomy terms.
    if ($target_type == 'taxonomy_term') {

      // Do stuff..

    }
  }
}

```

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


# Question
Title: How add custom node in a View (Nested View)?
Currently I have simple view that is used on the main page. In includes nodes of custom type. That's great. But now I need to do something different.

Consider I have following structure:

-----View-----
-------Node 1--------
-------Node 2--------
-------Node 3--------
-------Node 4--------
-----End View-----

But I want to have the structure like that:

-----View-----
-------Node 1--------
-------Node 2--------
-------Node 3--------
---------View Nested in the node ---------
------------Nested Node 1-------------
------------Nested Node 2-------------
---------End Nested View ---------
-------Node 4--------
-----End View-----

So I need nest another view in a top level node.

How can I implement this?

Is there any way to do this using core functionality? Otherwise I need to change the content of a node before data is passed to a template, but I don't which hook to use?

Please suggest how to deal with this task.

# Answer
> 2 votes
You can use the Views Field View to show the Nested Nodes (that should be a kind of Node Reference)

> There are a lot of cases in views where you want to embed a list inside each row. One example could be, you have a list of groups, and for each groups you want to list the first and last name of all of their members.

For modify the content of a node you can use the template\_preprocess\_node() maybe you will need to Check content type of node in preprocess hook.

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


# Question
Title: Programing date custom field into content type
I'm building a module that creates a content type when it installs. I already have my content type, let's call it MyContentType and I have a field body that I created based on Drupal documentation (https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type) and I could create the two additional fields but I can't find a way to add a field of type date, datetime or timestamp. I tried to replace 'type: text\_default' to 'type: datetime' but when I did it all my fields disappeared! I know I should also have a file named field.field.node.mycontenttype.field\_date.yml with the correct configuration but what is the way to tell drupal that the type is datetime ? And how can I set it to current time?

# field.storage.node.field\_date.yml

```
langcode: en
status: true
dependencies:
  module:
    - node
    - text
id: node.field_date
field_name: field_date
entity_type: node
type: datetime
settings: {  }
module: datetime
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

```

# field.field.node.mycontenttype.field\_brand\_information.yml

```
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_date
    - node.type.mycontenttype
  module:
    - text
id: node.mycontenttype.field_date
field_name: field_date
entity_type: node
bundle: mycontenttype
label: 'Date'
description: 'Date'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  display_summary: false
field_type: datetime

```

And then I referenced it like:

# core.entity\_form\_display.node.mycontenttype.default.yml

```
langcode: en
status: true
dependencies:
  config:
    - field.field.node.mycontenttype.field_date
    - node.type.mycontenttype
  module:
    - file
    - path
    - text
_core:
  default_config_hash: qZE-qJ04DTTNggVVQdVOPQmpE_I69GQ_LqB32kXivVg
id: node.mycontenttype.default
targetEntityType: node
bundle: mycontenttype
mode: default
content:
  created:
    type: datetime_timestamp
    weight: 2
    settings: {  }
    third_party_settings: {  }
    (...)

```

and

# core.entity\_view\_display.node.mycontenttype.default.yml

```
langcode: en
status: true
dependencies:
  config:
    - field.field.node.mycontenttype.field_date
    - node.type.mycontenttype
  module:
    - file
    - text
    - user
_core:
  default_config_hash: Nfnv6VMugBKl6EOqi_U0I_LQ1ZQpbNDN3a9GXHWUBz4
id: node.mycontenttype.default
targetEntityType: node
bundle: mycontenttype
mode: default
content:
  field_date:
    weight: 101
    label: above
    settings: {  }
    third_party_settings: {  }
    type: datetime

```

Thank you.

# Answer
> 0 votes
Like 4k4 suggested, I used https://www.drupal.org/docs/8/api/entity-api/using-the-ui-to-export-the-code-for-your-custom-fields to create and export all my needed fields and it worked really well.

Note: With a lot of changes you may need to delete config for the already created settings. Remove it with: `drush config-delete field.storage.node.field_name` Found that here

---
Tags: 8, entities, datetime
---


title: How to identify and copy a pane?

text:
# Question
Title: How to identify and copy a pane?
I have a site that is developed with panes. There are "Contact Us" forms at the bottom with bad links. Some pages share the same pane, some have different panes.

My task is to standardize all the pages so that they use the same pane, so that fixing a link in one will fix the link in all of them.

What I see as the title is `Contact Us (id: 1740)`. That's the title of the pane that is shared among certain pages. On other pages, it's `Contact Us (id: 1738)`, with different ids for different pages.

What I would like to do is copy the pane entitled `Contact Us (id:1740)` to all the pages that have the Contact Us section. However, I am not sure how to copy it from one page to another.

When I click on the gear icon of the page and choose `Edit`, I can edit the values, but I don't see what type it is. I've looked at node of nid 1740-- it's not that node. Also, I don't see that title in the list of re-useable panel panes.

How can I copy this panel pane to other pages where it doesn't already exist?

# Answer
It turns out my pane was a fieldable panel pane. As far as I can tell, these panes serve as templates, and when placed in panels, they are copied into one-off panes.

So my solution was to add another copy of the fieldable panel pane, this time making sure to check the 'reusable' box. Then, I replaced all the one-off panes throughout the site with the reuseable pane.
> 0 votes

---
Tags: panels
---


# Question
Title: How to convert an image field to an entity reference field
We have Drupal Paragraphs using image fields that are media entities. When the media entity is updated with a new image the old images still show unless we manually edit each page, remove the image from the paragraph, and add it back. We have tested using entity reference fields that reference those same media entities and they update. How can we programatically convert the image field to an entity reference field or copy over the references from that field to the media entity field?

# Answer
> 0 votes
In a mile high explanation:

* add entity reference field to content type.
* you can use rules, or a php-script to load all the nodes for your content type.
* loop through each node, get the field value `fid` of the image paragraph field, assign it to the entity reference field.
* save the node

After all the above is done, remove/delete the paragraph bundle.

---
Tags: 8, media, paragraphs
---


title: Resubmit all nodes

text:
# Question
Title: Resubmit all nodes
I would like to save all nodes, because I created a validation function picking data from Google Analytics.

This doesn't work:

```
$node = Node::load(nid);
$node->save();

```

# Answer
> 0 votes
A naive solution to your problem is to load all the nodes and save them one by one.

```
foreach (\Drupal\node\Entity\Node::loadMultiple() as $node) {
  $node->save();
}

```

The above code will resave all the nodes but is not efficient and can result in a 50x error due to not enough available memory.

To do this in a more efficient way, you should only load batches of nodes.

And if you have a limit on your run time then you should use the drupal batch-api.

---
Tags: 8, nodes
---


title: Opening hours - Days and times

text:
# Question
Title: Opening hours - Days and times
I have created a content type - Shops in College

I would like to display opening days and times. Something like this:

Monday - 09:00-18:00

Tuesday - 09:00-18:00

Wednesday - 09:00-18:00

Thursday - 09:00-18:00

Friday - 09.00-13:00

Saturday - Closed

Sunday - Closed

Is there any way I can do this by managing the fields? Or how would I go about this?

Thanks

# Answer
There is a module for Drupal 7 for this called Opening Hours and for 8.x there is Office Hours.
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: Hook fires before current_user service can identify current user
I want to make a menu link disappear when a user doesn't have permission to use it. I tried this code:

```
function some_module_menu_links_discovered_alter(&$links) {
  $user = \Drupal::currentUser();

  file_put_contents(DRUPAL_ROOT . '/logs/permission.txt', var_export($user->hasPermission('access some module config'), true));
  file_put_contents(DRUPAL_ROOT . '/logs/roles.txt', var_export($user->getRoles(), true));
  file_put_contents(DRUPAL_ROOT . '/logs/id.txt', var_export($user->id(), true));

  if (\Drupal::moduleHandler()->moduleExists('some_module')) {
    if (!$user->hasPermission('access some module config')) {
      $links['some_module.admin']['parent'] = '';
    }
  }
}

```

And it didn't know that the logged in user existed. I was logged in as an administrator, and it thought I was anonymous. I tried the same code in another hook, and it worked. So, I'm curious:

1. Why does this hook load before currentUser knows I'm logged in?
2. And, are there other hooks like this?
3. Should I try to figure out the current user through another more low-level method?
4. Or, is there another way to make a menu link disappear when a user doesn't have permission to view it?

EDIT: Providing code to show what I've done. The menu link **is not disappearing** when users don't have access to the route it links to.

```
some_module.settings:
  path: '/admin/config/system/some_path'
  defaults:
    _form: '\Drupal\some_module\Form\SomeModuleForm'
    _title: 'Some title...'
  requirements:
    _permission: 'access some module config'

```

The users **do not have** the `access some module config` permission, yet the menu link is showing up for them. When they click on it, they get an access denied page.

# Answer
**Question in the title: Hook fires before current\_user service can identify current user**

The menu discovery process is not that dynamically, only runs when you clear the cache or make changes that need a rebuild. So the current user while rebuilding the menu has nothing to do with the current user of a request when the menu is displayed.

**I want to make a menu link disappear when a user doesn't have permission to use it.**

About the question behind this, what do you not like about the default behavior? Drupal doesn't show menu items the user has no permission for. If you want to do more adjustments probably the best place is in preprocess.
> 3 votes

---
Tags: 8
---


# Question
Title: How to create a product display view showing all users who purchased a product through a specific display
Im looking to create a view which will have an exposed filter of Product Display Titles in a select list and then display a table of users who purchased a product which originated from that display. The product will be used on multiple displays so this is important to get that filter. Im really struggling to achieve this and so far am getting it to display users for a product but not the display.

It seems the only indicator of the original product display is the display path. I thought I had cracked it but its just not working. If anyone can have a go or walk me through it that would be amazing.

Thanks all

# Answer
Your view needs to have this relationship setup, with multiple relationships added so you can relate your entities in this way.

Product Display \> Product \> Order \> User

I should be able to provide a stronger answer if you can provide a little more detail, but have struggled with a similar view I had to create about 2 years ago and remember it taking a few days for me to resolve :)

Good luck!
> 0 votes

---
Tags: views, commerce
---


title: List of facilities

text:
# Question
Title: List of facilities
I have a basic page called facilities. I would like to list facilities on that page. For example I want to have bank of Ireland and a picture and description then right under that I would like to have Gym and a picture and a description and so on. I would like users to be able to comment on them too.

I tried so many ways but I don't know how to do it. I tried to do it by creating a content type and I can get one to display on the page but then I can't figure out how to display another one right under it on the exact same page.

I also tried doing it with views but it didn't work for me either

Any help be great. thank you

# Answer
Sounds like you need to relate your content models with reference fields. From there you can use Views to create content displays of these references nodes.

Here is a good writeup on it: https://atendesigngroup.com/blog/making-sense-drupal-views-relationships-and-entity-references

For Drupal 7 you will want to grab this module: Entity Reference. Add this new field on the content types you want to add references to, and configure the field. From here, you can either use entity view modes and field formatter displays, or the more popular method is using Views to relate and display referenced entities.
> 1 votes

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


# Question
Title: How can I make an order generated through Services invoke hooks or checkout complete?
I am stuck at integrating a Drupal Commerce store with Services.

I setup a REST server. In several steps I can login, create a user, create user shipping/billing profiles, create an order, add line-items to that order. This works fine, even a correct total gets calculated. I then need a bunch of rules and some hooks to get triggered to make invoicing happen and to send out emails. This fails. I tried to trigger this by changing the order status. Maybe I haven't done it right.

Drupal 7 Modules I use:

* Services
* Commerce Services
* Services Entity

How can I make a D7 Drupal Commerce order generated through Services invoke hooks and rules? To make it simpler: How can I invoke the checkout complete process through services?

# Answer
So, for anyone looking for a solution, here is what I did after asking for help in IRC #drupal-commerce:

Don't use the order status, don't use a checkout-status. Use something (an entity) as a trigger that is necessary for creating the order. I picked the last action provided via .json-file, POSTing a line-item. As soon as this is known by Drupal, all corresponding rules start their work, and some hooks respectively.

Sidenote: I learned something else also and wished to have been pointed to that earlier: Next time I will not use the above mentioned modules again. They're buggy and obsolete in D8 anyway since the concurring RESTws module became part of core.
> 0 votes

---
Tags: 7, commerce, rules, hooks, services
---


# Question
Title: getting rid of Media Module Message "Media Folder: Media Root"
Why is the message "Media Folder - Media Root" appearing on this article, and not on the other articles and pages that also use media to insert images on my site? How can i get rid of it, i don't like it. http://notesmusic.be/node/3

# Answer
> 3 votes
A similar problem came up for me when upgrading a Drupal site to Drupal 7.53. I found that the "media folder" field suddenly started appearing on all images on the site.

What fixed it for me was hiding the media folder field from the file type generated by the file entity module (which makes files fieldable). Here are the steps to do that on your Drupal site:

1. Go to Home » Administration » Structure (admin/structure/file-types).
2. Click "Manage display" for the affected file type.
3. Change the label and format to "hidden" for the "Media folder" field and click save.
4. While you are at it, repeat steps 1 and 2 for all the file types on your site.
5. Clear your caches.

# Answer
> 0 votes
*Media Folder* is a taxonomy field on your your node type that's set to display. If you want to disable its display. Go to the **Manage Display** section for your relevant content type and set it to *Hidden*.

---
Tags: media
---


# Question
Title: How do I show all "songs" that reference an "album" (for example)?
Suppose I have a content type (*Song*) which has a content reference field, referencing an *Album* node to which it belongs. When I view an album, I want to show a list of all songs which reference that album.
Can this be done?

I'd rather not use a taxonomy term. I've looked at the "Manage Display" screen for the *Album* content type, but I could not find any way to display the songs which reference it. I know that I can create a view which filters by album, but I want to display this information directly on the *Album* view screen, so when users click the album link, a list of all songs on that album will show up. Is this possible?

# Answer
Thanks for this comment pointing me to the EVA module. Here are the exact steps I had to take in Drupal 8, which is slightly different than Drupal 7.

# Steps for Drupal 8:

1. Make sure your reference field is already set up (e.g., the *Song* entity has a field referencing an *Album*)
2. Install and activate the EVA module
3. Add a new view (*Manage \> Structure \> Views \> Add View*)
4. Type in the view name, and in *View Settings*, set it to show *Content* of type *Recording* (i.e., the "child" entity). No need to "Create a page" or "Create a block".
5. Under the *Displays* heading will be a label called *Master*. Click the *Add* button just to the right of that.
6. Select "EVA", *not* "Entity Reference" (this is a difference from Drupal 7)
7. Under *Displays \> Format*, I like to change "Unformatted list" to "Table".
8. Under *Display \> Entity Content Settings*, change "Entity type" from "None" to "Content".
9. Change "Bundles" from "All" to "Album" (i.e., the "parent" entity)
10. Under *Advanced*, add a "Contextual filter".
11. Search for the field which links *Recording* to *Album* (i.e., the field in the child entity which references the parent), and select it, and click "Add and configure contextual filters".
12. Under "When the filter value is *not* available", select "Provide default value" and choose "Content ID from URL".
13. click "Apply".
14. If you know the ID of an album (parent entity), you can enter it in the parameter in the "Preview" section to make sure it is working as expected (you will need to pre-populate entities to test this).
15. Click "Save" under the "Display" section for the view.
16. A message should show up: "The view \___ has been saved."
17. Clear all caches (*Manage \> Configuration \> Development \> Performance \> Clear Cache \> Clear All Caches*).
18. Navigate to a sample parent entity, and the child entities should show up on that page.
> 2 votes

# Answer
You can create the views list as you suggested and use the viewsfield module to embed it in your content.
> 0 votes

---
Tags: 8, entities
---


title: Views timestamp not recognized as date?

text:
# Question
Title: Views timestamp not recognized as date?
I have an INT field with a Unix timestamp. When I add this field to a view, I do not get any date formatting options. I just get options for the thousands market (non, comma, etc). How do I get Drupal to recognize that this is a date field?

I am using the Date modules.

# Answer
> 1 votes
`I have an INT field` that's the problem. You need to use a Date field and not an integer field. As INT fields are not meant/designed to hold dates. Drupal cannot know that your INT it's actually a time stamp and not a number.

As per my Q here: Unix timestamp time is not saving to DB, I was never able to figure out how to save unix time to the DB.

So you could stick with the INT field and use jQuery to convert your unix time to what ever time you need. The big downside is that if you will not be able to sort or filter by a certain month or year.

The better solution is to use Date field, but transform your Unix time stamp to some format accepted by the Date field. By using PHP, with hook\_node\_presave or using jQuery.

In conclusion, use a date field.

---
Tags: views, datetime
---


title: Add description for Field Group

text:
# Question
Title: Add description for Field Group
I am using the Field Group module on my user registration form.

Is there any option to add a help text (description) to the whole group, which has 7 input fields?

I want the users to be able to see some description text below the FieldGroup heading.

# Answer
Go to `Content type > Manage fileds > Field Group`.

In the filed group you can find settings icon beside.

Clicking on that will give you a field to add description to.
> 1 votes

# Answer
Some field\_group formatters do have a description setting, others do not.

If you look at field\_group\_field\_group\_formatter\_info(), and look at 'instance\_settings' for each entry, you see which settings are available for each formatter.

From what I tried, after changing the formatter for a field group, the new settings only appear after saving the entire field\_ui form.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Call to undefined function making site unavailable
After making a Backup/Migrate copy of source site files, the very source site for unknown reason broke down with this error:

> Fatal error: Call to undefined function link\_field\_property\_info\_callback() in /sites/all/modules/entity/modules/field.info.inc on line 30

Most probably it comes from references to the Link module. I have googled around, but the solutions good for others are not for me, as I cannot access admin to un-install the module. Is there anything I could do here without Drush?

I really do not quite understand the origin of that situation, but I would more like to focus on resolving the effect.

# Answer
You can try to (re)move the faulty module's directory, at least temporarily. It should prevent the call and let you access the necessary admin pages.
> 3 votes

# Answer
You can try

```
    drush sqlq "DELETE FROM cache_field"

```

In case, you are using memcached use the below

```
    echo 'flush_all' | nc localhost 11211

```

drush command worked for me.
> 0 votes

---
Tags: backups
---


# Question
Title: Does turning off features modules affect what the features modules does?
I have a site that uses the media\_vimeo module and I need to turn it off to install another module, but I can't turn it off as its currently being used by a bunch of feature modules. Would turning off these features modules affect the site or it doesnt matter as these features modules has already imported the needed changes to the site?

# Answer
> 2 votes
FWIW I've successfully uninstalled modules required by a feature before, but I had to remove the dependency from the feature's info file first and then disabled and removed the module. I've seen several Features where the creator unwittingly auto-added all sorts of modules and dependencies to the feature, so just because a module is listed as a dependency doesn't necessarily mean that it is really needed. As this tutorial points out, we should "Build natural dependencies, prevent arbitrary dependencies." and it's so true because as these arbitrary dependencies creep in, a site's features become more difficult to manage.

---
Tags: 7, features
---


# Question
Title: Wrong and ignored language to be translated
My website is by default in French and I need to get an English version.

**Prob n°1** : I've got this kind of Exposed filter (exported in a block), everything in it is translated excepted "Tri" (sort) and "Appliquer" (apply) which stay in french.

Here, you can see all modules about languages/i18n (add i18n, i18n\_block)

In my exposed filter settings (in FR) :

In the view, translate view \> English \> traduire \> and I wrote this

In Config \> Regional \> Translate I found what I wrote correctly

**Answer n°1** : Why my exposed filter labels can't be translated ?

**Answer n°2** : Another thing, it's maybe common but I found this strange, when I write a sentence in `t()` function, it must be in english and not in my site language else I get

Is it normal to write in english in `t()` function even if the site language is not ?

Thanks in advance for helps. I'm listening some tricks, advices and good practice about languages.

# Answer
> 1 votes
First, you need to select source/default language from `admin/config/regional/language`.

After you need to import .po file of English or your selected import other import languages **(https://localize.drupal.org/translate/languages/en)**.

Now you will able to translate your term from `Config > Regional > Translate`. and those are visible according to your language.

---
Tags: i18n-l10n
---


title: Why is my field not displayed?

text:
# Question
Title: Why is my field not displayed?
I got a template for drupal 8 and modifying a content type, when editing a new field, it does not show up.

I'm attaching the images of the structure (fields, form display, display), creation of content and impression.

For more that adds any field I do not manage to make it visualize at the end, in web portal

AND, As in the last page of print (celestial circles) I can not edit that, for more that I have edited in: filds, form display and display. Please where else is it that you can edit these texts in drupal 8?

Can someone help me please

regards

# Answer
> 2 votes
The template most likely does not print content directly only specific fields, you need to add {{ content.field\_name }} to the template, where you want to have it displayed.

---
Tags: views, theming, entities
---


# Question
Title: How to select quarters in a date field not the actual date?
Is there any way that I can select quarters in a date field not the actual date. I want the date field exactly like in the below image.

I have checked for the options in the date field but I didn't find any such option?

Or is there any other module which provides the same functionality?

# Answer
I also could not find a widget that provides this functionality but I would stick to the date field.

You need 2 things:

1. A widget that allows you a selection like that.
2. A custom format for the display of your field's value. The default date format will not help here since PHP does not provide the quarter.

Keep in mind that the storage for the values will be a normal date but you could i. e. interpret "2017-01-01 00:00:00" as "Quarter 1 2017", "2017-04-01 00:00:00" as "Quarter 2 2017", etc.

You can find further information on how to create your widget and formatter here:

* Widget: You can also take a look at the date\_popup sub module of the date module.
* Formatter
> 0 votes

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


# Question
Title: How to remove "Time Zone" element "user_register_form" form using hook_form_alter
I analyzed the "Create new account" page of drupal by using hook\_form\_alter and $form variable. as you see, #form\_id value is: "user\_register\_form" and other elements are as following:

```
attributes->Array
administer_users->Array
#attached->Array
#cache->Array
account->Array
language->Array
#entity_builders->Array
#process->Array
#parents->Array
user_picture->Array
actions->Array
#form_id->user_register_form
#type->form
#action->form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM
#build_id->form-78GnGyO2iwZsooojZLCOiAw9pYXyDqngJ5C0DU_EzUQ
form_build_id->Array
form_id->Array
#id->user-register-form
#method->post
#theme_wrappers->Array
#defaults_loaded->1
#tree->
#validate->Array
#submit->Array
#theme->Array
contact->Array

```

I want to remove "Time Zone" element of this form (user\_register\_form), which of this array elements should I unset to remove that element?

# Answer
> 1 votes
EDITED

As @KrishaWeb and @Kevin said: Drupal 8 provided admin path at: admin/config/regional/settings to do it.

---
Tags: 8, forms
---


# Question
Title: hook_theme_suggestions_HOOK() doesn't work
I am making a template in Drupal 8. At this moment, I made a theme in the /themes directory; there, I have my .theme file and a copy of the html.html.twig file from the core/themes/stable directory.

I have enabled Twig debugging mode and in the Chrome inspect tool I read the following.

```
<!-- FILE NAME SUGGESTIONS:
   * html--front.html.twig
   * html--.html.twig
   x html.html.twig
-->

```

I added the following hook to the theme file.

```
function testTheme_suggestions_html_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'html__testHTML';
}

```

After clearing the cache, there isn't any change to the file name suggestions.

Also I have activated `kint()` in html.html.twig file that is located in my theme root, but `kint()` also shows only these variables.

```
'theme_hook_suggestions' => array(2)
string(6) "html__"
string(11) "html__front"

```

Why doesn't the new suggestions appear?

# Answer
Try it like this:

```
function yourthemename_theme_suggestions_html_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'html__testHTML';
}

```

Replace "yourthemename" with your theme name.
> 3 votes

---
Tags: theming, 8, hooks
---


title: Change contact setting flood limit

text:
# Question
Title: Change contact setting flood limit
I want to change the contact setting flood limit, but I don't find the correct place. How I change the flood limit for sent messages?

# Answer
> 1 votes
There isn't an interface to change this, but you can do it by importing a config file. You need to get a hold of `contact.settings.yml` file. Default looks something like this:

```
default_form: feedback
flood:
  limit: 5
  interval: 3600
user_default_enabled: true

```

You can see the flood limit and interval which you can change and then import the file using the config management system.

# Answer
> 0 votes
With Drush, you can use `drush cedit contact.settings`.

---
Tags: 8, emails
---


title: Features and CMI Together

text:
# Question
Title: Features and CMI Together
We are developing a single Drupal 8 site with a set of different features (content types, etc). The CMI approach is *great* for sharing config through git and importing/exporting on local, dev, stage, and prod environments.

But... I also really like the organizational aspects of the Features module. It is appealing to have config grouped in meaningful buckets rather than a single global sync folder. Individual modules also provide a nice place to hang default content and `hook_update_N` functions.

I've read that these two can play nicely together, but I'm having trouble determining the practical logistics of it all. When I develop a feature, I usually do a `drush cex` and commit the changes -- so with Features, do I also export a feature and commit that? Now the config lives in two places -- should I be concerned? Will it cause conflicts?

Am I just complicating things by trying to use both? If forced to choose, I will use only CMI because I want to be sure to control all config (not just the bits I've grouped into Features) -- and we want consistent and predictable deployments between local, dev, stage, and prod.

# Answer
> 2 votes
In my opinion Features isn't really useful for just *one* site. It is useful for extracting and packaging functionality to use on multiple sites. Using both at the same time is probably counter productive and prone to errors, as they both try to enforce features via configuration and manage them as well.

If you had a site and wanted to copy/clone the article functionality or product catalog functionality from it to another (different) site, then, yes. You would need Features to do this, because core CMI does not work when you want to take pieces and import to a totally different site.

On the other end of the spectrum, you could ignore the core config management and use Features to do this for your entire site, but it is more for you to manage, and as stated, if you are not extracting it out for use in other sites, it is just busy work.

---
Tags: 8, features, configuration
---


# Question
Title: Adding an entity reference field to entity
I'm looking for a way to add an EntityReference field to an Entity, but haven't found an answer to this. Is it possible? Can someone point me in the right direction?

Thank you

# Answer
> 1 votes
You need to go to the admin section for your entity / entity types, and add fields with the Manage Fields tab (just like you would for content types).

---
Tags: 7, entities
---


# Question
Title: Trying to figure out which view to edit!
I have a main page of my site that has views and blocks. There is a photo view which I'm trying to figure out which one it is (drupal 6). I need to edit that view to change the sort order.

However (in admin mode) when I hover the cursor over the block of photos, the "Edit View" comes up and then when I move the cursor a bit upwards to edit it, the link disappears! So it's driving me mad which view to edit.

I have then gone to "site building"/ views / list and then I've changed the sort order of every view that has been named by that title but still the sort order on the main page doesn't change (i want to add sticky sort order).

So can anyone help by letting me know how to catch the edit view link that disappears when I hover the cursor around it? Thanks!

# Answer
> 1 votes
You can perhaps figure out what View it is from the id and class names on the containing markup which should tell you the view and the view display to edit. You can also change the theme to a core theme like Garland to get around whatever CSS issue you're having to get into the edit mode so you can identify the view.

---
Tags: views, 6
---


# Question
Title: Drupal View rewriting output of the field
I created a taxonomy vocabulary with several terms and it is assigned to a content type. So a node can have multiple terms from that vocabulary. After assigning it I have created a view to format the content type nodes into a json data.

Now in the JSON data the taxonomy field is showing multiple values. I want to separate those individual items by comma. Please help me out how to do it. I've tried adding this expression to the tpl file.

`]+>/i', ', ', $output); ?>`

# Answer
> 2 votes
Without seeing your view, it is difficult to solve. But if you edit the taxonomy field in your view, make sure that in the `MULTIPLE FIELD SETTINGS` section the checkbox "Display all values in the same row" is checked. That should display the taxonomy terms as `term 1, term 2, term n`.

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


# Question
Title: Drush: "Unknown engine type outputformat" module conflict
I've been searching in all forums for the answer, I had a problem with drush everything i did showed this message "Unknown engine type outputformat \[error\]"

I updated drush and still got that message since it took me so long to find the answer I'll post it here for other people with the problem its the first answer.

# Answer
The solutions is one of 3 things:

1.- Update drush

2.- Clear drush cache

3.- If you have the module "module\_missing\_message\_fixer" the best solutions is to disable the module make the changes on drush and enable it when you are done, for some reason that module stops drush from working.

I hope this helps someone else.
> 3 votes

---
Tags: drush
---


title: How make node view return without menu?

text:
# Question
Title: How make node view return without menu?
Perhaps the question is simple, but I can not understand how to return the body of a node without a menu. I did a module that loads the content of node into the custom area.

```
function loadnode_in_region_menu_alter(&$items) {
    $items['load_node/%'] = array(
        'page callback' => 'loadnode_in_region_node_page_view',
        'page arguments' => array(1),
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

return $items;
}

function loadnode_in_region_node_page_view($nid) {
    $node = node_load($nid, NULL, false);
    $vnode = node_view($node);
    return drupal_render($vnode);
}

```

JS looks like

```
    jQuery.ajax({
        type: 'GET',
        url: Drupal.settings.basePath + 'load_node/' + id,
        dataType: 'html',
        success: function(data){
            jQuery('#ajax-result').html(data);
        },
    });

```

Result looks like this, with a duplicate menu

If I change line from

```
    return drupal_render($vnode);

```

to

```
    echo drupal_render($vnode); OR print drupal_render($vnode);

```

The result looks like I would like it, but some fields are not displayed correctly, such as voting and image. Looks as if they are not themed.

How to return themed node body without a menu?

# Answer
> 0 votes
You can create tpl for the menu and render the content and design tpl as required or create tpl for the content type in theme

---
Tags: 7, nodes
---


# Question
Title: Programatically initialising paragraph field in drupal 8
I would like to programatically populate a paragraph field with a default value for one of my content types.

I came up with the following solution:

```
use \Drupal\Node\NodeInterface;
use \Drupal\paragraphs\Entity\Paragraph;

function my_site_node_create(NodeInterface $node) {
    switch ($node->getType()){
        case 'my_content_type':
            $paragraph = Paragraph::create([
                'type' => 'references',  // paragraph type machine name
                'field_references_title' => [  // paragraph's field machine name
                    'value' => 'Some examples of what we have done' // body field value
                ],
            ]);
            $paragraph->save();

            $node->set('field_paragraphs_content', [
                [
                    'target_id' => $paragraph->id(),
                    'target_revision_id' => $paragraph->getRevisionId(),
                ],
            ]);
            break;
    }

}

```

This code seems to work but im worried I might be creating useless Paragraph-entities when the user doesn't save this node (because of the '$paragraph-\>save()').

How can I avoid this?

# Answer
> 2 votes
You should be able to rely on the auto-creating of new paragraphs, instead of assinging the ID, do not save the paragraph and assign it with `'entity' => $paragraph`.

This should then actually save the paragraph when the node is saved.

# Answer
> 2 votes
Inspired in https://www.drupal.org/project/paragraphs\_tools I created the next hook which worked for me. Basically instead for a $node-\>set it calls the appendItem from the paragraph field.

```
/**
 * Implements hook_entity_prepare_form().
 *
 * @param EntityInterface $entity
 * @param string $operation
 * @param FormStateInterface $form_state
 */
function example_module_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {
  $bundles = ['blockherotertiary', 'blockblogpost'];
  $entity_manager = \Drupal::entityManager();
  $langcode = $form_state->get('langcode');

  $field = $entity->get('field_blocks');
  $target_type = $field->getSetting('target_type');

  foreach ($bundles as $bundle_name) {
    // Create paragraph and display.
    $entity_type = $entity_manager->getDefinition($target_type);
    $bundle_key = $entity_type->getKey('bundle');

    /** @var FieldableEntityInterface $paragraphs_entity */
    $paragraphs_entity = $entity_manager->getStorage($target_type)->create(array(
      $bundle_key => $bundle_name,
      'langcode' => $langcode,
    ));

    // Field values.
    $field->appendItem($paragraphs_entity);
  }

}

```

---
Tags: 8, hooks
---


# Question
Title: Views filter has taxonomy term in whole vocabulary
I'm trying to use the "has taxonomy term" filter in a view together with Views Populate filters (https://drupal.org/project/views\_filters\_populate).

The taxonomy filter has not to be exposed because the exposed filter is the one created with Populate filters.

The site admin continuosly add new term to the vocabulary.

Consequently I cannot fill the "is one of" setting for the "has taxonomy term" filter.

I would need some settings like: if the term is in the vocabulary.

Any idea?

It seems strange to me that you cannot use the same input field to search for example in title and in a term reference field.

thank you in advance

# Answer
I've reached this question while looking for something similar and couldn't find anything relevant. Yet, after searching trough views options, I've managed to achieve something I think is the easiest workaround to our mutual issue, which is why I'm resurrecting this question.

First things first, I've created a `View` to show all the `taxonomy terms` of certain vocabulary and replaced the output as a link to, say, `/disciplines/[Term ID]`. Afterwards, I've created a `view` to replace the taxonomy display page and defined the term id as a contextual filter to the url(using the `%` replacement). Now every time the admin creates a new taxonomy term, the first `view` will always redirect to the second one with all the good stuff `Views` can offer.
> 1 votes

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


# Question
Title: Access referenced entity in Rules using hook_entity_property_info
I am using the Reply module for comment threads on a custom entity (we'll call it `myentity`). I'd like to create a rule that triggers when certain properties of `myentity` are met. However, the Reply module has very minimal `entity_property_info`, and so there's no way for rules to reference `myentity` in a condition.

The Reply module creates a Reply entity, that references an entity via entity\_id column and an entity\_type column. So, I created a `property_info_alter` hook as follows:

```
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['entity_id'] = array(
    'label' => t("Entity id"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'entity',
    'getter callback' => 'entity_property_verbatim_get',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}

```

When I create a condition in rules of "Entity is of Type", I expect to find my new property as an option like `reply:entity-id` but it doesn't. It only appears in the condition "Data Comparison".

I feel like I'm missing something very simple, but really can't put my finger on it. How do I get this property to appear as a referenced entity that I can then evaluate in Rules?

# Answer
> 0 votes
This works as-is. I actually had a typo in my code that took me a long time to catch. I'm leaving this up if anyone else has the same situation. The final code looked like this (cleaner):

```
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['myentity'] = array(
    'label' => t("My Entity"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'myentity',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}

```

---
Tags: rules, entities
---


# Question
Title: jQuery not Loading for "Anonymous" Users
For Drupal 7, a jQuery will not load for "anonymous" users on any template pages. But when I log in as an administrator it loads. It's similar to this issue: http://drupal.org/node/802432, but nothing I tried has worked. The only way I could get the jQuery to load was by giving the user access to the administration menu, which I do not want to do.

I have the following code in the `preprocess_node` function of the *template.php* file.

```
if ($variables['view_mode'] == 'full') {
$node =& $variables['node'];
if ($node->type == 'page') {
  $path = drupal_get_path('theme', 'responsive');
   drupal_add_js($path . '/js/jquery.snap.js', array('type' => 'file', 'scope'
   => 'header'));
   drupal_add_js($path . '/js/jquery.snap2.js', array('type' => 'file', 'scope'
   =>'header'));
  }
}

```

Here is the original JS code

```
<script type="text/javascript">
document.write(unescape("%3Cscript src='"
+((document.location.protocol=="https:")?"https://snapabug.appspot.com":
"http: //www.snapengage.com") + "/snapabug.js' type='text/javascript
'%3E%3C /script%3E"));
</script>
<script type="text/javascript">
SnapABug.addButton("77777-7777","0","50%", true);
</script>

```

I put the code in two separate JS files (couldn't get it to work in a single file)

jquery.snap.js

```
(function($) {
document.write(unescape("%3Cscript src='"
+  ((document.location.protocol=="https:")?"https://snapabug.appspot.com":
"http: //www.snapengage.com") + "/snapabug.js' type='text/javascript
'%3E%3C /script%3E"));
})(jQuery);

```

jquery.snap2.js

```
(function($) {
SnapABug.addButton("77777-7777","0","50%", true);
})(jQuery);

```

When I look at the HTML source I see an error for jquery.snap2.js: "Uncaught Reference Error: SnapBug is not defined." The result is the snapabug.js is not loading. This error does not occur on the administrative side and the snapabug.js does load.

# Answer
Drupal does not load jQuery if there are no dependency on it.

When `drupal_add_js()` is used once any where, Drupal includes jQuery automatically.

In case of user session, admin menu and overlay are dependent on jQuery so it is added automatically. So i advise you to try your `drupal_add_js()` code in `hook_init` just for try. I am not confirmed if it does not have any effect if it is called in `hook_preprocess`.

Please also check if you `hook_node_preprocess` is working at all?
> 2 votes

# Answer
And in Drupal 8 just add `Drupal` js as a dependency to your theme library

```
- core/drupal

```
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: How to create a full project on drupal.org?
I have created a custom module in Drupal 7. And now I want to contribute this module via drupal.org. For this I have created my account on drupal.org and created a sandbox project.

Now I am not getting how to make it full project.

# Answer
For promoting the sandbox module to full project requires for going through a one time review process.

Check: Apply for permission to create full projects

Before creating an issue for the promotion, make sure you go through the project application checklist to get good reviews.
> 3 votes

# Answer
Your starting point is https://www.drupal.org/project/projectapplications You'll need to create an issue according to the instructions on this page. People will review (automated and manually) to check if this module is good for contrib.
> 2 votes

# Answer
To promote your sandbox project to full project, you will have to apply for permission to create a full project as described here in drupal docs: https://www.drupal.org/node/1011698 .

After getting permission you will be able to promote your sandbox to a full project.

Here are complete screenshots: https://www.drupal.org/node/1068952.
> 2 votes

# Answer
As of 2017/03/07, users do not need to go through the Project Application Review process to promote a project. With this change, people without the git-vetted status can promote one sandbox project to full project status. See also the change record:

> Strong signals about security advisory coverage are available on project pages on Drupal.org, and in the updates.xml that is served by Drupal.org for core to consume. There is also now a field for project maintainers to opt into security advisory coverage.
>
> This means that we're now able to open the gates, to allow any user who has accepted the Git repository usage policy to promote their sandbox projects to full projects with releases.
>
> At the same time as we make this change, we'll be repurposing the 'git-vetted' user role as a 'may opt-into security coverage' role. The existing project application process move from a gate on promoting full projects to the gate for opting in to security advisory coverage. That process will be further refined by various stakeholders in follow ups.
>
> We'll be updating the documentation to reflect this change in process as well.
> 2 votes

# Answer
An alternative approach to "create a full project on drupal.org", is to investigate the existing (+17K) contributed modules, and narrow them down to projects with status like:

From the search results that you get, verify if there is anything that has a "namespace" (= the machine name of your module) that might fit (or is close enough) to what your (new) module is about.

Then request the module's ownership to be treansfered, using these steps (in specified order):

1. Contact the module owner via the contact form of that owner on Drupal.org, asking for the ownership to be transferred.
2. If current owner indicates to agree with a transfer, or if after 2 weeks you have not received any response to step 1, then file an issue in the Drupal.org project ownership project (component = *Ownership transfer*), to request the "ownership to be transferred" (include relevant communication from step 1 to motivate your request). Issue # 2367923 is an example of such issue.
3. The people handling the request from step 2 will then also try to contact the current owner (if you didn't get a reply to step 1.). And after a grace period of (about) 2 weeks, the project's ownership will be changed to you (unless there was some type of feedback from the current owner to not do so).
4. Do whatever you want to do with the module for which you became the new owner, without any review process involved. But make sure to:

* give credit to the previous owner somehow.
    * NOT destroy any (GIT) history of the old version of the module.

The above period works fine, though it takes a little time (a few weeks at max) to complete all the steps ... And it has the advantage (I think) that you contribute a very little bit to reduce the amount of abonded-looking contributed modules.

**PS**: There are occasions where the current maintainer responds/reacts with something like "Hm, somebody interested in contributing to a 2nd live to a module I started ... how about I only grant co-maintainer status instead of transferring module ownership?". If that happens, then "you" have to decide if you yes/no are willing to accept that. A possible compromise in that case could be "how about we turn the table: I become owner, and make you (current owner) a co-maintainer".
> 1 votes

---
Tags: community-official-site
---


# Question
Title: What is the best way to delete or disable ( most expected) the field of a content type?
We have several content types (features) on our Backend, now site Administrators (authors) and content managers need some field to be disabled when creating content. How I can manage it? I heart about the 'field\_permission' module but I'm not sure if that module can solve my problem. What could be the best way to disable these fields? Is there some module or could some one explain where I should start? Pseudo code are Welcome Thank you in advance Hermann

# Answer
Here's what I usually do.

1. Find contents that have data for those fields you want to delete.(You can easily find it in DB)
2. Delete all contents found in step 1 or remove data from those contents.
3. Remove the field from content type.
> 0 votes

# Answer
It really depends on your setup. If you dont want those fields anymore you can simply delete them off content type but if you want those fields to be available for certain roles then go with something like field permission module. Also, if you have those content type defined in features, I would recommend making changes to it first and then rebuilding the features.
> 0 votes

---
Tags: entities, features
---


# Question
Title: Convert Media tags to markup failing again
Once again I am plagued by this. Embedding an image from the media library shows in the editor, but when you view the node on the front end you get this:

```
[[{"fid":"851","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"Reality Check","field_file_image_title_text[und][0][value]":""},"type":"media","attributes":{"height":"333","width":"1502","style":"font-size: 13.008px;","class":"media-element file-default"}}]]

```

Normally you would confirm a couple things in drupal 7.5 -

* Check the text format configuration to make sure convert media tags to markup is set. In my case its on every filter and it is in the top position. no matter which position it is in, still nothing works.
* Check to see if a custom template is used and make sure it's using render() and not just a plain echo. In my case, it is a custom template and it is using `render($node->body['und'][0]['value'])`
* Check to see if any wrapping tags may be causing a conflict. In my case there is no wrapping tag. It's just an inline image from the media library.

I'm using a custom tinyMCE install with the wysiwyg module because for reasons unknown the media library module broke everything much worse. Somehow I don't think this has anything to do with tinyMCE though.

Anyone have any further ideas?

# Answer
> 1 votes
For those of us just constantly plagued by this failure in programming, here's a link with the solution that worked for me. Upvote if you find it helpful: Media with WYSIWYG not converting media tags to markup

Essentially, don't trust `print render()` \- I had to use this in my custom template file:

```
<?php print render(field_view_field('node', $node, 'body', array('label'=>'hidden'))) ;?>

```

---
Tags: 7, media, wysiwyg
---


# Question
Title: How to redirect certain requests to use https://www.example.com in pantheon?
In my Drupal install I would like to direct most URL requests to use https://www.example.com and only a few pages to use http://www.example.com Since my site is hosted on pantheon i cannot use .htaccess and i need to rely on my settings.php file. I tried the following but it doesn't really seem to work.

```
$redirect_domain = 'www.example.com';
if (isset($_SERVER['PANTHEON_ENVIRONMENT']) && $_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
  $redirect_location = '';
  // Do not require HTTPS for specific pages.
  if (in_array($_SERVER['REQUEST_URI'], array('/node/524','/some/unsecure/iframe'))) {
    // Check if HTTPS is enabled.
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
      $redirect_location = 'http://' . $redirect_domain . $_SERVER['REQUEST_URI'];
    }
  }
  // Require HTTPS for everything else.
  else if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
    if($_SERVER['HTTP_HOST'] != 'www.example.com'){
      $redirect_location = 'https://www.example.com' . $_SERVER['REQUEST_URI'];
    }
    else{
      $redirect_location = 'https://' . $redirect_domain . $_SERVER['REQUEST_URI'];
    }
  }
  // Perform redirect.
  if ($redirect_location) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: ' . $redirect_location);
    exit;
  }
}

```

typing in example.com does correctly redirect to https://www.example.com but typing in https://example.com doesn't perform any redirect.

# Answer
> 1 votes
That's because the $redirect\_location doesn't get updated for https://example.com. See updated code below.

```
$domain = 'www.example.com';
if(isset($_SERVER['PANTHEON_ENVIRONMENT']) && $_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
  $location = '';

  if(in_array($_SERVER['REQUEST_URI'], array('/node/524'))) {
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
      $location = 'http://' . $domain . $_SERVER['REQUEST_URI'];
    }
  }
  else {
    if($_SERVER['HTTP_HOST'] != 'www.example.com') {
      $location = 'https://' . $domain . $_SERVER['REQUEST_URI'];
    }
    if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
      $location = 'https://' . $domain . $_SERVER['REQUEST_URI'];
    }
  }

  // Redirect
  if ($location) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
  }
}

```

---
Tags: redirection, configuration
---


# Question
Title: Geolocation Field Oops! Something went wrong
I'm using Geofield Gmap as Field in a Content Type. Each time I try to create/Add a node, the (Geofield) field display the below Error message

> "Oops! Something went wrong this page didn't load google maps correctly. See the javascript console for technical details."

The Steps that I did:

* Create API key For Google Map.

**UPDATE:**

I tried to apply the following patch:

```
patch -p1 < https://www.drupal.org/files/issues/fix-api-key-not-being-used-2746209-5.patch

```

I see this message:

> No such file or directory

# Answer
> 3 votes
Usually you see this message when you don't have in the Geolocation module the Google API Key or the Google API Key is not working well. For this you need to go to:

```
http://YOURSITE/admin/config/content/geofield_gmap

```

Write your working Google API Key and save the Configuration.

**Edit:**

To apply the patch you need download the file to:

```
sites/all/modules/geofield/modules/geofield_map

```

then go to the dir and run:

```
patch -p1 < fix-api-key-not-being-used-2746209-5.patch

```

# Answer
> 0 votes
You can possibly solve it by looking at the JavaScript console for technical details. Click on F12 and view the JavaScript error.

EDIT: If you got a missing key map error, then it is probably misconfigured and you should find a solution here.

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


title: Write a File Locally

text:
# Question
Title: Write a File Locally
I am trying to write files and read from them. The following code works great on my local Kalabox server, but when I push to Pantheon, the files don't get written.

Could it be because all files are under sub versioning on Pantheon?

```
$csv_text = array2csv($db_result);
save_csv_file($csv_text);

if($_GET[save_to_email] == 'true'){
    save_defaults();
}

function save_csv_file( $csv_text){
    //$file = './inventory.csv';
    $file = 'public://inventory.csv';
    file_put_contents($file, $csv_text);
}

function save_defaults(){
    $default_vals = get_inventory_defaults();
    $default_vals[sort_direction] = $_GET[sort_direction];
    $default_vals[threshold] = $_GET[threshold];
    $default_vals[hide_zero_inventory] = $_GET[hide_zero_inventory];
    $default_vals[email] = $_GET[email];

    save_inventory_defaults($default_vals);
}

function get_inventory_defaults(){
    $file = './inventory_defaults.txt';
    //$file = 'public://inventory_defaults.txt';
    $content = unserialize(file_get_contents($file));
    return $content;
}

function save_inventory_defaults($my_variable){
    //$file = './inventory_defaults.txt';
    $file = 'public://inventory_defaults.txt';
    $content = serialize($my_variable);
    file_put_contents($file, $content);
    //file_save_data($content, $file, FILE_EXISTS_RENAME );
}

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

```

I am not sure when to go from here... A million thanks!!

# Answer
From Pantheon docs: "Pantheon cannot be used to host files over 256MB, no matter how the file is uploaded"

http://helpdesk.getpantheon.com/customer/portal/articles/745361-known-limitations

It could be that your file is too large and therefore Pantheon will not host it.
> 1 votes

# Answer
I would suggest you to check the server permission for writing the files, if the permissions are properly given then you can try giving the exact relative path (which would be something like DRUPAL\_ROOT . "/sites/default/files") instead of just "public://".

If that doesn't work then you can try cURL to read and write the contents of file instead of using file\_get\_contents and file\_put\_contents.
> 0 votes

---
Tags: files
---


title: How do I create a calendar of events?

text:
# Question
Title: How do I create a calendar of events?
I am needing a solution to add an event to a calendar, and the events are also displayed on a web page in order of the next event.

Similar to this Wordpress plugin: https://wordpress.org/plugins/the-events-calendar/screenshots/

Any help is greatly appreciated.

# Answer
As it stands, there are a few options from a module perspective.

Calendar and FullCalendar are the popular calendaring options in Drupal - neither seem to have a stable Drupal 8 release yet but their dev branches may be workable. You'd have to try, and read through their issue queue to understand where they are at functionality wise.

Calendar View is a lightweight module to display any Views results in a calendar table. Compatible with any View. Zero dependencies.

Lastly, you could iframe embed a Google Calendar onto a page. But as you may have guessed, this means events need to be managed in Google Calendar itself, unless you set up a sync from Drupal to Google Calendar.

Other than that, there are no 'ready made' modules for this yet that are stable and production ready for Drupal 8. It looks like the others only have a Drupal 7 release or have been abandoned.
> 6 votes

# Answer
The Drupal 8 Calendar module is working well for our sites needs. It integrates well with views to create lists of upcoming events and add to a calendar display being delivered from a single or multiple content types.

This module has over 125,000 installs so it will be a solid platform for our site calendar.
> 2 votes

---
Tags: 8, datetime
---


# Question
Title: Add a subquery to SELECT'd columns in a dynamic query
I have a query I want to run through Drupal 7's DB API as a dynamic query where a subquery needs to be a column of data.

For example:

```
SELECT a, b, (
  SELECT x, y
    FROM table
    WHERE table.x = 'value') as c
FROM table_2
WHERE table_2.a = 'value_2'

```

How can I perform this through the Drupal 7's DB API?

# Answer
> 2 votes
If you're building a dynamic query, the method `SelectQuery::addExpression()` will let you add a SQL subquery expression to the list of selected columns:

```
$query = db_select('table_2', 't2')
  ->fields('t2', array('a', 'b'))
  ->condition('t2.a', 'value_2');

$sub_query = "(SELECT x, y
  FROM table
  WHERE table.x = 'value')";

$query->addExpression($sub_query, 'c');
$results = $query->execute();

```

# Answer
> 1 votes
You can use `db_query()`

```
$result = db_query(
  'SELECT a, b, (
    SELECT x, y
    FROM {table}
    WHERE table.x = :value1) as c
  FROM {table_2} AS table_2
  WHERE table_2.a = :value2',
  array(
    ':value1' => 'value',
    ':value2' => 'value_2',
  )
);

```

---
Tags: 7, database
---


# Question
Title: How to make view to group by only one field?
I have a view with multiple fields and the fields have multiple values, so I get many duplicates in results. When I try to use distinct, nothing happens, because select distinct does not affect on multiple values. I have predictable, but non desired result.

When aggregation is disabled I don't have any "groupby" directives in resulting SQL.

When I enable aggregation, I see in resulting SQL the following:

```
GROUP BY field_data_field_tour_short_name_node_entity_type,
field_data_field_tour_short_name_field_tour_short_name_value, node_title,
nid_1, field_data_field_arr_dates_node_entity_type,
field_data_field_arr_dates_field_arr_dates_value,
field_data_field_tour_duration_node_entity_type,
field_data_field_tour_duration_field_tour_duration_tid,
field_data_field_tour_minimal_price_node_entity_type,
field_data_field_tour_minimal_price_field_tour_minimal_price

```

So, as you can see, I have ALL the fields in my view.

When I disable aggregation and try to use hook\_views\_query alter

```
$query->add_field('node', 'nid', 'nid', array('function' => 'groupby'));
$query->add_groupby('node.nid');

```

I get the following:

```
GROUP BY node.nid, field_data_field_tour_short_name_node_entity_type,
field_data_field_arr_dates_node_entity_type,
field_data_field_tour_duration_node_entity_type,
field_data_field_tour_minimal_price_node_entity_type

```

As you can see, I get less fields, but not one.

But I need simply:

```
GROUP BY node.nid

```

How can I get grouping by only on field instead of many?

UPDATE: I found the following strings in views\_plugin\_query\_default.inc

```
$groupby = array_unique(array_merge($this->groupby, $non_aggregates));
  foreach ($groupby as $field) {
    $query->groupBy($field);
  }

```

So views for some reason add other fields to groupby if groupby is present. How to avoid this adding? I could change the file, but this is not proper way.

# Answer
I had the same problem. Try to implement the group by in hook\_views\_pre\_execute, it's work for me.

```
function MYMODULE_views_pre_execute(&$view){
  if ($view->name == 'YOUR_VIEWS' &&  $view->current_display == 'SOME_DISPLAY') {
    $view->build_info['query']->groupBy('node.nid');
  }
}

```

If you are using a pager, updating $view-\>build\_info\['count\_query'\] with the same changes should keep the pager consistent with the query results.
> 6 votes

# Answer
You can `unset` the fields that you are not interested in. This code works for me, in `hook_query_alter`:

```
    if ($query->hasTag('views_' . $view_name)) {
        $fields =& $query->getGroupBy();
        unset($fields['item_id']);
        unset($fields['field_data_field_field_rf_product_node_entity_type']);
        $query->groupBy('field_oem_ubication_field_collection_item__field_data_field_');
        $query->groupBY('taxonomy_term_data_field_data_field_brand_name');
    } // if

```

As you can see, I **add** some fields ( $query-\>groupBy ) and **unset** others.
> 2 votes

# Answer
A screenshot would be really beneficial here as I'm getting it hard to visualise the problem. But generally, hiding the field you want to group by and then grouping by it is the general way to go.

https://www.drupal.org/project/views\_merge\_rows is also a bit of an alternative to aggregate.

Anyways, just throwing out ideas cause no one else has answered.
> 1 votes

---
Tags: views
---


title: Password reset on user_save() issue

text:
# Question
Title: Password reset on user_save() issue
I used user\_save to update the field. However, whenever I run this function and I log out and try to log back the password doesn't work anymore.I think it cause a change in the password. can anyone help me to get the actual password back?

```
$existingUser1 = user_load($uid1);
$existingUser1->field_group_id[LANGUAGE_NONE][0]['value'] = $g_id;
user_save((object) array('uid' => $existingUser1->uid), (array) $existingUser1);

```

# Answer
You probably want this:

```
$existingUser1 = user_load($uid1);
$existingUser1->field_group_id[LANGUAGE_NONE][0]['value'] = $g_id;
user_save($existingUser1);

```

You just need to call user\_save() on the user object to save the values after you have changed any fields.
> 2 votes

---
Tags: 7, users
---


# Question
Title: Entity translation: views with and without language fallback
I need views with entity language fallback and others without.

if "Enable language fallback" is activated, is there a way to disable this for a specific view

Thanks Rainer

# Answer
There doesn't seem to be a solution with "Enable language fallback" activated. I guess it has to be made the other way around. Disabling it and add a fallback on views level using the "No results behavior".
> 0 votes

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


# Question
Title: How to work with .install files and hook_enable etc... when developing a module?
I'm writing a module which utilises a .install file to create and configure things - specifically I'm creating a custom line item based on the commerce\_example module. Turns out it's quite a bit of code and will take a bit of time to get right.

This is all good, but how can I go about testing this as I'm going? I'll inevitably want to add fields to the install function later on, but to do this I'll need to disable (and uninstall?) the module, deleting the existing line-items, and re-enable every time I need to test if it's working which seems so slow. Is there a better way of working when doing this?

# Answer
> 0 votes
Yes You can write in your hook\_update\_N() like this in your mymodule.install file:

```
function mymodule_update_7001() {
 db_add_field('table_name', 'field_name', array(
  'description' => 'The total amount to be paid for the order.',
  'type' => 'numeric',
  'precision' => 16,
  'scale' => 5,
  'not null' => TRUE,
  'default' => 0.0,
 ));
}

```

After writing this you can simply run your update.php file

---
Tags: 7, installation
---


# Question
Title: Breadcrumb displays overridden page label instead of node title
Configuration:

* Drupal 8.1.5
* Panels 8.x-3.0-beta4
* Page Manager 8.x-1.0-alpha23
* Layout plugin 8.x-1.0-alpha22
* Panelizer 8.x-3.0-alpha2

Main menu:

* About
    + Team
    + Technology
    + ...

When visiting page `/about/team`, the breadcrumb shows `Home About`.

With Page Manager, I have overridden the default `/node/{node}`, and created a couple of panel variants based on path.

With this configuration, when visiting page `/about/team`, the breadcrumb shows `Home Node view`. So, instead of the node title for the `/about` page, the label of the custom page managed by Page Manager is displayed.

Is this a bug or expected? How to fix it?

# Answer
This is an issue related with page\_manager module. Check out the d.org issue queue https://www.drupal.org/node/2665328
> 1 votes

---
Tags: 8, panels, breadcrumbs
---


# Question
Title: The best way to generate buttons and apply visibility restrictions based on roles
I want to generate about 40 buttons on the same page, every button should be visible to only a certain group of people based on their Drupal roles.

What the best way to do it ? I thought about creating a bloc for every button but to display them with visibility restriction in the Block layout and restrict every bloc by role..but it's not very efficient and the Block layout page will be full of those blocs.

Does anyone have any suggestions ?

Thank you

# Answer
you can simply create different class for each type color and based on the role you can add the class to the button.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: Sort content of views with drag and drop
I use Drupal 8, but I can not figure out how to sort views with drag and drop. The client needs to sort the items of the views in a very personal way.

Do you know some way?

# Answer
The Draggable Views module might be what you need. There is a version of the module for Drupal 8.

According to the module description,

> DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.

I tried the following instructions in the documentation page on a vanilla Drupal 8.2.6 installation, and it worked fine (see screenshot below).

> 1. Activate the module and navigate to the edit-page of an existing view.
> 2. Now go to the Format section and choose Table.
> 3. Make sure you have the "Content: Title" field, place it as your first field.
> 4. Add the field "Draggableviews: Content" at the Fields section, place it after the "Content: Title" field.Make sure not to check "Exclude from display"; if you do the view will permit drag and drop but the changes will not be saved.
> 5. Add "DraggableViews: Weight" at the Sort criteria section and place it as the first Sort criteria. Save the view and you're done.
> 10 votes

# Answer
Have you tried Entityqueue? It is a drag and drop interface, in which you insert nodes and sort them.

You can then use the nodequeue as a relation, and sort criteria in views...

https://www.drupal.org/project/entityqueue
> 1 votes

# Answer
You will need to create two set of views (lets say list view and order view) and they both should be sorted by draggableviews:weight. The order list view should be displayed as a table and should have draggableviews:content as one of its fields. See attached example.

Once this is setup, you can go back to list view and click on draggableviews:weight and select the newly created order view as sort order.

Let me know how you go.

STEP 1:  STEP 2:  STEP 3:
> 0 votes

# Answer
Refer this link, it may help. https://www.drupal.org/node/2824325
> -1 votes

---
Tags: 8, views
---