# Question
Title: Add a "autocomplete" field in a buildForm
How do I add an autocomplete field in a class that extends `FormBase`?

I created a custom module, which uses a class that extends `FormBase`. I want to programmatically create a form field that autocompletes the username from the user registered in the site.

# Answer
> 10 votes
You use *entity\_autocomplete* as #type for the form field. `CommentForm::form()` contains such a form field, for the administrator users to be able to change the author of a comment. This is the code it uses.

```
  // The uid field is only displayed when a user with the permission
  // 'administer comments' is editing an existing comment from an
  // authenticated user.
  $owner = $comment->getOwner();
  $form['author']['uid'] = [
    '#type' => 'entity_autocomplete',
    '#target_type' => 'user',
    '#default_value' => $owner->isAnonymous() ? NULL : $owner,
    // A comment can be made anonymous by leaving this field empty therefore
    // there is no need to list them in the autocomplete.
    '#selection_settings' => ['include_anonymous' => FALSE],
    '#title' => $this->t('Authored by'),
    '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
    '#access' => $is_admin,
  ];

```

As you can see from the code, you can also choose to include the anonymous user.

The result is shown in the following screenshot.

>

# Answer
> 2 votes
Drupal 8.0 provides a form element specifically for autocomplete with any entity (implemented by the `EntityAutocomplete` class), and has some changes for custom autocomplete.

Look at the Drupal Change Records and search for *autocomplete* in the *Keyword* field; you will get a list of changes for Drupal 8. There is a change record that lists the changes for a custom autocomplete functionality by using the form properties #autocomplete\_route\_name and #autocomplete\_parameters.

So with that information you should be able to add an entity autocomplete element in your form for users.

---
Tags: 8, entities
---


# Question
Title: How can I conditionally show a field in the node/add page?
When users are in node/add/page, I want to show the body field when the title is not empty. How can I achieve this?

# Answer
By default in Drupal 8 "Seven" is the admin theme.

(Assuming you're using Seven as your admin theme) In `/core/themes/seven/js` add/create *custom.js* file.

**custom.js**

```
(function ($) {

   $('#edit-body-wrapper').hide();

   (function Forever(){

     var title = $('#edit-title-0-value').val();

     if (title != '') {
       $('#edit-body-wrapper').slideDown(1500);
     }
     // slides down and shows the body field in 1.5 secs if the title field is not empty

     else if (title == '') {
       $('#edit-body-wrapper').slideUp(1500);
     }
     // slides up and hides the body field in 1.5 secs if title is empty

   setTimeout(Forever, 1);

   })();

})(jQuery);

```

Now edit **seven.libraries.yml**

In the `node-form:` section add

```
  js:
    js/custom.js: {}

```

So it should look like this:

```
node-form:
  version: VERSION
  css:
    layout:
      css/layout/node-add.css: {}
  dependencies:
    - node/form
  js:
    js/custom.js: {}

```

**PS:** Don't forget to clear the cache to see changes.
> 1 votes

---
Tags: nodes, 8
---


# Question
Title: How to disable cache for a specific content type?
I use Drupal 8 and I want to disable caching for a specific content type in full view mode.

I've found how to disable caching for all view modes, but I want to disable it for only a specific content type.

How can I do that?

# Answer
You need to set max-age 0 in e.g. hook\_node\_view().

```
function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'yourtype' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

```

That said, I recommend you find a way to make caching work. There are concepts like lazy\_builder that allow you cache most of a node and only dynamically build a small part in it.

Also note that this does *not* disable the page cache for anonymous users. If you need that too, which I would recommend even more to try and avoid, then you also need:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

Update, answer is getting too long to post in a comment:

Ah, flag. How do you hide the flag for the author? Are you using the latest D8 and flag version?

If you look at flag\_entity\_view(), you can see that flag is already doing exactly that. It registers a so called lazy builder and enables a thing called placeholdering. It does that to show a flag/unflag link depending on the user. You probably just set #access on that element right now.

Flag is supposed to have access hooks but I think they don't work right now. See https://www.drupal.org/node/2584299. Follow that issue, once that is resolved, you can just implement that.

But for now, you can just switch out the lazy builder callback there with your own for now that does your additional check and then does what the existing one does. And it will just work.
> 9 votes

# Answer
You can also use the option

```
no_cache: TRUE

```

in your route declaration as described here: https://www.drupal.org/node/2463533
> 2 votes

---
Tags: 8, caching, entities
---


title: Display fields node in table like views

text:
# Question
Title: Display fields node in table like views
I have a content type documents and my fields (created by admin) are:

* Doc1
* File
* Date
* Doc2
* File
* Date
* Doc3 ...

The reason why I don't do a content type just with: "Doc, file, date" and add the nodes I want is because I need the Document name to be written by admin, and no one can edit it.(for example: birth certificate) (If you have an idea to do this other way, I'm listening)

This way, the user inserts just one node with all of those fields.

I want to somehow group those fields (Doc1, file, date) and display it like a view.

Views display all nodes from a content type. I need to display the fields of just one node, like a table. Is this possible?

Thanks

# Answer
You can create a view to display a single node. You can determine which node to display by using a contextual filter. For instance, you can pass the node ID to the view, in order to get it displayed.

There are many tutorials explaining how to use contextual filters with views. A possible starting point might be the following: https://www.drupal.org/node/1578558
> 1 votes

# Answer
You could stick with the common practice: content-type with your fields and multiple nodes. There's a module called field-permissions, where you can set a field permission e.g. to view and/or edit by admin only. I guess this will work.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: How do I show specific content on a separate page?
I have menu links **HOME | Property**(links to property content type) **|** **NEWS**. In every News there are tags which reference to the property.

I want to link "NEWS" menu item to a separate page which should display only the news list which contains the tags for the property.

For example, i am on a property page say "Property XYZ", so there is a menu item "NEWS", when i click this menu item, a new page opens and this page is showing news which contain the Tag "Property XYZ" in them.

How do I achieve this?

# Answer
From what i understand, These tags can be taxonomy terms and you can create a view where you can use contextual filter to get the tag name from url and show the related news content.

1)Page "Property XYZ" will have a link as abc.com/news/tag1
2)You can create the view page with path /news/%
3)News content should be already having those tags,so that you can get it from that view.

If this is not what you are looking for please provide more details.

EDIT:
1)https://www.drupal.org/project/pathauto
You can use this module to create patterns according to your need for your each news node path alias. You can use tokens of the taxonomy tag field to set those patterns.

For eg:
news/\[node:title\]/\[node:field-news-category:1:name\]
where field-news-category is the taxonomy reference field where you select tags terms

Now how to put these all these links in the menu is a different thing and that is up to you.

2)when you create a page view set path as /news/% (% for just a tag) OR /news/%/% (where first % can be news title and second can be tag)
% is the argument from url which is used in the contextual filter field

In right column of the view go to advanced and add a relationship field Content: Taxonomy terms on node then add contextual filter field as Taxonomy term: Term ID

There should be a default view as Taxonomy term,which will give you some idea to go about it. Play around a bit with contextual filters.

This might help,
Url Path Alias is not working with the "raw value from URL contextual filter"
> 1 votes

# Answer
If you're new to Drupal 7, one the fun surprises is that the query builder isn't in core (it finally was added in D8). You'll need to install the views module (which requires the ctools module, and a good tutorial will help). Given the description of your navigation you may want to have views create the property page as well.

1. Make sure taxonomy, views, and views UI modules are all enabled.
2. Create a vocabulary for your terms.
3. Add a taxonomy field to both your News and Property types, and link it to the taxonomy you created in step 2.
4. Create a few test pieces of content with shared terms (so you can test the view as you build it).
5. Create a view that searches for nodes or type news. Create a page display. Without more than the default filters this will probably be a very reasonable general purpose news page.
6. Create a block display on that view.
7. To the block display add a contextual filter (third column) that filters by the taxonomy term ID, set the type to "Taxonomy term ID from URL", check the box labeled "Load default filter from node page, that's good for related taxonomy blocks", and then select the field you created in step 3.
8. Go to the blocks display (or whatever module you are using to control block placement) and add your new view block to display on the property pages.

There will be details to tweak and massage but this should get you 80% of the way there. If you want the exact behavior you've described above, you could use a page display for the news listing that has a different setting on the context filter to filter by term name. Or you could update the taxonomy pages (again using views) to only show nodes of type news, and link directly from the property page (when you install views there are disabled views for the terms that you can modify to do exactly that if you want).
> 0 votes

---
Tags: views, 7
---


# Question
Title: Send email to different email depending on taxonomy term
This was fairly simple to do in D7 and is a common request. How would I send an email to a different email address depending on a taxonomy term chosen from a dropdown box on the contact form?

# Answer
I don't know how you did it in D7, but hook\_mail\_alter is my preferred solution. And in hook\_form\_contact\_site\_form\_alter i would add taxonomy term reference field to the contact form.

> This still works in D8

Code would look like this in your custom module:

```
/**
 * Implements hook_mail_alter().
 */
function YOUR_MODULE_mail_alter(&$message) {

  if ($message['id'] == 'contact_page_mail') {

    $tid = $message['params']['your_form_field'];
    if (!empty($tid) && $tid > 0) {
      // $tid to determine the address ?!
      $message['to'] = 'your@emai.l';
    }
  }

}

```
> 2 votes

---
Tags: 8, emails
---


title: Executing multiple drush commands

text:
# Question
Title: Executing multiple drush commands
I manage a lot of Drupal sites and drush is a lifesaver. I usually script what I need done and then loop over all of the sites.

Many times I need to execute several Drush commands on the same site. Because Drush has to go through the bootstrap process for each command it can be a bit slow. So if I do three commands, Drupal gets bootstrapped three times. Example:

* drush cc all
* drush dl freds\_module
* drush en --yes freds\_module

So is there any way to run multiple commands with one bootstrap? Something like:
drush "cc all" "dl freds\_module" "en --yes freds\_module"

The idea is to bootstrap drush only once rather than three times. If it is not possible, I'll still be happy with Drush.

Thanks.

# Answer
> 2 votes
From my personal experience, I would run these tree commands like this: `drush cc all; drush dl freds_module; drush en freds_module --yes`. I use semicolons to separate my commands. You can also use the ampersand(&&), `drush cc all && drush dl freds_module && drush en freds_module --yes`. Here, if one command fails, the rest will not run.

# Answer
> 1 votes
A simple way is create bash file in Linux or batch file in windows,put your command in batch(bash) file and run it.

simple example if create bash file in linux

simple example if create batch file in windows

# Answer
> 1 votes
You can also make Drush shell aliases to run drush and bash commands. It is possible to place multiple commands in these Drush shell aliases using the method that Hectorplus mentions in his answer by separating them with `&&`.

Adding the following to your drushrc.php in one of the 6 possible locations.

```
$options['shell-aliases']['en_freds_module'] = 'drush cc all && drush dl freds_module && drush en --yes freds_module';

```

Then you can run the Drush shell alias with:

```
drush en_freds_module

```

# Answer
> 0 votes
I'm not sure if you can execute multiple commands like that, but with your specific example, `drush en freds_module --y` will download the module if it is not already present. (The `-y` flag will answer yes to all prompts.)

Note that this was added in Drush 6.0.0 `(#1364814 by eiriksm, jonhattan: Added Extend pm-enable to offer downloading the project for missing extensions.)`

# Answer
> 0 votes
In your example `cc`, `dl` and `en` can be replaced just by one command:

```
drush -y en some_module

```

It'll automatically download and enable the module at the same time. If module defines new menu items and other hooks, most of the time cache is cleared as well.

If you'd like to use drush for other multiple commands, there is no straight forward solution other than passing them as list or creating your own custom drush command.

You can also create alias command in your `drushrc.php`, in example:

```
  'debug-enable' => '!
    drush vset --yes rules_debug 2 \
    && drush vset --yes rules_debug_log 1 \
    && drush -y en devel
    && drush views-dev
    ',

```

so executing one `drush debug-enable` command, it actually will execute multiple commands. If you prefer run them multiple simultaneously, consider running them in the background (`&`).

Alternatively as workaround use `drush_hook_post_COMMAND()` and `drush_hook_pre_COMMAND()` to perform additional tasks within one bootstrap for specific command (e.g. clearing caches after `pm-enable`).

If this is part of the script, another trick is to send different `drush` processes into the background at the same time and wait for them (works with Bash), e.g.

```
drush -y en dblog devel &
drush -y updb &
drush -y fr mymodule &
wait

```

# Answer
> 0 votes
One option is to use Drush alias command in your "drushrc.php" file. There is lots of examples and documentation at https://github.com/drush-ops/drush/blob/6.x/examples/example.aliases.drushrc.php

On the left side of that page. Under "branch" menu. Select the appropriate Drush version.

---
Tags: drush
---


# Question
Title: No more error messages shown, once i uploaded a file of invalid size?
The scenario is as follow: when i uploaded a file with invalid extension a proper error shown, everything is fine. nothing bad with invalid extensions. where as: when i uploaded a file of larger size (greater than limit) an error shown. and if i tried second time with invalid file(i.e both for size and extensions) no error shown and file is also not uploaded. i want to display errors in all tries with invalid files. and i am using **HTML5 Drag & Drop File** module for uploading multiple files by browsing or drag and drop

any help please

# Answer
> 1 votes
The error about invalid extension which you're seeing is invoked by File module in `modules/file/file.js`, here is a snapshot:

```
/**
 * File upload utility functions.
 */
Drupal.file = Drupal.file || {
  /**
   * Client-side file input validation of file extensions.
   */
  validateExtension: function (event) {
    // Remove any previous errors.
    $('.file-upload-js-error').remove();

    // Add client side validation for the input[type=file].
    var extensionPattern = event.data.extensions.replace(/,\s*/g, '|');
    if (extensionPattern.length > 1 && this.value.length > 0) {
      var acceptableMatch = new RegExp('\\.(' + extensionPattern + ')$', 'gi');
      if (!acceptableMatch.test(this.value)) {
        var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", {

```

Since it worked for the first time, but not on the second time, it's possible that you've some JS error which preventing this event to be invoked. If that's not the case, make sure `file.js` is included on the second time.

To debug that issue, you may create a breakpoint in above code to see if it's triggered properly. If it's not, using DevTools try enabling *Event Listener Breakpoints* for *Control* *change*/*submit* events, then try to reproduce the issue, so you'll know exactly what's happening.

Test also if you can reproduce the issue with File it-self using the default theme. If not, maybe it's worth to report a bug against that module.

---
Tags: 7, forms, files, debugging
---


# Question
Title: Restrict menu item to certain roles in TB Mega Menu
I am currently using TB Mega Menu on D7 to configure my main menu. One of the main menu item is accessible to both anon & authenticated users.I would like to have a block attached to this item as a drop down but it should be accessible only by certain roles - not all authenticated users. I have enabled block visibility restrictions for this block by the user roles I want. But I am still able to view this block as part of the menu as an anon user. How do I restrict this?

# Answer
> 0 votes
A possible workaround solution would be to create another menu all together and give the block menu access to the role that you need and exclude this role from your original menu.

---
Tags: 7, blocks, navigation
---


# Question
Title: How to incorporate the body field back into a content type from which it has been previously deleted?
I am on D7. In the past, I have deleted the body field from a certain content type in my project. Now, the problem is that I want the body field back into this same content type, but cannot find it in the list of existing fields in my project to be added to the content type. How can I add the deleted body field back into the content type? Is it possible? It is important to say that I don't want its content back. I just want the regular Body field with the original ID body, instead of creating a "field\_body". Thanks.

# Answer
In a hook\_update\_n(), module\_install(), module\_enable(), or devel module eval php code:

`$types = node_type_get_types();
node_add_body_field($types['my_content_type_name']);`

giving it the machine name of your content type, and optionally you may provide a label for what you want the human readable label for the field to be (defaults to 'Body'). see node\_add\_body\_field() API documentation
> 12 votes

# Answer
In Drupal 7, I think that if you create a new content type, it appears with default "body" field. So it appears again in "existing fields" menu too. Then you can select it for any other conent type and after that you can delete the new content type created for this pourpose.
> 2 votes

# Answer
With drush I used

```
drush  php-eval '$types = node_type_get_types(); node_add_body_field($types["content_type_name"], $label="Body");'

```
> 2 votes

# Answer
In a hook\_update\_n or module\_install() or module\_enable $types = node\_type\_get\_types(); node\_add\_body\_field($types\['my\_content\_type\_name'\], $label='Body');
> 1 votes

# Answer
insert directly into the field\_config\_instance table: mysql\> INSERT INTO `{{database}}`.`field_config_instance` ( `field_id`, `field_name`, `entity_type`, `bundle`, `data`, `deleted`) VALUES ( '2', 'body', 'node', '{{your-content-type}}', '{{blob-data}}', '0');

I copied the blob data separately from an existing content type via MySQLWorkbench and omitted 'id' from the query, which is an auto-increment field
> 1 votes

# Answer
Just found out that if you simply have another content type created and has the default BODY field on it, you can simply add it to your needed content type from the **Add existing field** section on the **Manage fields** tab.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: Deny access to non-existing sub-paths that bubble up to an existing node
I have a drupal site with a page 'About us' (url: `example.com/about-us`). So when you type the url it correctly opens up the 'About Us' page. But if you append that url with any garbage value or a sensible word (eg: `example.com/about-us/adfasd` OR `/home`) it still opens up the 'About us' page.

Is there a way to restrict this? That means the user should get an error (something like 'Page not found') if he enters a url for a page which is not valid or if there is not content for that url on the website.

Any kind of help or guidance is greatly appreciated.

# Answer
check admin/config/system/site-information and configure, in my site it's empty and all wrong urls get a drupal msg that the page couldn't be found.
> 0 votes

---
Tags: nodes
---


# Question
Title: How do I get a list of nodes that have a reference to a given user?
I can get a node's referenced users like so:

```
$users = $node->get('field_allowed_editors')->getValue();

```

But how can I get a reverse list? Getting all the nodes that have a certain user referenced?

# Answer
> 1 votes
You can use an entity query:

```
$nids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('field_allowed_editors', $userid)
  ->execute();

```

This will result in an array with all node id's that match the conditions.

---
Tags: users, 8, nodes
---


# Question
Title: How do I debug connection problems while testing Deploy module while using local host?
I'm attempting to properly set up between the Deploy Module between these two by follow these instructions. I've used Drush QuickDrupal to set up two new Drupal 7 instances.

```
$ drush qd d7-deploy-stage
$ drush qd d7-deploy-live

```

Initially, I ran them as on the same host machine via PHP's internal development server

```
$ php -S localhost:8000 # d7-deploy-stage
$ php -S localhost:9000 # d7-deploy-live

```

The end point is listed as `http://localhost:9000/services/rest` and the authentication (and only user) is `admin` with password of `admin`.

However upon a `cron run` on the d7-deploy-stage instance I

> DeployAuthenticationException: Authentication error:-111 Connection refused in DeployAuthenticatorSession-\>deploy()

**Question(s):** How would I begin to debug this? Since the error reads "connection refused", I'm also curious if I start the servers with a fully qualified domain name (or my machine's IP) or if the port numbers an issue in the addressing

**What I've tried so far:**

*The Patch:* The '#31' has failed with the following output `patch -p1 < deploy-404_CSRF_error-2017767-31.patch`

> patching file plugins/DeployAuthenticatorSession.inc Hunk #1 FAILED at 76. 1 out of 1 hunk FAILED -- saving rejects to file plugins/DeployAuthenticatorSession.inc.rej

**Update**

On both instances, based this answer below, I downloaded the 'add start up .ht.route' patch, applied and restarted

```
wget https://www.drupal.org/files/issues/add_a_startup-1543858-58.patch
patch < add_a_startup-1543858-58.patch to each instance.
php -S public-ip-number:8000 .ht.router.php # stage
php -S public-ip-number:9000 .ht.router.php # live

```

The error on `drush cron` has changed

> WD deploy: DeployAuthenticationException: Authentication error: 404 Not found : Could not find resource user. in DeployAuthenticatorSession deploy() (line 76 modules/deploy/plugins/DeployAuthenticatorSession.inc).

# Answer
> 1 votes
There are few issues with your examples.

1. You're missing routing-script for the built-in PHP web server. It's recommended to use since you're using PHP built-in web server and by default it may have some problems handling certain clean URLs (for example URI containing dots are treated as direct files). So you should apply this patch from #1543858 and re-run you server as below (same file you can use for both Drupal 7 & 8):

```
php -S localhost:8000 .ht.router.php

```
2. You should use `-l` in order to specify URI of the Drupal site to use, so your code knows what's your proper hostname (since the fail is related to the connectivity issue).

```
drush -v -l http://localhost:8000/ cron

```

If you still have *Connection refused*, you should check where the code is trying to connect and check the connection (e.g. wrong configuration or firewall in place). To debug the connectivity issue, on OS X you can use `dtruss`, on Linux this can be debugged by `strace`, e.g.

```
strace -e trace=network -fp $(pgrep -fn php)

```

---
Tags: 7, deployment
---


title: Products - Add to cart

text:
# Question
Title: Products - Add to cart
I need some advice.

My client has a website with loads of products. Now the client want the ability to add products to a cart, and instead of buying, they want the products to be mailed.

How can I acheive this. I took a look at the commerce module. This module is amazing. I did some research and found this article saying I can achieve what I want with the rules module.

This is awesome. But drupal commerce has its own set op products that you need to add inside the store. I need to use products already created. As well as add options such as colors and sizes that also needs to be displayed in Select lists.

Is there a way that I can get this feature with existing products? Or just add the cart button to my nodes?

Thanks.

# Answer
It depends on how your node 'products' are setup. In Drupal Commerce, 'products' are a fieldable Entity Type and each bundle of that entity type is a different product with different sets of fields.

One possible solution would be to check out the Migrate and its ecosystem of other modules to see if there would be a way to convert your product Content Type to a Product Type.

Note that in the native Commerce workflow, you also need a Product Display node to act as a container for products to display them to the end user. Think of the Product entity as a single product option \[in the example of a t-shirt it could be "X-Large Blue"\] and the Product Display node is the wrapper that contains all options to display as a single "product" to the user.
> 1 votes

---
Tags: nodes, commerce, rules, emails
---


# Question
Title: if term reference is value X in tpl.php file
I want it so that in my page.tpl.php file if the user has selected "Standard" as the "Page Type" term reference it prints an extra bit of html.

I tried something along the lines of the code below but have not had any luck so any help would be greatly appreciated.

```
<?php $page_type = field_get_items('node', $node, 'field_page_type');
if ($page_type == 'Standard') {
    print "worked";
} ?>

```

If I print the "field\_page\_type" value further down the page it prints "Standard" on the page but if I use the if statement above it doesn't print the "worked" result.

I am using Drupal 7.

# Answer
> 1 votes
The above use of `field_get_items('node', $node, 'field_page_type');` is going to return an array that looks like:

```
Array
(
    [0] => Array
        (
            [tid] => 549
        )

)

```

But what you want is the value of the term so you'll need to do the following:

```
<?php $page_type = field_view_field('node', $node, 'field_search_type');
if ($page_type['#items'][0]['taxonomy_term']->name == 'Standard') {
    print "worked";
} ?>

```

---
Tags: 7, theming, hooks
---


# Question
Title: Strange error in status reports en unable to safe my taxonomy term url-alias
When I go to `admin/reports/status` I see this error (see image).

Also I am unable to safe my taxonomy term url-alias? What does this error mean and how can I fix this?

# Answer
You can safely ignore this.

See https://www.drupal.org/node/2661178 and the core issue linked there for details.

Nothing is broken, the entity definition change tracking just gets a bit confused.
> 0 votes

---
Tags: taxonomy-terms, 8, path-aliases
---


# Question
Title: Difference between browser session and Drupal session
After reading this question over here from 2014, I'm left wondering:

Is there any benefit, security concern, or real reason to use Drupal's session manager class over the browser session `$_SESSION[key]`?

Specifically wondering about the Symfony session API that was mentioned in the above linked question and whether or not that provides any benefits over the way i'm storing and accessing session data.

'The Drupal Way':

```
$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

```

How I'm currently doing it:

```
$_SESSION['three_minute'] = array();
$_SESSION['three_minute']['utility'] = $form_state->getValue('utility');

```

# Answer
> 6 votes
What you are describing is not Drupal session vs. Browser session. There's just one session, always managed by Drupal (partially by using Symfony code. But it's still Drupal).

The (private) tempstore is just a custom storage that used to be provided by ctools in 7.x. For anonymous users, it actually requires a session to be present, as it uses the session ID to identify the entries.

The main difference is that session data is always loaded, on every request. While for the tempstore, you control when and what is loaded. If you have data that is small and you need on many/all pages, use the session directly. If you have big objects, consider using a temp store.

Drupal itself uses the tempstore for example to store node objects for the preview feature and views while editing them.

---
Tags: 8, sessions
---


title: Can I use MS SQL?

text:
# Question
Title: Can I use MS SQL?
I don't want the whole of Drupal (Drupal itself plus SQL) on the same server. I need Drupal on a normal LAMP setup connecting to a db hosted on a separate server using MS SQL. Is it possible?

I've seen there's a MS PHP drive for Drupal to work, but the drive is a Windows executable file, so I guess it won't work on a Linux box.

Alternatively, is there any difference in Drupal itself for it to be able to connect to MS SQL?

# Answer
Out of the box there is practically no support for MSSQL. Drupal 7 there was an attempt to support it driven by the Commerce Guys, but that work migrated to a contrib module and is not in core. Here is a quick rundown of compatibility.

**Drupal 6**: Not possible

**Drupal 7**: Possibly with the MSSQL Layer module called SQLsrv. But be prepared for issues when using contrib modules, some will not work because many modules write out SQL commands and run them with db\_query instead of the abstraction layer for performance reasons - especially complex queries.

**Drupal 8**: Not possible out of the box. There is a third party module that provides a driver for MSSQL.

If you really want to get the most out of Drupal with as little headache as possible, run MySQL or even MarianDB on Windows.
> 7 votes

# Answer
Drupal 7 and 8 have full MSSQL Support.

Currently, PHP7 is also supported and Linux Support for PHP7 is comming soon.

My recommendation is that - if you are using MSSQL - go for a full MS software stack.

To install Drupal on SQL Server see this tutorial:

http://www.drupalonwindows.com/en/blog/installing-drupal-windows-and-sql-server http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows
> 2 votes

# Answer
By default Drupal supports MySQL, PostgreSQL and SQLite. But you can try to extend existing classes and write your own for MsSQL (or find some existing). I don't think that MsSQL can work on Linux, but maybe via emulator.
> 1 votes

---
Tags: 7, database
---


title: Problem with the template of a view

text:
# Question
Title: Problem with the template of a view
I created a template to customize labels views. But the fields are not displayed between labels.

Here are the views-view-field--sitemap--views-data-export--field-image.tpl.php :

```
<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

echo $fields["field_image"]->content;

```

and here are the views-data-export-xml-header--sitemap.tpl.php :

```
<?php print '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
?>

```

and the result :

```
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">  <url>
    <loc>http://www.s1biose.com/boutique/produit/savon-d-alep-artisanal-bio-pure-olive</loc>
    <image:image><image:loc>http://www.s1biose.com/sites/default/files/image/boutique/savon-d-alep-artisanal-bio-pure-olive-photo-1.jpg</image:loc></image:image>
  </url>
  <url>
    <loc>http://www.s1biose.com/boutique/produit/savon-d-alep-artisanal-bio-5-de-laurier</loc>
</urlset>

```

The result should be :

```
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
  <url>
    <loc>http://example-1.com/sample.html</loc>
    <image:image>
      <image:loc>http://example-1.com/image_1.jpg</image:loc>
      <image:title>title image 1</image:title>
    </image:image>
    <image:image>
      <image:loc>http://example-1.com/image_2.jpg</image:loc>
      <image:title>title image 2</image:title>
    </image:image>
  </url>
  <url>
    <loc>http://example-2.com/sample.html</loc>
    <image:image>
      <image:loc>http://example-2.com/image_1.jpg</image:loc>
      <image:title>title image 1</image:title>
    </image:image>
    <image:image>
      <image:loc>http://example-2.com/image_2.jpg</image:loc>
      <image:title>title image 2</image:title>
    </image:image>
  </url>
</urlset>

```

# Answer
> you know how I can view the full URL of the image?

I found it, replace your 1st line with:

```
$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

```

> thank you it works but it displays 1 image instead of 3

**In views click on your image field**, click on *MULTIPLE FIELD SETTINGS* **uncheck** display all values in the same row.
> 1 votes

---
Tags: views
---


title: Help with view on multiple pages

text:
# Question
Title: Help with view on multiple pages
I experimented for a few hours with drupal (tried contextual filters) and searched across the internet, but couldn't find a solution for my problem. (I'm not a "drupal engineer", so maybe it's very easy to solve this problem, but I couldn't).

I have view that I want to use on multiple pages on our drupal site. If the user browses to http://www.mywebsite.com/######, is it possible to display that view, but showing only nodes that contain "######" in a specific field in the content type displayed by that view?

edit: when ####### isn't found in that field (if 'ts available in the content type), of course it should not show the view. When ######### isn't provided (http://www.mywebsite.com/), it should display the view without te filter....

# Answer
> 0 votes
You did not specify if this is a block view or a page view.

If it's a page view, you have to use `/something/%` as your path.

1) Add your field in question as a contextual filter. (I used title as an example)

2) Use *Provide a default value*

* *Raw Value from URL*
* Path is 1 assuming its `yourwebsite.com/####`. Path is 2 if `yourwebsite.com/something/####`

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


title: Doing A/B testing

text:
# Question
Title: Doing A/B testing
I would like to do some A/B testing.

I would like to have 2 slightly different templates and different modules and paths for each template and then I would like to do to the visitors 50% template A + modules and logics etc. and 50% of the visitors template B + own modules.

It would be based on user IP and some simple logic half visitors will be seeing first template and the second half of the visitors will be seeing the second template with different settings.

An important thing is that a user (based on IP or login) should see the template he saw for the first time forever not only for his session.

I am not sure if I have to install two Drupal versions with two databases and use `.htaccess` or something to make the decision.

Or I have looked for modules but found only this one: http://drupal.org/project/multivariate

Which seems too light.

Any advice which way to choose and how to approach this problem.

# Answer
I would recommend you to consider testing http://visualwebsiteoptimizer.com/ for your use case. There is also a module http://drupal.org/project/visual\_website\_optimizer which makes the integration easier for you.

From the FAQ page of VWO you can see that

1. Uses cookies to track visitors
2. Visitors see same variation even on repeat visits

So that should solve your problem. To make the decision of which variate should be visible to which users, there is sleek UI for selecting those conditions.

However if you want to do the things, the Drupal way then you can use http://drupal.org/project/multivariate which gives you more control. Multivariate is more like Rules or Context module. You have a set of conditions(is the user using X browser, is his IP originating from Y country and so on) and when those conditions are met a set of actions can be performed(serve his multivariate A instead of B).

> An important thing is that a user (based on IP or login) should see the template he saw for the first time forever not only for his session.

For making sure that above condition is met you can increase the life of the cookies set. If you want to track the users before loggin in(anonymous users) and after they have authenticated, then you might need to do some custom coding.
> 6 votes

# Answer
There are a few options for A/B testing a Drupal website, and all options will run the simple test requirements of this question (splitting traffic with specified percentages and keeping visitors in their initial experiences). The two basic approaches are using a paid external service to run the A/B tests or using a fully Drupal-integrated module. Here are the options for each approach:

**Drupal Modules**

* A/B test: Available for D7, this module is described on the project page as a "low-level API for implementing A/B tests in code". The tests are implemented with custom PHP, which requires knowledge of Drupal data structures and hooks on the PHP side. Also note that an HTML cacheing layer will complicate matters (if not all site visitors are hitting backend PHP). This module has not been updated since April 2015 and has not had a stable release, but there are 30+ sites that currently report using it.
* Multivariate: As Gokul mentioned, Multivariate allows tests to be configured through in the admin UI, without needing any custom code. It is available for D7, but has not had a stable release and hasn't been updated since October, 2013. It does have the highest current usage of any non-external A/B testing module with 100+ sites currently reporting that they use it. As it is a backend solution, an HTML cacheing layer could prevent usage of this module.
* A/B Test JS: This is a new module for D7 and D8 that runs tests in JavaScript and exposes an admin UI for test creation. It does not currently have sites reporting usage, but is actively being developed and maintained. Custom JavaScript snippets are required to create tests, and evaluation of the tests must be done in a separate analytics platform like Google Analytics.

**External services**

The external options run all testing logic on the frontend (in JavaScript) and can be implemented with either direct inclusion of the scripts, or through Drupal modules when available.

* Optimizely: I have not used Optimizely, but I do know that is widely used and considered state-of-the art for A/B testing. It includes a WYSIWYG UI for creating the test modifications, so tests can be created without any code. The *Optimizely* Drupal module is available in D7 and D8, and has the most usage of any of the A/B testing options.
* Visual Website Optimizer: I don't have experience with this either, but it does include a WYSIWYG interface for creating tests and interface for viewing results. A Drupal module that includes the VWO javascript in your site's pages is available for D6, D7, and D8, and also has a significant amount of usage on Drupal.
* Adobe Test and Target: From personal experience with Adobe T&T, it has the WYSIWYG interface for creating tests, but I found the UI quite buggy, and worst of all, many of our tests caused "flicker" for site visitors, where the original page flashes before test modifications are implemented. The *Test&Target* Drupal module also has very little usage, and is only available in D7.
* Google Content Experiments: As a part of Google Analytics, Content Experiments are not as fully featured as the options above, but I believe the service is free and would satisfy the requirements of this question. The *Content Experiments* Drupal module is available in D7.

**Conclusion**

Long story short, this use case can be satisfied with any of these solutions so long as they function as intended. More specifics would be needed to find the best solution. In general, I prefer to use Drupal A/B Test JS, but that's also because I made it :)
> 6 votes

---
Tags: theming, users, testing
---


# Question
Title: Flush cache of individual node when updated?
Is there any way to have an individual node's cache flushed if it gets updated? (instead of having to flush drupal's entire cache to show the changes to anonymous users immediately? (Rules or a module maybe?)

# Answer
If you are using node\_save, cache for the particular node will be cleared automatically. If you are using any other method to save the node then use the following,

```
entity_get_controller('node')->resetCache(array($node->nid));

```
> 8 votes

# Answer
This worked for me. The entity\_get\_controller('node') call provided in the other answer didn't work.

```
// Clear field cache
$entity->type = 'node';
$entity->id  = 54321;
cache_clear_all("field:$entity->type:$entity->id", 'cache_field');

```
> 6 votes

# Answer
I believe Views Custom Cache module could be your solution.

Install "Views Custom Cache" module as usual.

### Views settings:

Your first argument is **Node ID**.

Add second argument **Custom Global: NULL** argument - which is ignored and will not efect the view in any particular way - exept caching!

Ensure that this argument is not present when view is generated so that *"When the filter value is NOT available"* rule will be triggered.

If your view has path for example "`node/nid`", `nid` is available to you as `arg(1)`.

**Note:** Adjust `arg()` value (0, 1, 2...) to match your use case in code snippet below.

In Global Null argument: When the filter value is NOT available / Provide default value / PHP code enter:

```
$node = node_load(arg(1));
return $node->changed;

```

Now your second argument (Global Null argument) will always return fresh node updated date (timestamp), and you can use "Custom cache: view's all arguments" cashe option.

Global Null argument will be nicely ignored and will not take any efect on view rendering, but it will make effect on cache - making it unique for specified Node ID + Node updated date pair. If node is updated, new Node updated date (timestamp) will be returned as second argument to the view which will cause automatic View cache refresh for specified Node ID.

Answer reference: https://www.drupal.org/node/2559607#comment-10436015
> 1 votes

---
Tags: 7, caching
---


title: HTML tags in Taxonomy Term Name

text:
# Question
Title: HTML tags in Taxonomy Term Name
I'd like to emphasize a character in the Taxonomy Term Name field. Text format is Filtered HTML, but the name (=title) is being displayed like this:

`AK ORDERED SETS, <EM>N</EM>-UPLES, ORDERED ALGEBRAIC STRUCTURES`

Any ideas?

Thank you very much!

# Answer
Check the setup text format: Filtered HTML, here

```
admin/config/content/formats/[your_format]

```

The settings will filter the desired output. Or just choose Full HTML (if configured properly) ;)
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to assign a user a role during registration using Rules and Profile 2?
I am using the Profile 2 module to select roles during the registration process. So a user selects a role (using a radio button) and then a rule fires to give the user the role that was selected.

Here is the rule I'm using:

```
    { "rules_give_user_a_role_after_registration" : {
    "LABEL" : "Give user a role after registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "account:profile-main:field-user-role" ],
          "value" : "Emporos"
        }
      }
    ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } }
    ]
  }
}

```

The issue is that the role is not assigned to the user. Any idea why not?

# Answer
> 1 votes
If "*...the role is not assigned to the user...*" (as in your question), it must be that your Rules Action is not performed. And if that's the case, then that must be because your Rules Condition is not satisfied (true).

And the reason why your Rules Condition is not true, is pretty sure because you should add another Rules Condition `Entity has field` (related to your additional field in the Rules Condition you already have). And make sure to add that `Entity has field` condition BEFORE the Rules Condition in which you want to perform that "data to compare".

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

# Answer
> 0 votes
Anyway I found a solution without using Rules and Profile 2.Instead using the Auto assign role module https://drupal.org/project/autoassignrole It gives you the ability to select a role during registration.

---
Tags: rules, users
---


# Question
Title: Use different comment template for replies-to-top-comment
I tried to make StackExchange-like comment section with different template for the comment replies. I create two template for both top-level comment and its replies. This is the result of the two `comment.tpl.php` file rendered and then collated in GIMP.

This is `comment.tpl.php` used for top comment contained in cyan box.

```
<div class="user-comment">
  <div<?php print $attributes; ?>>
    <div class="user-identification">
      <?
        print render($avatar) . "<br/>";
        print $commenter_name . "<br/>";
        print $creation_date;
      ?>
    </div>
    <?php
      hide($content['links']);
      print render($content['comment_body']);
      print render($content['links']);
    ?>
  </div>
</div>

```

While this is `comment.tpl.php` used for comment reply contained in yellow box.

```
<div class="user-comment">
  <div<?php print $attributes; ?>>
  <?php
    print render($content['comment_body']);
    print " - " . $commenter_name;
    print render($content['links']);
   ?>
  </div>
</div>

```

If i use one of these template, it will effect ALL the comments as shown below.

I know I can change the style rudimentarily via theme css as suggested in this question, but going by this route means that I have to create one-size-fit-all template for both case that won't be pretty.

My question is: Is there any template file I missed or any other strategy that I can employ to make separate template that will target only the replies-to-top-comment?

# Answer
I manage to solve this problem by exploiting the `pid` (parent ID) value in the `$comment` variable. First, I check if the corresponding comment is a top-level comment. It is a top level comment if the `pid` value is `0`. The code inside `comment.tpl.php` so far is:

```
if ($comment->pid == 0) {
  // Top level comments code here
} else {
  // Replies to comments code here
}

```

The code above will split the template programatically already, but it will be better if I worked at two separate files for the two cases. To do this, I used `drupal_get_path` function to point every case inside `comment.tpl.php` to their corresponding template.

In my case, I create these two templates inside my theme folder:

* `/templates/comment/comment-top.tpl.php` for the top comment
* `/templates/comment/comment-reply.tpl.php` for the replies

The code inside `comment.tpl.php` then become:

```
if ($comment->pid == 0) {
  include drupal_get_path('theme', 'mytheme') .
    '/templates/comment/comment-top.tpl.php';
} else {
  include drupal_get_path('theme', 'mytheme') .
    '/templates/comment/comment-reply.tpl.php';
}

```

Of course change the `mytheme` in the code to your theme name.

To finish off, I pasted the template I posted above in the question to the corresponding template. It will render the template properly with all the variables you define inside the preprocesses function working.
> 0 votes

---
Tags: 7, theming, comments
---


# Question
Title: Autcache + Varnish modules installed but cache tables growing
I have a site in Drupal 7, multilanguage and multidomain, and when I do a weekly manual database backup (apart from the automated ones), I see that the size of the mysqldump file is of about 200 Mb. When I run the cron (which is set automatically to once each 3 hours), clear the cache, and then, finally, TRUNCATE all tables with prefix "cache\_", the size of the dumped file reduces 4 fold to 50 Mb. I have Authcache and Varnish modules activated, so I thought that the cache was functioning in another way. How is it possible that the cache tables are so full, even with cron updating each 3 hours? May I have something wrong in the configuration?

# Answer
Varnish should not ideally affect your cache tables, not sure about auth\_cache. You should try the reverse approach to figure out what is wrong, check which of your cache tables is growing abnormally and then do bit of digging around to find what module/s is responsible for stashing cache data in those tables.

There is a well-known issue with cache\_form table in D7, it can grow abnormally for some live sites. Check this issue, Cache Form table size is enormous.

If you find your cache\_form also huge you can use one these modules to help you to periodically clear it, https://www.drupal.org/project/optimizedb or https://www.drupal.org/project/safe\_cache\_form\_clear.

Hope this helps.
> 2 votes

---
Tags: 7, database, proxies, caching
---


# Question
Title: Rest full web service API url is changed in d8
I have rest service url for a node in d6 as

```
https://192.168.1.236/rest_endpoint/node/1140.json

```

but the same url in drupal 8 is not working at all , for d8 i have to give

```
https://192.168.1.236/rest_endpoint/node/1140?_format=json

```

here **1140 is the node id** and **192.168.1.236 is the base url** .

As the url is changing i have to modify many scripts .What may be the reason for this ? or is there any workarounds ?

# Answer
> 2 votes
From the related issue:

> Drupal core no longer uses accept headers for routing but rather rely on a \_format query parameter, **because browser, (reverse) proxy and CDN support is very poor, and hence could lead to severe bugs**. See See #2364011: \[meta\] External caches mix up response formats on URLs where content negotiation is in use for more background.

So it was a conscious decision, to help prevent common bugs out in the wild. I wouldn't advise trying to find a workaround, the motivation for changing it is sound. But if you want/need to, perhaps just a simple rewrite rule that would take requests for `*.json` and forward them on to `*?_format=json` would suffice.

---
Tags: 8
---


# Question
Title: Use db_select with multiple conditions of which one needs to apply
My question is not a duplicate and it has complex conditions. Please let me explain. In my second condition, first I need to check if number value is correct (in first condition I checked complete opposite). If so, then check if there's a value in email column. Then show error message if there's a value in email column. My problem is I need to write first query (already done by me) and second query under the same 'db\_select'

Checking for email value only activates if webform value matches a value in 'number' column.

---

I have a table containing two columns namely, 'number' and 'email'.

I need to run a `db_select` query to display same error message when a webform is submitted. My conditions are as follows:

1. Show error message if number value provided by webform does not matches a value in 'number' column
2. Show error message if number value provided by webform matches a value in 'number' column but corresponding 'email' column is not empty.

So far I'm able to show error message for the first condition.

```
db_set_active('mydatabase');
    $query = db_select('mytable', 'c');
    $query->fields('c', array('number','email_address'))
    ->condition('number', $phoneval, '=');
    $result = $query->execute()->fetchAll();

if (empty($result))
{
    form_set_error('phone_number','We have no record of that Assessment Number');
}

```

How can I show the same error message for condition 2? I don not want to query the database again and thinking of using for `db_or` this.

Thanks

# Answer
Syntax for db\_or :

```
$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

```

For More Information
> 1 votes

# Answer
```
db_set_active('mydatabase');
$query = db_select('mytable', 'c');
$query->fields('c', array('number','email_address'))
->condition('number', $phoneval, '=')
->condition('email_address', $mailval, '=');
$result = $query->execute()->fetchAll();

```

You could use nested if

```
if (empty($result)) {
  // do print_r($result);
  // here you will get the result in array
   if (empty($result['number'])) {
    form_set_error('phone_number','We have no record of that Assessment Number');
   } else if(empty($result['email_address'])) {
   form_set_error('email_address','We have no record of that email');
   }
}

```
> 0 votes

# Answer
Can't you just use PHP for this?

```
db_set_active('mydatabase');
  $query = db_select('mytable', 'c')
    ->fields('c', array('number','email_address'))
    ->condition('number', $phoneval, '=');
  $result = $query->execute()->fetchAll();

// Don't forget to set the db back to default
db_set_active();

if (empty($result)) {
    form_set_error('phone_number','We have no record of that Assessment Number');
}
// We found a record with matching number... check e-mail
else {
  // Grab the first item in array
  $result = reset($result);
  // If e-mail's not empty, show error.
  if (!empty($result->email_address)) {
    form_set_error('phone_number','We have no record of that Assessment Number');
  }
}

```
> 0 votes

---
Tags: database, webforms
---


title: custom user login/register menu tabs

text:
# Question
Title: custom user login/register menu tabs
I'm making a website with 2 different kind of users. using the Profile2 module, and i'm kind of stuck.

1. Tourists who register with the normal `user/register form`.
2. And Guides who register with a custom `guide/register form`.

On the homepage we have a simple user menu with login and register button.

I want to customize the tabs on the user/register page to have two tabs: `Register as tourist` and `Register as guide`

So I want the tabs of `login` and `request password` to be gone on the registration forms.

**BUT** I do want the `login` and `request password` tabs on the login page.

# Answer
> 0 votes
You can add tpl file for user registration Example:

```
function THEME_NAME_theme() {  // Add this function in template.php
    $items = array();
    // create custom user-register.tpl.php
    $items['user_register'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'THEME_NAME') . '/templates',
        'template' => 'user-register',
        'preprocess functions' => array(
        'THEME_NAME_preprocess_user_register'
        ),
    );
return $items;
}

```

According to role. add changes in user-register.tpl.php. You can refer link to add user-register.tpl.php.

# Answer
> 0 votes
It sounds like you're wanting the use case covered by the Profile2 Registration Path module:

> By default, the Profile 2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

Anything else, might need to be covered by a form/menu altering custom module or Tab Tamer.

---
Tags: 7, users
---


# Question
Title: Set weight for JavaScript files loaded via theme.libraries.yml?
Im loading a JavaScript file via my theme's libraries.yml file. How can I change the weight of this file?

I need the file to load before the core and module's JavaScript files. If I set `header: true` then this happens, but I still want to load the file at the bottom of the page.

# Answer
You need to try this with in libraries.yml file

```
js:
    js/foo.js:
    js/bar.js: { weight: N }

```
> 10 votes

---
Tags: theming, 8
---


# Question
Title: How to Determine view type (content, user taxonomy, etc)
I have inherited a site and I am trying to customise and replace some of the views. I have been told that there are views of various types, content, user, taxonomy, search index, etc. Where in the view after it has been created does it indicate the type of view.

# Answer
> 1 votes
If you are already editing the view, it is also in the Title (so you don't have to navigate away from editing).

# Answer
> 0 votes
On the /admin/structure/views views listing page, each view has a type attribute listed.

---
Tags: views
---


# Question
Title: drupal facebook autopost working but post are not visible to public
I am using Facebook Autopost module and rules module to automatically post content to my facebook page when a new content in created. The post are appearing in my facebook page but they are not visible to public. What am I doing wrong.

# Answer
You need to take your app out of development mode and make it live to the public. All of your previous posts will then appear to their appropriate audiences (and so will future posts).

You can do this by going to https://developers.facebook.com, going to your app's dashboard, then to App Review. At the top there is a Yes/No field for "Make app public?" Set it to yes.
> 0 votes

---
Tags: rules, social-network
---


# Question
Title: Select fields from three tables using db_select()
```
SELECT u.`uid`,u.`name`,f.`field_user_first_name_value`,l.`field_user_last_name_value`,u.`mail` from users as u, field_data_field_user_first_name as f, field_data_field_user_last_name as l where f.entity_id = u.uid and l.entity_id = u.uid limit 10

```

Is there a way to write this using db\_select function?

# Answer
> 0 votes
I have used this.

```
$query = db_select('users', 'u');
$query->join('field_data_field_user_first_name', 'f', 'f.entity_id = u.uid');
      ->join('field_data_field_user_last_name', 'l','l.entity_id = u.uid');
$result = $query
  ->fields('u', array('uid', 'name', 'mail'))
  ->fields('f', array('field_user_first_name_value'))
  ->fields('l', array('field_user_first_name_value'))
  ->execute()->fetchField();

```

# Answer
> 0 votes
Try This

```
$query = db_select('users', 'u');
$query->join('field_data_field_user_first_name', 'f', 'f.entity_id = u.uid');
$query->join('field_data_field_user_last_name', 'l','l.entity_id = u.uid');
$result = $query->fields('u', array('uid', 'name', 'mail'))->fields('f', array('field_user_first_name_value'))->fields('l', array('field_user_first_name_value'))->execute()->fetchField();

```

---
Tags: database
---


# Question
Title: How to fetch content data based on Node reference field into a view
i am attempting to fetch the records based on node reference fields into a content type page.

i added node reference fields "news" & "Articles" (and many more) into my "Industry" Content type:

Now i've created a view with a filter (Content type= industries). Find the snap of the view here:

i want to list down all the selected/inserted news and articles (along with their content data) into the view. (currently its fetching only titles but with lot of repetition of the titles from both content types.)

# Answer
> 0 votes
I think you can either construct your news and article views as attachments and attach them to your view, or you can bring the content for news and articles in field by field in the main view.

Using attachments might help you to end up with less repetition without having to use query aggregation.

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


# Question
Title: Pass contrib module tokens to custom event in rules
I am creating a custom rules event using hook\_rules\_event\_info. This custom event is extending the features of the Stripe Subscription contrib module. The custom rules event is working fine so far.

Stripe Subscription creates several tokens for use within the module using hook\_tokens. Is it possible for me to pass the tokens available in the module onto the custom rule event I have created so I can use them in the actions?

The event rule I have created looks like this:

```
function stripe_subscription_rules_event_info() {
  return array(
    'stripe_subscription_event' => array(
      'label' => t('A user subscribed'),
      'module' => 'stripe_subscription',
      'group' => 'Stripe Subscription',
      'variables' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who is subscribing.')),
        'plan' => array('type' => 'text', 'label' => t('The purchased plan.')),
        'subscription_action' => array('type' => 'text', 'label' => t('The subscription acton')),
      ),
    ),
  );
}

```

# Answer
When the Rule gets invoked, you can send any number of parameters along with it. Just make sure they match the expected data type.

```
rules_invoke_event('stripe_subscription_event', $acting_user, $plan, $stripe_subscription_event);

```

This will trigger the Rule and send the variables along. It is up to you call this function and obtain these values somehow.

Since your Rules description is *A user subscribed*, I suppose you should the submit function of that event to invoke the Rule. You might be able to grab the values from the `$form_states['values']` array. I have no idea what the Stripe subscription module does, so I am not sure how you should obtain these values.

I don't think you can use tokens. Those are specifically for rendering content and I have never seen them used in code. (You might obtain the values by copying some of the logic though.)
> 0 votes

---
Tags: rules, tokens
---


# Question
Title: What is the path for form elements which are ajax-enabled
I am working on the quiz module.
I have to modify the form `node/add/multichoice` by hiding some of the form elements in it.
With the help of krumo function of devel module, I am able to find the correct form elements and set `['#access']` to `FALSE` in order to hide them.
All this is done in a custom module using the `hook_form_alter()`.

But the problem is that I have to hide advanced fieldset under alternatives. The path for form element for advanced fieldset is thus like below :
`$form['alternatives'][0]['advanced']`
`$form['alternatives'][1]['advanced']`
But there is an option of add more alternatives.
What is the path for form elements which are ajax enabled.

# Answer
```
foreach (element_children($form['alternatives']) as $delta) {
  $form['alternatives'][$delta]['advanced']['#access'] = FALSE;
}

```

Something like this.
> 1 votes

---
Tags: ajax, quiz
---


# Question
Title: Autocomplete not working for Search API with Solr - Drupal 7
I have these modules installed with Drupal 7:

* search\_api
* search\_api\_solr
* search\_api\_autocomplete

There is a view configured for search results with exposed full-text search filter, based on the index in Solr set up via Search API. The view is working well, however autocomplete function isn't working at all, no glimpse of it present. Are there any special settings for autocomplete that may need to be activated for the view?

# Answer
The README.txt file in the search\_api\_autocomplete module provides the following information:

* Necessary setup

After having installed and enabled the module, you have to do some administrative steps to activate the autocomplete functionality. Autocompletion can be enabled and configured for each search separately.

To activate autocompletion for an index's searches, go to the index's „Autocomplete“ tab. There, you see all available searches for the index and can enable (and afterwards configure) autocompletion for each of them. All fulltext key fields on the searches should then become autocompletion fields.
> 1 votes

# Answer
I finally found the answer, and I'll share it here in case it helps someone. As @controla says, the help says you need to go into the autocomplete tab in your index settings, and enable the search for your view. It also says that you need to go into the permissions and choose which roles have permission to use autocomplete on the search. The thing that was missing for me is back on the search index autocomplete tab.

After enabling autocomplete for your search view, you need to click edit on the autocompletion index you've enabled and choose the display to enable autocomplete for. Mine was set to master by default, and not page as I needed it to be.
> 0 votes

---
Tags: ajax, search
---


# Question
Title: Workbench moderation repeats "Save and " in the button labels
My workbench moderation label is, for example, *Save as draft*, but the button says *Save and Save as Draft*. How can I get rid of that *Save and* , which is repeated for every button?

# Answer
> 0 votes
**Save and** has been hardcoded in the Workbench Moderation module.

---
Tags: 8, workbench
---


# Question
Title: Where has module-specified HOOK_preprocess_page gone in D8?
I'm making a quick module whilst playing with D8, which I want to preprocess Stylus into CSS. The obvious choice for me, coming from D7, would be to use `hook_preprocess_page`, but it seems to have been removed from D8, or at least only in themes and not modules.

So just to reiterate, I have my module `stylus`, my file `stylus.module` and the function `stylus_preprocess_page(&$variables)`, but no dice.

What would be the best D8 alternative?

# Answer
> 2 votes
This hook has not been removed, there are still preprocess hooks for modules:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook\_preprocess\_HOOK/8.2.x

---
Tags: 8
---


title: How do I get the node ID from the URL?

text:
# Question
Title: How do I get the node ID from the URL?
So far, I came across these 3 functions in Drupal 7, but I am not really sure what the difference between them is, and which is more appropriated to get the node ID in a block preprocess function.

Can you give me any insight?

# Answer
> I am not really sure what the difference between them is

* menu\_get\_object() returns the object associated with the page currently shown. If the code is executed when Drupal is showing the page example.com/node/1, then `menu_get_object()` will return the node object for the node whose ID is 1; if the page being shown is example.com/user/1, then `menu_get_object('user')` will return the user object for the user whose ID is 1.
* menu\_get\_item() returns an array containing an index for each field contained in the "menu\_router" table. This includes:
    + path: the current path of the menu callback
    + load\_functions: an array of function names (like `node_load`) to be called to load an object corresponding to a part of the current path
    + access\_callback: the callback that checks if the currently logged in user has access to the menu item
    + page\_callback: the name of the function that renders the page
    + title: the title for the page associated to the menu item
* drupal\_lookup\_path() is the function that returns you the internal path associated with the alias passed as argument. If "homepage" is the alias associated to example.com/node/1, then `drupal_lookup_path("homepage")` will return `"node/1"`. Path aliases can be associated to any internal paths, not only to node paths.

> and which is more appropriated to get the node ID in a block preprocess function.

If all you want to get is the node ID of the node currently shown, then you just need to use the following code:

```
if (arg(0) == 'node') {
  $nid = arg(1);
}

```

If you need to get the node object, then you can use the following code:

```
if ($node = menu_get_object()) {
  // Use the node object.
}

```

Of those snippets, the second is better, as it returns the correct node object for internal paths such as node/1/revisions/3/view.

Keep in mind that some preprocess functions, such as the ones for the page, or the node, have already a `$variables['node']`. This means that in those cases, you just need to use the following snippet in your preprocess function, without worrying about which function to use.

```
if (isset($variables['node'])) {
  // Check the node ID or other properties.
}

```

For other preprocess functions, check the documentation to see if there is any variable containing the node object. For example, that is the case for `template_preprocess_comment()` which makes `$variables['node']` available to the preprocess functions for comments.
> 67 votes

# Answer
How it's done in Drupal Core's template\_preprocess\_page:

Line 2267 of theme.inc and onwards:

```
if ($node = menu_get_object()) {
    $variables['node'] = $node;
}

```

template\_preprocess\_page uses menu\_get\_object. After that it's just a matter of checking if the node is defined and getting $node-\>nid.
> 8 votes

# Answer
In Drupal 8, you can get url arguments based on what's in the routing.

To get the id alone:

```
$nid = \Drupal::routeMatch()->getRawParameter('node');

```

If you plan to load the node object, you can simply get it this way:

```
$node = \Drupal::routeMatch()->getParameter('node');

```

To find the parameter names, you can use:

```
$possible_parameters = \Drupal::routeMatch()->getParameters();

```
> 5 votes

# Answer
One thing you have to be careful of is path alias.

`drupal_get_normal_path($path)`

to get the current path use the system variable `$_SERVER["REQUEST_URI"]`

(If you are on the node page you can call `$node->uri['path']`, this will return a non-alias path. Then again if you are on the node page, you can just use `$node->nid`.)

this will return node/XXXX

so try something like

```
  $node_path = explode('/', drupal_get_normal_path($path));
  $nid = $node_path[1];

```
> 4 votes

# Answer
```
arg(1);

```

Is not a bad way of doing it. arg() works on the internal path, so it won't be affected by path aliases.
> 3 votes

---
Tags: 7, uri
---


title: User Registration to appear in a block

text:
# Question
Title: User Registration to appear in a block
I want the user registration to appear in a block in some other page than home, let's say a page called "Sign up." What I want to achieve is the following.

>

# Answer
> 0 votes
To achieve according to your use case you have to render login form on node or on page, if i am not wrong.

You can add following snippet to render the login form.

The `user_block_view()` function has this line in it for the `login` delta:

```
if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

```

If you're logged in, the function will return an empty array, which is probably what's happening in your case.

If that's not the reason (and even if it is) you can get around it by calling the form function directly:

```
print drupal_render(drupal_get_form('user_login_block'));

```

There doesn't appear to be any extra access checks done in the form function so it should be rendered regardless of whether you're logged in or not.

# Answer
> 11 votes
Well there is Form Block

> Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Download and install the module. Navigate to `admin/structure/block` You can see Registration form as a block there.

# Answer
> -1 votes
It is pretty simple to handle this. I fixed this on Drupal 7 like below

1. Create block say 'User register form' in content top.
2. Put this code in its body `<?php print drupal_render(drupal_get_form('user_register_form')); ?>`
3. In text format select PHP code
4. In visibility settings, under roles select 'Anonymous user' or who ever who wants to see the form.

---
Tags: users
---


# Question
Title: How to automatically delete all product displays when a product is deleted?
To automatically delete the product displays when a product is deleted, is a feature of the module Auto Product Display, but I don't need that module.

Preferably using the Rules module, I would like to accomplish the same. An issue in drupal.org is present, but currently open.

I'm trying to fetch the referencing product displays:

Trigger: After deleting a Commerce Product

* Fetch entity by property
* Entity is of type: node
* The property by which the entity is to be selected: product (the product reference field)
* The property value of the entity to be fetched: ?? (The node ID of the product is not available to select)

How to get the node ID's of all product displays referencing the product?

# Answer
1) You need the **commerce product id** (which is the one of the commerce product that has been deleted) and not the nid because of the reference you are using. If this parameter is not available you must bring it into scope using a proper validation.

Notice that after deleting the commerce product there is no product id so no products are referencing it. The correct trigger should be "before deleting commerce product" but does not exist by default.

Also, how do you handle a Product display (node) with multiple product variations? Should this node be deleted? There should be an additional condition to check if there are other variations for the same product display. Except if you have a 1 to 1 reference.

2) Another option should be to do the opposite which is to fetch all the nodes (Product displays) that have an **empty commerce product reference**. This is easier to create.
> 0 votes

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


# Question
Title: How to hook into field creation (form successfully processed)?
I need to act after field has been created (new db table). Actually I need to use data from the first field form: field-ui-field-storage-add-form So ideally I need to hook on this form being successfully processed (and its data). Is there any way of achieving it? Something like old hook\_field\_storage\_create\_field

# Answer
> 2 votes
Field storage configs and field configs are config entities hand have the standard hook\_ENTITY\_TYPE\_presave/insert/update/delete() hooks.

```
/**
 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
 */
function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
}

```

---
Tags: entities, 8
---


title: Config entities and views integration

text:
# Question
Title: Config entities and views integration
Do Config entities have views support? What I have:

1. ConfigEntity which have fields: `id, admin_label, display_label, config_options`.
2. ContentEntity with fields: `id, entity_config_id, author`.
3. `entity_config_id` is an entity\_reference to ConfigEntity entity.
4. I use views to show all ContentEntity entities and I outputted fields: `entity_config_id, author`.

**What I need:**

I want to output in views with ContentEntity some additional fields from ConfigEntity(e.g. display\_label). But I can't do it, because I don't see any way how to integrate ConfigEntity with views.

# Answer
> 4 votes
No, there is no views integration for config entities (that's the term you mean, not entity configuration).

The easiest way to achieve what you want is to write custom custom views field plugins and define it in a EntityViewsData class for your entity and then just access the config entity and render what you want.

# Answer
> 3 votes
I have created a module to expose Config Entities to the views. I just pushed the first, initial, commit to my sandbox.

* Install as usual: Config View
* Configure which Config Entities you are going to expose to the view: /admin/config/config\_view
* Create a view: /admin/structure/views/add config entity will show up in the View Settings

Hope it will help.

Config View

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


# Question
Title: Call another view with a single exposed filter
I have a page view which works fine for two cases in the exposed filter (say school one and school two).

However, if school three is chosen in the exposed filter, I want another view to be displayed instead of the page view for school one and school two.

I don't mind if it's a block view or page. Just to call another view because its display is different (a summary of school one and two in addition to school three)

@No Sssweat

# Answer
> Wao! A brilliant idea. But where do i add the JavaScript? In the themes folder or in the created views?

In **template.php** located in `sites/all/themes/yourtheme`

Add the following code at the bottom:

```
function yourtheme_views_pre_render(&$view) {

   if ($view->name == 'view_name') {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/custom.js');
   }
}

```
* replace **yourtheme** with you actual name of your theme.
* replace **view\_name** with your view name.

Also, you'll need to wrap/format your jQuery code like this

/sites/all/themes/yourtheme/js/**custom.js**

```
(function($) {

    //your code goes here

})(jQuery);

```

**PS:** Don't forget to clear the cache to see the changes.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Why does the "Registration List" tab not appear for my events for users with adequate privileges?
I'm using the RNG events module in D8 - when a user with adequate privileges clicks the event tab, they can see and edit all fields, but the "Registration List" tab doesn't show, and they can't see the list of current registrants without the use of a custom view.

This may or may not be connected to the problem I'm having here - How do I limit permissions to manage an event?

# Answer
Figured it out - I had installed and was using the Field Permissions module which takes over any and all other permissions set in any of those other places. Once I edited each field on the event content type with custom permissions everything works great.

This still doesn't solve or explain the missing Registration list tab for admin users per How do I limit permissions to manage an event? though.
> 0 votes

---
Tags: 8, rng
---


# Question
Title: Show menu item to all users, prompt for credentials for anonymous
I have an item in the navbar that links to a page view which can only be accessed by authenticated users.

I want the menu item visible for anonymous users, and also to have them redirected to login if they try to access it. This seems like a common use-case. I see a plethora of modules that accomplish this in Drupal 7, but I don't see any for Drupal 8.

How can I show the navbar for anonymous users that prompts users to login with Drupal 8?

# Answer
As you know, Drupal excludes menu links that the user doesn't have permission to view.

One way around this is to build a menu specifically for anonymous users using the same titles as your other menu, but all pointing to the **/user/login?destination=my/view/path** path. Once the that menu is built, you can create a menu block from it that only displays for the *anonymous user* role.

After adjusting the original menu block such that it only displays for the *authenticated user* role, you will effectively have menu items that display for both roles and prompts a user to login when viewing anonymously. For good measure, you might want to set your Basic site settings such that 403 requests are redirected to **/user/login** in case the user navigates to the views page directly.
> 2 votes

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


# Question
Title: How to exclude the result of one view from another one?
I would like to implement a discussion overview page which displays the hot topics and latest topics, **excluding the hot topics from the latest ones**.

* I have two displays in the same view, each of those operates on the same dataset (listing the same content type).
* The difference between the two displays is the sort criteria only.

Is it possible to set up the display which generates the latest topics list to exclude hot topics? More generally: is it possible to exclude the results of one view from another without making a custom module?

*I would like to get a general answer not involving offsets, because we'll probably face a situation where the sort criterias have to change. Most likely offsetting won't solve my issue there.*

\[Drupal 7 with Views 3.\]

# Answer
> 1 votes
One thing that pops to mind, albeit dirty, is to use php in the argument and do:

* views\_get\_view\_result($name, $display\_id = NULL)
* Loop over resulting nids of your hot topics then explode them out separated by +
* set the argument to exclude these nids.

Not the cleanest solution as it leaves you with php in the DB but it would work.

# Answer
> 1 votes
Have you tried the Views exclude previous module ?

> The Views exclude previous module provides a views filter that excludes nodes that have already been loaded/displayed on the current page.
>
> This is very useful when you have pages with several embedded views, and you want to make sure that a given node only appears once in the page.

# Answer
> 1 votes
I just created a views filter that does just that: Other View Filter.

> The filter provided by this module can be used to exclude a node or multiple nodes from a view, by excluding the results of one view from another one.
>
> 1. In the view from which you wish to exclude selected items, add filter "Content: Other view result"
> 2. Select the view/display combo whose output you want to exclude from the current view.
> 3. Save the view.

---
Tags: views
---


# Question
Title: Use contextual filter global null to pass values to override field result
I come again with new question about Drupal Views and i hope you can help and explain me how to achieve this, I made a page view to display all my content (this works fine) with the following path:

`/car/%/%/%`

Now I want to get all the aliases of that path, for example: `/car/2009/vw/jetta` and then get `%1=2009`, `%2=vw`, `%3=jetta` and then use this to rewrite the output of a field to show something like this:

`<a href="/details/%1/%2/%3"> [name]</a>`,

and with this get my URL like: `/details/2009/vw/jetta`

I see that maybe this is possible with contextual filter: `global: null`. I tried to configure it but i only get the URL with tid's (`/details/10/25/33`) instead of the alias.

Can you explain me how can I configure `global:null` to get the values that i want without affecting my view results?

# Answer
Took me a while but i solved this problem with something like this:

Added 3 Global: Null context filters and then i configured them with something like this:

For global 1: WHEN FILTER VALUE IS NOT IN THE URL\>\>Provide default value\>\>Type:RAW value from URL\>\> Path Component: 1 \>\> Checked Use Path Alias \>\> Apply changes

For global 2: WHEN FILTER VALUE IS NOT IN THE URL\>\>Provide default value\>\>Type:RAW value from URL\>\> Path Component: 2 \>\> Checked Use Path Alias \>\> Apply changes

For global 3: WHEN FILTER VALUE IS NOT IN THE URL\>\>Provide default value\>\>Type:RAW value from URL\>\> Path Component: 3 \>\> Checked Use Path Alias \>\> Apply changes

And with that you can get the values to use them when you want to override a field output using contextual filter values.
> 0 votes

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


# Question
Title: Remove node_view rendered node's title link
I am using the code below to add a form to my node. This renders a page with the node and form on it. Apparently, the node is rendered with its title as a link. I would like to have the node's title without a link. So I tried to change `$node->content`, but there seems to be no value that determines that the node title is a link. how do I change this with code?

```
$form = array();
$node = node_load(24)
$form['offer_form'] = array(
  '#value' => drupal_get_form('dt_offer_entry_form', $node),
  '#weight' => 10
);
$node->content = $form;
return node_view($node);

```

# Answer
> 0 votes
Quoting from this comment, this code worked for the OP.

```
$node_view = node_view($node, FALSE, TRUE);
return '<h2 class="title">Voorstel indienen</h2>' . $node_view;

```

---
Tags: nodes
---


# Question
Title: Using a View as a filter criteria to another view
How can I a view as *is one of* filter criteria for another view, So that it provides a list of possible options?

# Answer
> 1 votes
You can try the Views filter view sandbox module, which does exactly what you are asking for.

> This module will allow to filter results by another view. This other view is either not active on the current site at all, then the view is executed and the result is taken.
>
> If the view on the site was runned already, the result is reused

# Answer
> 0 votes
Views Reference Filter

> This module provides the views filter for entity ID or entity reference fields:
>
> * node ID
> * user ID
> * taxonomy term ID
> * term reference field (Drupal core)
> * entity reference field (Entity reference module)

# Answer
> 0 votes
You can try Other View Filter, which filters a view by another view. Supports nodes, managed files, and users.

---
Tags: views
---


# Question
Title: pass view result from one view to another
I have a view that outputs field content, and outputs one result. There are four additional views that I need to have this result passed to somehow so I can filter the nid of that result out of the possible results for the other four views.

It's the end of the day so I wrote this question in haste, if it is no clear, please ask for clarification. I will review later and update if necessary.

# Answer
> 2 votes
You can use Views field view module ,https://drupal.org/project/views\_field\_view with which you can have a view inside a view,and pass an argument from one view to another.

# Answer
> 0 votes
You might try Views Filter View or Other View Filter, two very similar modules that allow you to filter one view by the output of another.

---
Tags: 7, views
---


# Question
Title: Is it possible to detect access to table on site db table and redirect the db query to a db shared by multiple websites?
I'm working on a project where I use a database that is common to all sites and another that is specific to each. Is there a way to detect access to a specific table on a contrib module (maybe using a hook) and redirect the queries to a table on the db of the shared site?

The contrib module in question is Oauth2.0 server and the table in question is the one where clients are stored, namely oauth2\_server\_client .

# Answer
You don't need to intercept all the query done for a database table. It is enough you change the settings for the database in the settings.php file.

Suppose that the default database definition is the following one.

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

```

If you change it as follow, you change the database used for that particular table.

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => array(
    'oauth2_server_client' => 'otherdatabase.',
  ),
  'collation' => 'utf8_general_ci',
);

```

In this way, you are telling Drupal that for the *oauth2\_server\_client* table, the *otherdatabase* database needs to be used. That database needs to be accessible from the same database user (username, in my example).

Generally speaking, you can alter the query done from a module if:

* The query is a dynamic query
* The module added a tag to that query, such as in the following code

```
$query = db_select('node', 'n')
  ->addTag('node_access');

```

In that case, you could implement `hook_query_alter()` or `hook_query_TAG_alter()`.

In your case, since you want to change the database table used for all the queries to that table, I would change the database definition in the settings.php file.
> 0 votes

---
Tags: database, hooks
---


# Question
Title: Using Features to create module with nested field collections
I'm using Fred Parke's method to create a content type module by first building the content type and then turning it into a feature and exporting it. It works perfectly well, except for when I include field collections that are nested, one inside another. The exported source code doesn't seem to include those, even when I manually select the field\_\* types for export.

Is it possible to export nested field collections in a feature? If the answer is *yes*, how can I achieve this?

At this stage, I'm looking at doing it in Wordpress and embedding the result in an iframe, which should tell you how desperate I am.

# Answer
Turns out I was running into some limitations in the Features export module (including some obscure bugs) and a misunderstanding of part of the return result for hook\_node\_info. All it took was three solid days of debugging and I got it working. So this one can go away now; given its limited usefulness, I don't mind if an admin wants to just delete the whole question.
> 0 votes

---
Tags: entities, features
---


title: Time field not available

text:
# Question
Title: Time field not available
I'm trying to set up a CSV import to create nodes. On the Mapping page for the feed import, several of the fields in my target node type are not listed in the dropdown box to select as a target field. I don't know why.

Some info:

All the fields that aren't showing up are of type Time, added by the cck\_time module. I've not seen any specific issues with mapping this field type, but it does seem like the common denominator here.

I set up the feed, then added extra content fields. The fields that aren't showing up were all added at this later point, although others that were added at the same time are. I've flushed cache several times.

Several of the fields share the same label (ie: "Earliest booking"), although obviously not the same machine name. (For instance, there's one "Earliest booking" field for each weekday, and the field is nested inside a group for that weekday). Other fields that share identical labels are showing up in the Mapping dropdown.

The feed isn't Attached to the content type (under Basic Settings), it uses a standalone form. It uses a Node processor and the selected Bundle is the content type.

Any ideas? Why would a content field not show up in that Mapping dropdown? Have I missed some vital step?

# Answer
> 0 votes
Found a solution @ https://www.drupal.org/node/2085879

Where you can use the patch by agileadam @ https://www.drupal.org/files/issues/timefield\_feeds\_support-2085879-6\_7.x-1.0-alpha2.patch

On top of which you can also apply a patch from pontus.froding found @ https://www.drupal.org/files/issues/0001-adds-weekly-repeat-to-times.patch which also as an added bonus adds the weekday repeating to the import

The patch is still to this date not imlemented into any release and the issue of time field not showing up in feeds was that Feeds doesn't know the field type and the Timefield module didn't have any feeds hooks in it, to make feeds module aware of it.

Implementing this patch manually (for now) seems to be the only solution.

---
Tags: entities, feeds, importing-exporting
---


# Question
Title: How to upload file from a custom module?
I am trying to create one basic module for Drupal 8, where I have added one form with some textfields and multiple file upload element. Now on "submitForm" I am saving textfields values on database, but I am not sure how I can save image fields. I will be only saving the filename in the database.

Will it be using same function as we have in Drupal 7?

# Answer
> 8 votes
If you upload a file, it stores the file temporarily in **file\_managed** table in database.And you have to set the file permanent status 1 to save it permanently else it will be deleted from the table by cron after some time.
This sample code to load a image and save it to database might help you to understand.

```
/* Fetch the array of the image file stored temporarily in database */
$image = $form_state->getValue ('image');

/* Load the object of the image file by it's fid */
$file = File::load ($image[0]);

/* Set the status flag permanent of the image file object */
$file->setPermanent();

/* Save the file in database ( "managed_file" table) */
$file->save();

```

when you select any file from **'managed\_file'** field type, drupal make a entry in **'file\_managed'** table, you just have to set the permanent flag as above to decide whether you have to save it permanently or not.

---
Tags: 8, media, files
---


# Question
Title: Why isn't the #ajax property available for more Form API elements?
Looking at https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7.x because I haven't seen a page updated for Drupal 8, it seems like only a select few form elements are allowed to have #ajax on them. Isn't this too limiting? I want to do Ajax on a markup element. There are a lot of scenarios in which I would want to do Ajax with my own custom HTML, but I don't want to lose the functionality of the Form API, like getting the $form and $form\_state.

The way I see it, there are two ways of doing Ajax in Drupal, either normally by just calling a controller, or by using an element in the Form API with an Ajax callback. If I do Ajax normally, I can create data in Javascript however I want and send it to php, but I can't get the data in Drupal's $form object or call some of Drupal's special Ajax functions like entity autocomplete. If I use the Form API, I lose the ability to respond to any events on certain elements of the form.

Why is it like this? And, is there a way to get around it without modifying core?

# Answer
> 0 votes
In Drupal 8 render elements are plugins and you can define a custom render element in a module without modifying core.

The scenarios you describe probably don't need a custom render element. A #markup with an event attached to it is like a link or a button, where you remove the styling with css.

Additionally you can hook into ajax js and react on events with your own javascript. See ajax.js, the hooks are called prototypes.

---
Tags: forms, 8, ajax
---


# Question
Title: Difference between upgrade and migration
What is the difference between *upgrade* and *migration* in Drupal?

# Answer
> 1 votes
Seen as a process, upgrading will keep your existing database (where content and configuration lives) and update the code of your system. After the code is updated, all needed database modifications (configuration and content) will be performed.

Migration on the other hand, usually refers to content migration. That said, the migration process targets a Drupal instance different from the existing one, where the content will be transfered to.

A definitely good reference is the official Upgrade documentation page

---
Tags: upgrading
---


# Question
Title: How do I show user created node in user profile page with edit mode?
I have a content type 'child'. And I have give the permission to authenticated user to create child node. Its working fine. But I need to show current user created node in user profile page with edit mode so user can easily updated own created node. For this I have created views but I am not getting any option to show a created node as a edit form.

# Answer
You have to give permission for Edit own page for that role to see "Edit link" in views or any other page.

Tha can be available from

```
www.example.com/people/permissions -> <Content Type>: Edit own content

```

You have to create a module for showing your custom link in user profile page

```
function <modulename>_menu() {
 $items['user/%user/<yourlink>'] = array(
    'title' => 'Your Pages',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
 return $items;
}

```

Not to mention you have to clear cache after the this.
> 0 votes

---
Tags: 7, nodes
---