title: How to create a dynamic date format?

text:
# Question
Title: How to create a dynamic date format?
I'm fairly new to Drupal and I'm struggling to find where and how I should approach the problem I'm describing below. I suspect I will have to dive in the code but that's ok I'm comfortable with PHP.

I have a content type "Event" with a "Date & Time" field called "Event Start Date". I've configured the Date format to be "l, F d, Y - h:i a", but it's not exactly what I'm looking for.

I need to add a condition to my date format so that it doesn't display :00 when the minutes are at 00.

For example

```
Tuesday, January 25, 2017 - 9:15 am
Tuesday, January 25, 2017 - 9:00 am

```

should display

```
Tuesday, January 25, 2017 - 9:15 am
Tuesday, January 25, 2017 - 9 am

```

How and where should I be doing this in code?

Preferably, I would like to be able to tell when to apply this rule.

# Answer
> 3 votes
I think the best solution is used custom field formatter for date type:

```
/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
      'mymodule_custom_datestamp' => array(
          'label' => t('Custom datestamp formatter'),
          'field types' => array('datestamp'),
      ),
      'mymodule_custom_date' => array(
          'label' => t('Custom date formatter'),
          'field types' => array('date', 'datetime'),
      ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'mymodule_custom_datestamp':
      foreach ($items as $delta => $item) {
        $tmp = (integer)$item['value'];
        $minutes = (integer)date('i', $tmp);
        if(empty($minutes)){ //you'll update only values with :00
          $element[$delta] = array('#markup' => date('l, F d, Y - h a', $tmp));
        }else{
          $element[$delta] = array('#markup' => date('l, F d, Y - h:i a', $tmp));
        }
      }
      break;
    case 'mymodule_custom_date':
          .....
          break;
  }

  return $element;
}

```

You can use it anywhere and It uses the least resources.

# Answer
> 0 votes
You can use the theming of field: create file into your theme for field "Event Start Date" field--field-event-start-date.tpl.php

or use function in template.php of your theme (for delete seconds)

```
 function mytheme_field__field_event_start_date($vars) {
    $value = (integer)$vars['element']['#items'][0]['value'];
    if(empty($value % 100)){ //you'll update only values with :00
       $vars['items'][0]['#markup'] = date('l, F d, Y - h a', $value);
    }

 }

```

for delete minutes:

```
function mytheme_field__field_event_start_date($vars) {
  global $language;
  $tmp_date = $vars['items'][0]['#markup'];

  switch ($language->language) {
    case 'fr':
      $vars['items'][0]['#markup'] = str_replace('h 00', 'h', $tmp_date);
      break;

    default:
      $vars['items'][0]['#markup'] = str_replace(':00', '', $tmp_date);
      break;
  }
}

```

P.S. I could be wrong with variable names

# Answer
> 0 votes
Here is the solution I implemented using the hook\_field\_attach\_preprocess\_alter hook.

```
/**
 * Implements hook_field_attach_preprocess_alter
 */
function mymodule_field_attach_preprocess_alter(&$variables, $context) {
  global $language;

  foreach ($variables['content'] as $field_name => $field) {

    // remove minutes formating if at 00 on field type datestamp.
    if (isset($field['#field_type']) && $field['#field_type'] === 'datestamp') {
      $tmp_date = $variables['content'][$field_name][0]['#markup'];

      switch ($language->language) {
        case 'en':
          $variables['content'][$field_name][0]['#markup'] = str_replace(':00', '', $tmp_date);
          break;

        case 'fr':
          $variables['content'][$field_name][0]['#markup'] = str_replace('h 00', 'h', $tmp_date);
          break;

        default:
          break;
      }
    }
  }
}

```

---
Tags: 7
---


# Question
Title: What is correct destination for fid in destination image field?
I am attempting to do a simple migration of an image from a D6 CCK file field to a D8 file field, and for some reason it's not working. Following best practices, I've run a separate file migration - named 'file' - and so now I want to just migrate the fid reference during the node migration. In my blog node migration, I have this in the process section:

```
field_image:
  plugin: d6_cck_file
  source: field_thumbnail
  migration: file

```

where field\_image is the name of the D8 file field, and field\_thumbnail is the source D6 field.

The problem is that the image reference is not being migrated to the D8 field (field\_image). In going through the code with my debugger, I'm noticing that the CckFile::transform() method is not being called at all (although \__construct() and create() methods are being called), and that's where the finding of the fid in the file migration happens.

Is there something I'm missing in my config? It seems pretty straightforward, so I'm not sure what I'm missing.

Thanks.

**UPDATE:** After doing some debugging, I found that when the process gets to this line in MigratExecutable:processRow() where the `$destination` is field\_image:

```
$value = $plugin->transform($value, $this, $row, $destination);

```

the value of `$plugin->id` is `get`, not `d6_cck_file`. I can't understand why, since the plugin name is clearly defined as `d6_cck_file` in the migration config.

**UPDATE 2:** After doing some reading, I'm thinking I might need to use the iterator plugin, since both my source and destination fields are multi-value fields (i.e. they are allowed to have multiple values, even if they actually don't). So I'm trying this:

```
  field_image:
    plugin: iterator
    source: field_thumbnail
    process:
      field_image_target_id:
        plugin: migration
        migration: file
        source: fid

```

but that's not getting it either. Still debugging...

**UPDATE 3:** So with this most recent setup, my destination id is being found correctly, but the issue seems to be the destination. field\_image\_target\_id is the name of the db field where the value is stored, but apparently not the destination value to use. I also tried 'field\_image/target\_id, but that didn't work, either. What would be the correct destination?

# Answer
So the final solution that worked for this is as follows:

```
field_image:
  plugin: iterator
  source: field_thumbnail
  process:
    target_id:
      plugin: migration
      migration: file
      source: fid
    alt: alt
    title: title
    height: height
    width: width

```

As explained to me by @mikeryan, the iterator plugin allows you to iterate over multiple values which have subfields, and map the subfields in the internal process pipeline the way fields are at the top level. In this case, I just used the migration plugin to get the target fid from the file migration, and this puts it in the field\_image\_target\_id column in node\__field\_image table.
> 0 votes

---
Tags: 8, files, migrations
---


# Question
Title: How to limit/throttle speed of Views feed?
I have a Views feed that includes all recent content on my website. I run this through an IFTTT applet to auto-post to Twitter.

Is there a way to throttle how many feed items are added to the feed at once, in order to limit the number of tweets that come out of the IFTTT applet?

For example, if I add 10 pieces of content, I'd like the feed to reflect the first five now, and the next five after fifteen minutes.

ETA: I'm not limiting myself to using only Feeds, other modules or suggestions for a custom module are welcome.

# Answer
> 0 votes
This is possible, but not with *just* feeds.

You'll have to implement some sort of queuing, that looks at previously published nodes to determine if the new group of nodes can be added to the feed yet, or if they need to wait.

You should be able to get this working with some clever rules and a few VBO views.

# Answer
> 0 votes
If you're feed is only showing published content, you could use the Scheduler module to publish your content periodically.

---
Tags: views, feeds
---


# Question
Title: Search button text not showing in a Bootstrap sub-theme
I'm using a sub-theme of the Bootstrap v8.x-3.1 theme.

By default the search button shows the search icon.

In the theme settings you can un-check 'Iconize Buttons' which I expect would show the 'Search' text instead of the icon, however it shows an empty button... no text or icon.

How do I get the button to show 'Search' text instead of an icon?

# Answer
The solution I found for this was to copy this file from the Bootstrap theme directory

`src/Plugin/Form/SearchBlockForm.php`

to the same location in your sub-theme.

Then you can set the icon\_only property to FALSE.

e.g.

```
<?php
/**
 * @file
 * Contains \Drupal\subtheme\Plugin\Form\SearchBlockForm.
 */

namespace Drupal\subtheme\Plugin\Form;

use Drupal\bootstrap\Annotation\BootstrapForm;
use Drupal\bootstrap\Plugin\Form\FormBase;
use Drupal\bootstrap\Utility\Element;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @ingroup plugins_form
 *
 * @BootstrapForm("search_block_form")
 */
class SearchBlockForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function alterFormElement(Element $form, FormStateInterface $form_state, $form_id = NULL) {
    $form->actions->submit->setProperty('icon_only', FALSE);
    $form->keys->setProperty('input_group_button', FALSE);
  }

}

```

I still think there must be an easier way... but until then.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: How to attach a library to a specific content type?
I wonder how to attach a library to a specific content type. .e.g News. I found the following code from a post and applied the "hook" to the "node" but no idea how to filter by content type. Any idea?

```
function fluffiness_preprocess_node(&$variables) {
  $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
}

```

ref: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

# Answer
You can check content type and add libraries like this:

```
function fluffiness_preprocess_node(&$variables) {
  $node = $variables['node'];
  //check content type
  if ($node->getType() == 'article') {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
  }
}

```
> 19 votes

---
Tags: theming, 8
---


# Question
Title: Why are some images not displaying after migration to localhost?
I just moved a site from a production environment to an ubuntu based localhost set up and some of the images aren't displaying and are popping up in the console as 404 errors.

The files are present on the localhost set up, and they have the same permissions as the images that do show up. I think this means that the files are corrupted. So,

1. How do I test/fix this?
2. How can I prevent this from happening in the future?

# Answer
So, I'm my case the files were getting corrupted durring transfer via ftp. Archiving the files first and then transferring the archive solved the problem.
> 1 votes

---
Tags: media, migrations
---


# Question
Title: Creating a ticket system with core only. How to modify fields on full_content view without reloading?
I'm trying to create a ticketing system with Drupal 8 core. I know Drupal 8 has quick edit module, but that doesnt seem to be working in D8 core. Below is a very basic ticket I made as it just contains:

* ticket subject (title)
* ticket body
* assigned to
* status
* priority

When viewing a ticket or node, I want to be able to be able to ajax edit the status, priority, and assigned to fields. These are dropdown options or taxonomy reference fields. Right now one would have to click on "edit" to edit the node itself to make these changes. But how would one edit these on the same page without reloading to a new page?

I was thinking of using views and exposing the edit form for the same node, but that doesnt seem like its doable.

# Answer
Another approach would be to use a form mode instead of a view mode. Put there the fields you want to make writable and add the read-only information in a form alter hook (or separate view block if you want a UI only solution).

To use the form mode you need a module like Form Mode Control or some custom code, see this good tutorial https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8.

While quickedit is a single purpose solution for in-place editing of web content, you can now that you have a real form do all kind of tricks to get the behavior you want, for example implement autosave: https://www.urbaninsight.com/2016/08/21/how-implement-ajax-autosave-drupal-8-forms
> 0 votes

---
Tags: 8, entities, ajax
---


# Question
Title: How do I migrate a Kickstart site from one server to another?
I created a site using Commerce Kickstart. Then I added all the products and stuff. Now I want to move this site on a new server as it is.

I have downloaded all the files from the original site. Also exported the database.

Is it possible to use these files and database to migrate the site on new server with different domain name as well as different database name?

If no, what should I do?

# Answer
> /admin/config/system/backup\_migrate

* Click **Backup now** under the backup tab. Store this file
* Now take backup of your files from existing site
* Either rename settings.php to some other name or just remove it
* Now upload the backed up files to desired destination
* Just enter your new URL, it will take you to

> yoursite.xxx/install.php

* Now follow the usual method of installing your site (enter new database credentials)
* You'll be redirected to a fresh and basic Drupal site
* Now go to modules, enable Backup and Migrate module
* Go to configuration page of the same, click the **Restore** tab, now upload previously downloaded file (using same module)
* Click on **Restore Now**
* That's it. Your site is restored!
> 0 votes

# Answer
1. drush ard (https://drushcommands.com/drush-7x/core/archive-dump/)
2. copy backup file to the new server
3. drush arr (https://drushcommands.com/drush-7x/core/archive-restore/)
4. done
> 1 votes

# Answer
This should definitely be possible. Upload all of your files to your new server and create a new blank database.

Make sure to delete your existing settings.php file and create a new one from default.settings.php. You can find this file in sites/default/

Run the install script - yourdomain.com/install.php

Now upload your database to the new database.

Alternatively, you can upload your database to the new database and change the settings in settings.php manually.

Be careful to make the settings.php file secure by either running this: chmod 644 sites/default/settings.php on the command line or changing it via filezilla/your FTP client.
> 0 votes

---
Tags: migrations, commerce
---


title: Dynamically hiding/showing form fields

text:
# Question
Title: Dynamically hiding/showing form fields
I have created a custom module in Drupal 8. There should be some fields invisible by default; when a user clicks on *More Options*, the field should display. When user clicks on *Fewer Option*, the fields should be hidden again.

How can I achieve this in a Drupal 8 form?

# Answer
You can easily do this with the Conditional Fields module.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
> 2 votes

# Answer
You can use the states API as described in `drupal_process_states()`, which should not be confused with the state API.

The only difference with your description is that *Show more* is a checkbox, and the extra fields you want to show would be visible when the checkbox is checked (which also means they would be invisible when the checkbox is not checked).
> 2 votes

---
Tags: 8
---


# Question
Title: How do I show content in an iframe as a specific user?
I want to display an external site (over which I have no control) in an iframe. Someone using my site can have or not have an account on that other site. That site requires membership (which is free) to see any content. In either case, I want to display that other site as a dummy user I made on that site. How do I do this?

I tried using the iframe module and have the iframe point to `https://othersite.com/content?email=myemail&password=mypassword`, but that seemingly did not do anything. When logged in with my regular user on that other site, the iframe was displayed for my regular user, when not logged in I got a page with a login button.

Can I trigger the pressing of the login button and then fill in the login form, or is it possible that that is not possible?

Edit: Using curl, I can first log in and then using the same session get the page I want. However, how do I put that out into an iframe? I've now got a variable containing the html of the page I want to show in an iframe between fields belonging to a content type.

# Answer
> 1 votes
The thing to keep in mind here is that an iframe runs on the client side. It is basically a browser within a browser. This also means that it will use an existing session if the client is logged in on the site (you already discovered this):

> When logged in with my regular user on that other site, the iframe was displayed for my regular user.

The problem is that Drupal runs server side. Theoretically you should be able to use `drupal_http_request()` to send the login data to the other site, catch the session cookie and initiate a session. But that would initiate a session on the server, not on the client. The same with cURL, it would log the server in, not the client. So the iframe for the client would still show the login button.

In order to do something client side, your only option is probably to use javascript and perform an POST the login data to the other site. This unfortunately means that the data to login (username and password) also will be sent to the client. A little tech savvy user will be able to compromise your account on the 3rd party site. (If he changes your password, it would break your own site)

> Can I trigger the pressing of the login button and then fill in the login form, or is it possible that that is not possible?

Unfortunately also no, browsers implement safety measures to prevent one site form interacting with another. You cannot use javascript (or CSS or anything else) to modify the site within the iframe.

For a second I thought you can try to start the session on the server and then send the session variables to the javascript to process client side. This will not expose your credentials but will still allow someone to take over your session.

So I will conclude with no. There is unfortunately no sensible way of doing this.

Finally there are 2 more things to keep into account;

* Do the terms of use of the other site allow you to share an account with multiple users (you could get into a lot of trouble)
* What if the client happens to already have an account on the site? You would override his session and he would be you. I would personally hate your site if it forced me to logout and in again on another website.

# Answer
> 0 votes
You will need a single sign-on (SSO) set-up for this. My advice would be to install the CAS module and follow these detailed instructions. Once you have this configured, any user that is logged in on your site is also logged in on the other site, be it in an iframe or not.

---
Tags: ajax
---


# Question
Title: How can I use feeds tamper to remove currency ($) sign when importing prices?
I have an integer field that I am using for price info (not commerce) and I am importing from a csv. I need to strip out the $ sign and a blank space after. "$ ". How can I do this with feeds tamper?

# Answer
> 0 votes
This is pretty easy. You can use the "Find replace" tamper under "Text", and then user "$" as the search and "$ " as the replace. If you want to be fancy you can use the "Find replace REGEX" tamper to make sure you only get the leading $. IIRC, this needs to include the delimiters. Using "/^\\$/" as the search and "$ " as the replace should work (you need the ^ to anchor to the beginning and then escape the $. Both of these plugins are part of the base feeds\_tamper module.

---
Tags: feeds
---


# Question
Title: How can I pull slideshow filenames from the database using jQuery?
I've have a jQuery plugin I'm using in my Drupal 7 site to make a fullpage background slider. I load it from a javascript file. How can I get the image names from Drupal's database instead of having to manually edit the list of images in the javascript file?

Here's the .js I load in my theme:

```
(function($) {
  Drupal.behaviors.BackgroundSlider = {
    attach: function(context, settings){
      $.backstretch([
            "/sites/default/files/styles/background_transition/public/ba5933c356c60f895785da952f8ad3e4_0.jpeg?itok=PjRiZj-V"
          , "/sites/default/files/styles/background_transition/public/8bad4c95b3776bed84222abe4c5288ba.jpeg?itok=cKq-2Dgj"
          , "/sites/default/files/styles/background_transition/public/78cefce14e9d9a613b0bc1950da662c6.jpeg?itok=4pAyvgsM"
          , "/sites/default/files/styles/background_transition/public/00336b1506db0487ea33af734abd3b16.jpeg?itok=QcS5dV2K"
      ], {duration: 3000, fade: 750});
    }
  };
})(jQuery);

```

# Answer
> 1 votes
Here's another option - how about create a view to generate JSON for the image paths and then pull that into your JS?

The module "Views Datasource" can output your view as JSON. You would need to create a view that pulls the images from the content type you are using and make sure that the image is rendered as a URL (rather than the actual image tag).

From there you could update your JS to pull the JSON from the view output. Create a loop that sets a variable with the JSON data (as a comma separated list) and use that variable within your backstretch function.

I can't provide any code examples at this time, but hopefully that can get you started down a path. Here is a stackoverflow article that provides examples on how to convert JSON to CSV and store that in a variable:

https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable

---
Tags: 7, theming, javascript
---


# Question
Title: How do modules end up in the profiles directory in distributions?
I'm building a basic distribution and I cannot find any information on how contributed modules that are included in a distribution get placed into the drupal-root/profiles/profile-name/modules directory.

I've looked at a number of distributions, both hosted on drupal.org and not, trying to find some line(s) of code that does this, but there doesn't seem to be any. It has got to be happening "automatically" somehow, but it isn't working for me. When I add modules to my make file, they always end up in sites/all/modules.

I've spent hours trying to ask Google this question but every form I can come up with just gives me information on how to install a module, or how to move modules from the profile of a distribution into sites/all/modules - both of which I am well aware of...

So, can anyone direct me to documentation that can help me out? I'm sure it is out there, but I've hit a wall trying to find it.

# Answer
I found the problem.

I have two make files - drupal-org.make.yml & build-xq42\_d7\_sk.make.yml. I was including the following in the build-xq42\_d7\_sk.make.yml:

```
includes:
  - drupal-org.make.yml

```

Turns out this caused the problem. There's no need to include any reference to that file at all in the build-profile-name.make.yml file.

This is the first make file I've built and I created it by reading documentation and looking at existing make files for other projects. I saw this line in one of the make files I used as an example and assumed it was OK.

Now I know...!
> 0 votes

---
Tags: distributions
---


# Question
Title: How to use features-export drush command?
I'm using Drupal 7. We have a large feature that we want to break apart. I am following the instructions here, and since there are a number of objects in the feature, I want to use drush commands, instead of clicking around the UI, to export the different objects.

I am looking at the drush commands from the features 7.x-2.10 module and found `features-export`. I'm not sure how to use the drush help command, but I found this description in `features.drush.inc`

```
case 'drush:features-export':
  return dt("Export a feature from your site into a module.
   If called with no arguments, display a list of available components.
  ...

```

But I called it with no arguments, and instead of a list of components, I got this error message:

```
$> drush features-export
No feature name given.

```

Poking around more, I found the `features-components` command, which gives me this:

```
$> drush features-components
Enter a number to choose which component type to list.
 [0]   :  Cancel
 [1]   :  all
 [2]   :  breakpoints
 ...
 [11]  :  field_base
 [12]  :  field_group
 [13]  :  field_instance

```

Selecting 11 (field\_base) gives me these tokens:

```
...
field_base:field_address_1
field_base:field_address_2
field_base:field_state
field_base:field_zip_code
...

```

So I thought that I could use a line or token from the above output in the `features-export` command. However, I still get errors:

```
$> drush features-export field_instance
No components supplied.                            [error]

$> drush features-export 11
No components supplied.                            [error]

$> drush features-export field_base:field_address_1
No components supplied.                            [error]

$> drush features-export "field_base:field_address_1"
No components supplied.                            [error]

```

How do I use the `features-export` command from the features 7.x-2.10 module?

# Answer
I figured out the syntax.

First, you have to learn the name of the component. Use the `features-components` command for this.

Then, when you know the component, do `drush features-export my_module_name 'component_type:component_name'`. That will create a module with the component you specified in it.

So in my case, I would do `drush features-export my_module_name 'field_base:field_address_1`.

If you want to add multiple components, you have add them to an existing, *enabled* module. So if I want to add another component to the features module I just created, I would do

```
$> drush en -y my_module_name
$> drush features-export -y my_module_name 'field_base:field_address_2

```
> 0 votes

---
Tags: features
---


title: Validation Users Issues

text:
# Question
Title: Validation Users Issues
I have my fresh web site up and running. My first test is to try the functionality of creating a new user. I tested added myself (no, not my admin account -- a different one with a different email address). The new user's (mine) email got an alert saying that the account would be approved by the admin and further instructions and password would be sent to me.

I got the alert email also at the admin email address and I logged on and assigned the account a password and approved the account.

But the new user's email never got the notification. I also tried to find the user's email address by using the admin's privileges on the site in case I needed to deliver the message to the user by hand. But I could not find out how to do that.

# Answer
I solved this issue. The problem was that one has to look in the "spam" folder to see email that is sent by automated means.
> 0 votes

---
Tags: 7, commerce, installation, http-request
---


# Question
Title: how to link to sections in the same page?
How to create menu items with links that link to the same page (like scroll down further)?

Example: http://eshbeata.com/ , clicking on "Work" or "About" just scrolls down the same page.

# Answer
This isn't so much a Drupal thing as an html link thing.

As you can see from the URL when you click on one of those links, you'll notice that they look like this:

```
http://eshbeata.com/#about

```

or

```
http://eshbeata.com/#works

```

Note the hash tag and word at the end (#about and #works).

That's called an 'anchor' and is essentially a link to a specific *part of a page* rather than a link to just the page.

Using anchors requires a two-part setup:

* First you have to label the place you want to jump TO with your link. So, by the exact place in the page that's the 'works' section, the author of that page would have the following:

```
<a href="#" name="works"></a>

```

It's just an empty link that names this spot in the page with the name 'works', and that's precisely what the link below will look for

* Second, in the link "Work" in the top menu, there is the anchor '#works' at the end of the link.

```
<a href="#works">Work</a>

```

Hope this helps. You can read much more about this online just by searching for something like 'html anchors' or similar terms.
> 1 votes

# Answer
I will suggest a little modification for the novices like me. Put the anchor tag withing the paragraph tag; so the anchor is created.

Now this anchor can be linked from another page also. such as link to: example.com/node/3/#works
> 0 votes

---
Tags: routes, navigation, 7
---


# Question
Title: How to get 'base theme' information about a theme?
In an admin settings form in a custom module, I need to determine what base themes a specific theme uses (the default theme, not the current theme). If I know the child theme's name, how do I obtain the names of the 'base themes' that child theme uses (if any)?

# Answer
You can get the details of a theme by using ThemeHandler::listInfo().

```
$child_theme = 'bartik';

$base_theme = \Drupal::service('theme_handler')->listInfo()[$child_theme]->base_theme;

$base_themes = \Drupal::service('theme_handler')->listInfo()[$child_theme]->base_themes;

```
> 3 votes

---
Tags: 8
---


# Question
Title: Embed one entity form into another and save both
I have a custom entity, that is depending on the user entity. In fact, it is even so depending that I felt it made sense to display my entity form within the user profile form:

The problem I am now having is the following; there are 2 save buttons. And if it is not bad enough, the save button for the user (the lower one) does not even function anymore and white label save button only saves the white label entity.

The form is altered into the user form like this:

```
function whitelabel_form_user_form_alter(&$form, FormStateInterface $form_state) {

  $whitelabel = WhiteLabel::load(1);

  $whitelabel_form = \Drupal::service('entity.manager')
    ->getFormObject('whitelabel', 'default')
    ->setEntity($whitelabel);

  $form['whitelabel'] = array(
    '#type' => 'details',
    '#title' => t('White label settings'),
    '#open' => TRUE,
    'form' => \Drupal::formBuilder()->getForm($whitelabel_form),
  );
}

```

I was hoping to shuffle some parameters in the `$whitelabel_form` array (that used to work in Drupal 7), but that array is enormous and I could not find the submit buttons and handler that I needed.

So the question is, can this be done? And what would be the recommended way of doing it?

# Answer
> 10 votes
Instead of trying to do your own thing, you should try Inline Entity Form module. This module is made for this specific case (creating / editing entities within entity forms).

I know a lot of work has been put in to this to improve workflow in Drupal Commerce, which means this should be working well. I haven't tested it out myself, but since Drupal Commerce depend on it in Drupal 8 as well, it should be quite stable already.

The module works by adding a widget to the entity reference field that creates the form, so it should be pretty much plug and play. The only requirement is that the user has a reference to your custom entity.

# Answer
> 7 votes
I believe this should be possible. Unfortunately, I do not have time to write code today, however, I think you should keep the following things in mind:

* While appending the sub-form, make sure you remove special items such as `form_id` and `form_build_id` used by Drupal to recognize which form was submitted.
* If you do not want the form buttons in the second form, you need to remove that form item like `unset($sub_form['actions'])` before you append the sub-form to the main form.
* Make sure you enable `#tree` for the form so that you can catch the sub-form values in a separate pocket in the POST variable. Example, `$form['#tree'] = TRUE; $form['sub-form'] = $sub_form;` This will make your sub-form values available in `$form_state['values']['sub-form']`.
    + If you want users to be able to submit the sub-form independently, you will have to rename the actions for the sub-form so that you can later recognize as to which button was clicked. If you want the user to use only one save button to save both the things, then there would be less trouble so ignore this sub-point.
* Now, that the form is visible in the UI, the next step would be to handle submission. To do this, add a form submission callback to your main form. You might also want to add the sub-form's validation callbacks to the main form as well. In the custom callback, you will have to trigger the submission callback for the sub-form. In Drupal 7 we used to do drupal\_form\_submit \- I dunno the equivalent for Drupal 8 yet. Alternatively, you can trigger the sub-form's submission callbacks manually in the worst case scenario, but make sure you pass only the `sub-form` values in `$form_state['values']` (hope you understand what I mean).
* Once the sub-form callback works without errors, you can assume both the forms were submitted and processed successfully!

Hope it helps! Sounds like one hell of an experiment! Good luck.

# Answer
> 1 votes
The theoretical answer (one that does not work, but this is the closest I got). Posting here for reference and a starting point for others.

Alter the user form.

```
function whitelabel_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $whitelabel = WhiteLabel::load(1);

  $whitelabel_form = \Drupal::entityTypeManager()
    ->getFormObject('whitelabel', 'default')
    ->setEntity($whitelabel);
  $renderable_form = \Drupal::formBuilder()->getForm($whitelabel_form);

  // Remove embedded form specific data.
  unset($renderable_form['actions']);
  unset($renderable_form['form_build_id']);
  unset($renderable_form['form_token']);
  unset($renderable_form['form_id']);

  // Also remove all other properties that start with a '#'.
  foreach ($renderable_form as $key => $value) {
    if (strpos($key, '#') === 0) {
      unset ($renderable_form[$key]);
    }
  }

  // Create a container for the entity's fields.
  $form['whitelabel'] = array(
    '#type' => 'details',
    '#title' => t('White label settings'),
    '#open' => TRUE,
    '#tree' => TRUE,
  );
  $form['whitelabel'] += $renderable_form;

  $form['actions']['submit']['#submit'][] = 'whitelabel_form_user_form_submit';
}

```

Submit handler:

```
function whitelabel_form_user_form_submit(&$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();

  $form_state = new FormState();
  $form_state->setValues($values);
  // Theoretically you'd want to use $values['entity_container']
  // for the dedicated entity values.

  // Obtain or create an entity. (You want to get this from the form.)
  if (!$whitelabel = WhiteLabel::load(1)) {
    $whitelabel = WhiteLabel::create();
  }

\Drupal::entityTypeManager()
  ->getFormObject('whitelabel', 'default')
  ->setEntity($whitelabel) // Current entity.
  ->buildEntity($form, $form_state) // Update with form values.
  ->save(); // Save updated entity.
}

```

---
Tags: 8, forms, users
---


title: Site structure taxonomy configuration

text:
# Question
Title: Site structure taxonomy configuration
I am looking forward to use Drupal in order to create a knowledge-base website having a structure as shown below. Therefore, each time a knowledge area is selected, Drupal should automatically filter the related sublevels and display them as a list.

* Q1 : Could anyone please help me in knowing what taxonomy/terms configuration i should use to solve my issue ?
* Q2 : Are (many-to-many) relationships represented by red lines supported by Drupal ? If Yes, how could that be done?

# Answer
Below is a blueprint of how I'd implement what you're looking for. It can work for both D7 and D8 ...

# Sub-level 1

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

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

**Resources**:

# Sub-level 2

### Option 1

You could use one or more taxonomies to implement "*Subject*". E.g. 1 taxonomy for each area, each of them with 3 terms. As a variation, a single taxonomy (used by all areas) with up to 9 (different) terms could also work.

### Option 2

As an alternative to using taxonomies/terms, you could also use the Entity Reference module (included in D8 core). Here is a possible solution to do so:

* create a content type (say) "*Subject*", and add any "field" to it you might need (now or in the future).
* create 9 nodes of type "Subject".
* for the content type you use for your "nodes" (in your picture), add a field that implements an entity reference to your "Subject" nodes.

# Nodes

That's pretty forward, just pick an appropriate content type for those nodes you want to create. One could argue if you yes or no want to use the same content type for the nodes of the various areas. But unless you have a need for different fields of those nodes for the various areas, I don't see any reason to have like a different content type for each area. Also because if you want to impose access rules for those nodes in the various areas, you'd do so using the Group module.

# Bonus

Everything above is based on using entities. With that you also have all sorts of bonus options to further refine your implementation using out-of-the-box facilities with modules such as:
> 0 votes

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


title: Same day with time range

text:
# Question
Title: Same day with time range
I'm trying to make an events calendar that has events on a day, (e.g. Feb 2), with a start and end time, (1pm - 3pm).

However, the current date module in Drupal 8 doesn't have support for end times and the date module doesn't seem to be ready yet.

How would I such a date field up? I could always use a textbox, but I need to be able to set different date formats for the day of this field.

I see that there isn't a well known option for drupal 7, but hopefully there is a elegant solution for Drupal 8. Worst comes to worst, I'll accept hacky solutions....

Thanks!

# Answer
You need to enable the Datetime Range module. It is currently an experimental module in Drupal 8, and not enabled by default. On admin/modules it's in the **Experimental** group:

Enable it, and a new field type will appear, **Date Range**.
> 3 votes

---
Tags: 8, datetime
---


# Question
Title: Stream_flush in not being called while using stream wrapper
I've created a stream wrapper foo:// and when I am using this wrapper and my file moved successfully but the flush\_stream function is not called I don't why I also checked for the public:// stream wrapper and It calls the flush\_stream function after moving file.

I backtracked the code while running for public:// stream wrapper I got this output

```
Array
(
[0] => Array
    (
        [function] => stream_flush
        [class] => DrupalLocalStreamWrapper
        [object] => DrupalPublicStreamWrapper Object
            (
                [context] =>
                [handle] => Resource id #11
                [uri:protected] => public://a1a1211127_aa_0.jpg
            )

        [type] => ->
        [args] => Array
            (
            )

    )

[1] => Array
    (
        [file] => /var/www/html/includes/file.inc
        [line] => 1633
        [function] => move_uploaded_file
        [args] => Array
            (
                [0] => /tmp/phpPaIdAn
                [1] => public://a1a1211127_aa_0.jpg
            )

    )
[2] => Array
    (
        [file] => /var/www/html/includes/file.inc
        [line] => 1585
        [function] => drupal_move_uploaded_file
        [args] => Array
            (
                [0] => /tmp/phpPaIdAn
                [1] => public://a1a1211127_aa_0.jpg
            )

    )

```

It means stream\_flush is called after the move\_uploaded\_file function. But in my case the move\_uploaded\_file function is called but stream\_flush is not.

Any idea why?

# Answer
> 0 votes
I Just changed the stream wrapper type to STREAM\_WRAPPERS\_LOCAL\_NORMAL and implements the chmod function and it works seamlessly.

---
Tags: 7, stream-wrappers
---


title: Loading block via ajax

text:
# Question
Title: Loading block via ajax
I have an custom module with Block:

```
namespace Drupal\generator\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class GeneratorBlock extends BlockBase {

    public function build() {
        $form = \Drupal::formBuilder()->getForm('Drupal\generator\Form\ProjektForm');

        return array(
          'form' => $form,
          '#attached' => array(
            'library' =>  array(
              'generator/generator-css'
            ),
          ),
        );

    }
}

```

All it does is placing some From in there with additional `.css` file (from library). I can place this block via Admin -\> Structure -\> Block layout and it works fine.

What I want now is to **load that block via Ajax** (because I want to refresh the whole block in some cases). And by that I mean I want to load it into wrapper (like with `$.load(...)`) or get the content of the block in JS variable (not the whole page with block, but just the rendered block).

I've found the tutorial for Drupal 7 on drupal.org, but I failed to port it to Drupal 8.

# Answer
> 7 votes
You can use the `#ajax` attribute to load main part of the block via Drupal ajax.

```
namespace Drupal\generator\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\generator\Form\ProjektForm;

class GeneratorBlock extends BlockBase {

  public function build() {
    return array(
      'form_wrapper' => array(
        '#prefix' => '<div id="form-wrapper">',
        '#suffix' => '</div>',
        '#markup' => '',
      ),
      'load_form' => array(
        '#type' => 'button',
        '#value' => $this->t('Load form'),
        '#ajax' => array(
          'wrapper' => 'form-wrapper',
          'callback' => array(static::class, 'getForm'),
        ),
      ),
      '#attached' => array(
        'library' =>  array(
          'generator/generator-css'
        ),
      ),
    );
  }

  public static function getForm() {
    return \Drupal::formBuilder()->getForm(ProjektForm::class);
  }

}

```

---
Tags: 8, blocks, ajax
---


title: How to add Structured data to a site?

text:
# Question
Title: How to add Structured data to a site?
I am trying to find a lot on Google how to add Structured data to site and from all the tutorials I got an impression that there is RDF module in core which was supposed to do that work like providing structured data to search engines (Google).

That module is in core and already installed on site, still Google Search Console saying,

> We do not detect any structured data on your site.

Am I missing something? If RDF does not provide structured data to search engines, what is the right method to add structured data to a site? Please, correct me if I am wrong about RDF.

# Answer
If you enable the **RDF** module, Drupal will automatically output some RDFa for your content. You can use a RDFa parser to extract it, e.g., http://linter.structured-data.org/. If it doesn’t find any data (under "Raw structured data extracted from the page"), you are likely using a theme that doesn’t support it. Use a default/core theme for testing, you should see it then.

If you want to provide additional structured data for your content types and field content, you need to map the content types to suitable RDF types, and the fields to suitable RDF properties. If you care about SEO, you’ll likely want to use the types and properties from Schema.org, as the big search engines sponsor this vocabulary, and use it for things like rich search results.

One way to add these mappings is using the **RDF UI** module (which comes integrated with Schema.org).
> 3 votes

---
Tags: 8, rdf
---


title: How do I configure front page?

text:
# Question
Title: How do I configure front page?
I have a new installation and I have "No front page content has been created yet". How do I configure this front page? How do I give a new user the ability to create their own blogs whilst also preventing them from having full control of the system?

# Answer
> 1 votes
## Build Your Own Content Type

Create a Blog Content Type:

* Admin \> Structure \> Content Types \> Add Content Type (yoursite.ca/admin/structure/types/add)
* Put "Blog" as the name of the content type
* Adjust the opitions, (Submission form settings, Publishing options, Display settings, Menu settings), accordingly
* Add the fields you want. If you want Tags, you could add a Taxonomy reference field

To allow users to make blogs, but not anything else:

* go to `Admin > People > Permissions` (yoursite.ca/admin/people/permissions)
* scroll down to the **Node** Section
* select permissions, normally *Blog: Create new content* and *Blog: Edit own content* at least, for the role you want, (or AUTHENTICATED USER, which is every logged in user)

## Use Core Content Type

There is already a core content type called article that has the following fields:

* Title
* Body
* Image
* Tags

Instead of making your own content type, you could just use this one.

To allow them to make blogs, but not anything else:

* go to `Admin > People > Permissions` (yoursite.ca/admin/people/permissions)
* scroll down to the **Node** Section
* select permissions, normally *Article*: Create new content\* and *Article: Edit own content* at least, for the role you want, (or AUTHENTICATED USER, which is every logged in user)

## Remove front page message

A couple of options. The most elegant is to make a landing page and set that page as the "welcome" page at Admin \> Configuration \> System \> Site information (yoursite.ca/admin/config/system/site-information)

Other options:

* a module
* CSS (Set `display: none` on the element)
* A view. Follow these instructions.
* Or scroll to the top of the mentioned link and read the forum. There are a ton of alternatives.

# Answer
> 0 votes
There isn't a front-page configuration. What you are seeing is the default front page. If you create some nodes (aka content), they will show up on that page automatically. So if you give your users permission to create blogs, the blogs will show up on that page.

As for giving users permission to create blogs, first you need to create a blog content type. Then give authenticated users permission to create blogs.

---
Tags: 7
---


# Question
Title: Where is the service container compiled to?
Where is the service container compiled to in Drupal 8, in the database or in a file?

# Answer
As @mradcliffe described in a commment, the normal Symfony way to compile and cache the service container is a single php file. Drupal used this until Sep. 2015. If you have an older installation, you still find the compiled container in `php/**/`, because it was never deleted by newer versions.

For better performance Drupal has changed this and stores it now in database in the table `cache_container`. The change record and how to take a look inside the container to debug it:

Change record: The service container definition is now stored in the database by default
> 2 votes

---
Tags: 8
---


title: How to view search API raw sql query

text:
# Question
Title: How to view search API raw sql query
can we get the raw SQL query based on the search API views?

Actually, the search result didn't return the result (sorting) in the way I need it to be done.

An example I have a product name "Bicycle 100" and there are other product names such as "Bicycle 100 spare parts", "Bicycle 1100", "Bicycle 1000", "Bicycle 2100".

If user search for "Bicycle 100" and the first result I would like it to display "Bicycle 100", "Bicycle 100 spare parts", then only by the others like "Bicycle 1000", "Bicycle 1100", etc.

I am thinking whether I can write a raw query with union with the search api query.

# Answer
> 1 votes
The latest stable version of Search API module (7.x-1.20) has a known bug when showing the SQL query that is performed. You will have to apply the patch that appears on that issue or upgrade to the latest development version.

Take into account that even when patch is applied, the information that will appear on Views UI will not be the raw SQL query itself. Instead, you will have the properties of a SelectQueryInterface element:

```
Index: test_search_api_index_node_index
Keys: 'university'
Parsed keys: array (
    '#conjunction' => 'OR',
    0 => 'university',
)
Searched fields: field_test_1, ...
Filters:
status = '1'
Options: array (
    'parse mode' => 'single',
    'conjunction' => 'OR',
    'filter class' => 'SearchApiQueryFilter',
    'search id' => 'search_api_views:test_view_search:test_search_page',
)

```

In order to get **the raw SQL query**, you will have to implement a custom module that alters the Search API query and use a debug tool like Devel module.

```
/**
 * Implements hook_search_api_db_query_alter().
*/
function yourmodule_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  dsm($db_query, 'The SelectQueryInterface element');
  dsm((string) $db_query,'The raw SQL query with tokens');
  // Below I am changing the way Search API performs this search.
  $conditions =& $db_query->conditions();
  if (isset($conditions[0]) && is_string($conditions[0]['field']) && $conditions[0]['field'] == 'word') {
    $conditions[0]['operator'] = 'LIKE';
    $conditions[0]['value'][0] = '%' . $conditions[0]['value'][0] . '%';
  }
}

```

When printed, you will see the query has some token strings. Those tokens are the same that Views UI has printed above:

```
The raw SQL query with tokens =>
SELECT t.item_id AS item_id, SUM(score) AS score
FROM {search_api_db_test_search_api_index_node_index_text} t
LEFT OUTER JOIN {search_api_db_test_search_api_index_node_index} t_2 ON t.item_id = t_2.item_id
WHERE  (word LIKE :db_condition_placeholder_0 ESCAPE '\\') AND (field_name IN  (:db_condition_placeholder_1, :db_condition_placeholder_2, ...)) AND(( (t_2.status = :db_condition_placeholder_12) ))
GROUP BY t.item_id

```

I hope this helps you.

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


# Question
Title: Redirect to a content page after login only from that page
On one certain page of my site, users have to log in before going any further. They don't have to be logged in to see most of the rest of the site content, but on this one specific page, they do have to be logged in. I figured out how to put a barrier up that forces users to log in before seeing that page's content (i.e., if users aren't logged in, the only thing on the entire page is a line that says "To create content, you must first log in" and there's a link to the login page), but how do I redirect newly logged-in users directly back to that same page (which now will have content on it) so they can now see its content?

At the moment, after they log in, it just takes them to their profile page.

In other words, if users log in on any other page, it's fine if they're redirected to their profile page, but on this one specific page, they need to stay put. I've seen lots of variation of the following code:

```
function hook_user_login(&$edit, $account) {
drupal_goto('node/1');
}

```

But I don't think this is what I'm trying to accomplish. The current code I have in there looks like this:

```
$sample1 = '<a href="../user">log in</a>.';
$sample2 = 'To create a classified ad, you must' . " " . $sample1;

global $user;
if ($user->uid == false){
return $sample2;

}

```

I've seen some code like this that looks promising:

```
#action' => url($_GET['q'], array('query' => drupal_get_destination()))

```

But I can't figure out how to make it work. Anyone got any ideas?

# Answer
Hope this will give you,

In Drupal 7, you can achieve it by using **destination parameter**.

Just add the destination parameter in the URL where you want to redirect it.

For example if you are in login page and after login if he want to redirect to some node say **about** page then

```
YOUR_DOMAIN/user/login?**destination=about**

```

Just add the **destination parameter** in "**To create content, you must first log in**" link. On click of this link it will redirect to User login page with the destination parameter. After login it will redirect to the path you have specified in the destination value.
> 5 votes

# Answer
Use the r4032login module and it will redirect users to the login page anytime they hit a page that they don't have permission to access. Once they login it will redirect them back to the page they were trying to access.
> 1 votes

# Answer
You can use the Rules module in Drupal. Use something like a 'execute custom PHP code' where you can use request\_uri to preg\_match with the page you need identified. That's it. Below is a simple block you could use:

```
$request_url = $_SERVER['REQUEST_URI'];
if (preg_match("/content-page/", $request_url)) {
  return TRUE;
}

```
* Keep the event "User has logged in".
* In the condition, "execute custom PHP code"
* Create a page redirect below that option to redirect to that page
* Assign a greater weight to this Rule if there's already login-redirect rules on your site.

Should get you working.
> 1 votes

# Answer
This can be achieved by using a combination of content access and login toboggan modules. You'll be able to restrict pages and prompt user to login to access them.
> 0 votes

---
Tags: users, nodes, redirection
---


# Question
Title: Add empty links from a BreadcrumbBuilder
For several specific parts of a website, I'm using a custom `BreadcrumbBuilder`, like this:

```
...
class SpecificBreadcrumbBuilder implements BreadcrumbBuilderInterface
{
    /**
     * @inheritdoc
     */
    public function applies(RouteMatchInterface $route_match)
    {
        $node = $route_match->getParameter('node');
        return $node->getType() == 'specificpage';
    }

    /**
     * @inheritdoc
     */
    public function build(RouteMatchInterface $route_match)
    {
        $node = $route_match->getParameter('node');

        $breadcrumb = new Breadcrumb();
        $breadcrumb->addCacheContexts(["url"]);
        $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

        $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));

        if (!empty($node->field_specific->value == '...')) {
          $breadcrumb->addLink(Link::createFromRoute('Specific pages', '<front>'));
          $breadcrumb->addLink(Link::createFromRoute($node->getTitle(), '<front>'));
        }

        return $breadcrumb;
    }
}

```

I would like to **not** use URLs for the two last links. Something like `<nolink>` (from the "Special Menu Items" module), but made from code.
I cannot find a way to add a text-only element to my Breadcrumb (and from what I can see, this class only have an `addLink()` function).

Any thoughts?

# Answer
> 2 votes
Drupal 8 has now a special `<nolink>` route to define empty links:

```
$breadcrumb->addlink(Link::createFromRoute('Empty link', '<nolink>'));

```

See issue (patch commited to 8.2.x): https://www.drupal.org/node/2693725

---
Tags: 8, navigation, breadcrumbs
---


title: Changes to leaflet Settings not working

text:
# Question
Title: Changes to leaflet Settings not working
I am unable to alter a settings of a leaflet map generated by a view using the method described here in a custom module. https://www.drupal.org/node/1883788

Using the code below in my custom module does not work.

```
  function MYMODULE_leaflet_map_info_alter(&$map_info) {
      $map_info['esri-world-street-map']['settings']['scrollWheelZoom'] = TRUE;
      $map_info['esri-world-topo-map']['settings']['scrollWheelZoom'] = TRUE;
  }

```

Where MYMODULE is the name of my module.

Someone else had this same issue and we have been talking trying to solve the issue. https://www.drupal.org/node/2831593

# Answer
The code shown in your question can never work: you need, at least, change the function name from "`MYMODULE_leaflet_map_info_alter`" to the actual name of your module.

PS: debugging is the art of taking away all possible reasons why something doesn't work as expected. This is for sure 1 of the possible reasons ...
> 0 votes

---
Tags: 7
---


# Question
Title: how to connect to database in drupal in order to display the content in a table
I am using drupal in order to create a website on my localhost machine.

I have a mysql database that i want to connect it to the drupal website and display its data in a table.

and in the drupal I download the Views Database Connector (VDC) module in order to connect to the external database.

but it did not work .

second method I used views and created content types that are the fields table of the external databases.

but I do not know how to continue to display the data.

third method I created the tables in drupal database and want to display its content .

I am new to drupal so I want any of these method to work for me

**note** feeds module also did not work because its not set up yet on the drupal 8.x

# Answer
You need add the followings lines in settings.php for connecting 'external' database.

```
$databases['default']['default'] = array(
      'database' => 'drupal8',
      'username' => 'username',
      'password' => 'password',
      'prefix' => '',
      'host' => 'localhost',
      'port' => '3306',
      'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
      'driver' => 'mysql',
    );

$databases['external']['default'] = array(
  'database' => 'external',
  'username' => 'username',
  'password' => 'password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

To activate external database

```
\Drupal\Core\Database\Database::setActiveConnection('external');

```

//code to fetch data and display

To activate drupal database

```
\Drupal\Core\Database\Database::setActiveConnection();

```

If you are looking some example refer How to connect to another database in your Drupal 8 site ?
> 2 votes

---
Tags: 8, database
---


# Question
Title: What would be the alternative to fix "Access forbidden 404" on my test site while using basic_authentication module for rest resource?
Background: I had http authentication enabled by htaccess on my test site. I had created REST resource using Drupal 8 core REST web services modules and views. When i used authentication as `basic_auth` than on Test site got `access forbidden 404` for each page request. Uninstall `basic_authentication` make it work but i want basic\_authentication should work for my test site. What would be the better alternative for this?

Thanks

# Answer
You can send in the user and password parameters with your API call.

```
user:password@http://site-url.tld

```

this way you can still communicate with the app whilst keeping it behind basic auth
> 0 votes

---
Tags: 8
---


# Question
Title: How to add a list under form in my module page?
I have created a Drupal 8 module and I need help to put list under form. Below is my code:

Controller

```
<?php

namespace Drupal\bocExtractor\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Utility\Html;
use Drupal\Core\StreamWrapper\PublicStream;

class BocExtractorController extends ControllerBase {

    public function DisplayBocExtractorSettingsForm() {
        $output = array();
        $form_class = '\Drupal\bocExtractor\Form\BocExtractorSettingsForm';
        $build['form'] = \Drupal::formBuilder()->getForm($form_class);
        $build['#title'] = t('Boc Extractor Settings');
        $build['list'] = array(
            '#weight' => 1,
            '#markup' => $this->BOCsList(),
        );

        return $build;
    }

    public function BOCsList() {

        ?>

        <div class="wrap">

            <div class="list-bocs">

                <h1>List of files / Liste des fichiers:</h1>

                <ul>

                <?php

                    if(!isset($_GET['start'])) {
                        $start = 0;
                    } else {
                        $start = $_GET['start'];
                    }

                    $exclude_files = array("");
                    $ifiles = Array();
                    $handle = opendir(DRUPAL_ROOT . "/" . PublicStream::basePath() . "/bocs/");
                    $number_to_display = '9';

                    while (false !== ($file = readdir($handle))) {
                       if ($file != "." && $file != ".." && !in_array($file, $exclude_files)) {
                           $ifiles[] = $file;
                       }
                    }

                    closedir($handle);

                    $total_files = count($ifiles);
                    $req_pages = ceil($total_files/$number_to_display);

                    // echo "Nombre total = ". $total_files."<br>";

                    for($z=0; $z<$number_to_display; $z++) {
                        if ($start < 0)
                            $start = 0;
                        $vf = $z + $start;
                        $ifiles_display = explode(".", $ifiles[$vf]);
                        echo "<li class='item-boc'><a class='btn-boc' href=". $ifiles[$vf]. ">".  $ifiles_display[0] . "</a></li>";
                        echo '<br>';
                    }

                    // echo "<br> Pagination = ". $req_pages. "<br>";
                    echo "<a href=\"?start=0\">Premier</a> |";

                    for( $x=1; $x<$req_pages; $x++ ) { ?>
                        <a href="?page=parametres-wp-boc&start=<? echo ($x-1)*$number_to_display; ?>"><? echo $x; ?></a> |

                        <? } ?>
                        <a href="?page=parametres-wp-boc&start=<? echo $total_files-$number_to_display; ?>">Dernier</a> |

                </ul>

            </div>

        </div>

    <?php }

 }

```

Form code

```
<?php

namespace Drupal\bocExtractor\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class BocExtractorSettingsForm extends ConfigFormBase {

    /**
    * {@inheritdoc}
    */
    public function getFormId() {
        return 'bocExtractor_admin_settings';
    }

    /**
    * {@inheritdoc}
    */
    protected function getEditableConfigNames() {
        return [
          'bocExtractor.settings',
        ];
    }

    /**
    * {@inheritdoc}
    */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $config = $this->config('bocExtractor.settings');

        $form['Description'] = array(
            '#prefix' => $this->t('Personnalisez le lien de publications et les classes CSS des BOCs au cas la BRVM changeait de site.'),
        );

        $form['BocExtractor_url'] = array(
          '#type' => 'textfield',
          '#title' => $this->t('BOCs url'),
          '#default_value' => $config->get('BocExtractor_url'),
        );

        $form['BocExtractor_class'] = array(
          '#type' => 'textfield',
          '#title' => $this->t('BOCs class'),
          '#default_value' => $config->get('BocExtractor_class'),
        );

        return parent::buildForm($form, $form_state);
    }
 }

```

Routing:

```
bocExtractor.routing:
  path: '/admin/structure/bocextractor'
  defaults:
    _title: 'boc Extractor'
    _controller: '\Drupal\bocExtractor\Controller\BocExtractorController::DisplayBocExtractorSettingsForm'
  requirements:
    _permission: 'access administration pages'

```

I get list on top and my form on bottom. See this screenshot: http://prntscr.com/e1459i

How can I get what I want?

# Answer
> 0 votes
```
$form['list'] = [
  '#markup' => $this->myList(),
];

```

Put this in your form. No need for the controller, update the routing to go directly to the form class.

Also don't put HTML in your PHP, use a twig template file. Don't use `$_GET` either.

---
Tags: theming, 8, forms
---


title: Display Suite show results from blocks

text:
# Question
Title: Display Suite show results from blocks
I am using Display Suite search as default search module. Is there a way to add the contents of blocks to the search results?

# Answer
> 0 votes
If you enable the Display Suite extras module you can create a display suite field that contains a block. It's included in the DS module you just have to enable it.

---
Tags: 7, display-suite
---


# Question
Title: How do I use dependency injection on \Drupal::moduleHandler() to a Controller?
I am using the following line in a controller class.

```
    \Drupal::moduleHandler()->alter('mymodule_myfunction', $plugin_items);

```

Pareview.sh is giving me this error message.

> \Drupal calls should be avoided in classes, use dependency injection instead.

How should I accomplish this? Do I need to create a constructor, create a method, or a service? If so, what code should the service need? I found an example on "Drupal calls should be avoided in classes, use dependency injection instead" for a case where a service already exists.

# Answer
> 23 votes
In a controller you inject services by using the service container. For example `ModuleHandler`:

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

class MyController extends ControllerBase {

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructs a MyController object
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   */
  public function __construct(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('module_handler')
    );
  }

```

Then you can avoid `\Drupal` calls by using the injected service:

```
$this->moduleHandler->alter('mymodule_myfunction', $plugin_items);

```

You can inject any service, existing ones from core/contrib or services you've defined in custom code in a `*.services.yml` file.

To find a core service name I usually look into `core.services.yml`, because that's the quickest way when you are working on a drupal project in your IDE.

You can use Drupal Console to list all services, not only from core:

```
drupal debug:container

```

You can also use the Devel module, which allows you to search for a name:

```
/devel/container/service

```

---
Tags: 8, services, dependency-injection
---


# Question
Title: How to update user fields from a custom module form?
I need to simply update some user fields from a custom module form.

I try this but it doesn't works :

```
/**
 * Submit the register form
 *
 * @param array $form
 * @param FormStateInterface $form_state
 * @return array|RedirectResponse
 */
public function submitForm(array &$form, FormStateInterface $form_state)
{
    // Create a new user
    $values = $form_state->getValues();

    // User from Drupal\user\Entity\User;
    $user = $this->ctrUserManager->getCurrentUser();

    if($user){

        $user->set('mail', $values['mail']);
        $user->set('field_last_name', $values['field_lastname']);
        $user->set('field_first_name', $values['field_first_name']);
        $user->set('field_civility', [$values['field_civility']]);

        $violations = $user->validate();

        if (count($violations) === 0) {
            $user->save();
            \drupal_set_message('Your profile has been updated');
            return $form;
        }
    }

    \drupal_set_message('Error during user profile update', 'error');

    return $form;
}

```

# Answer
> 9 votes
you are not saving the user correctly, you should call:

```
$user->save();

```

This is an example how to change the username:

```
$user->setUsername('new-username');
$user->save();

```

Here is another example to add a role to a user:

```
$user->addRole('administrator');
$user->save();

```

Can you try the following:

```
/**
 * Submit the register form
 *
 * @param array $form
 * @param FormStateInterface $form_state
 * @return array|RedirectResponse
 */
public function submitForm(array &$form, FormStateInterface $form_state)
{
    // Create a new user
    $values = $form_state->getValues();

    // User from Drupal\user\Entity\User;
    $user = $this->ctrUserManager->getCurrentUser();

    if($user){

        $user->set('mail', $values['mail']);
        $user->set('field_last_name', $values['field_lastname']);
        $user->set('field_first_name', $values['field_first_name']);
        $user->set('field_civility', [$values['field_civility']]);

        $violations = $user->validate();

        if (count($violations) === 0) {
            $user->save();
            drupal_set_message('Your profile has been updated');
        } else {
            drupal_set_message('Error during user profile update', 'error');
        }
    }
}

```

# Answer
> 1 votes
Ok ! I manage to solve my problems, in my buildForm I was using #value instead of #default\_value !

---
Tags: 8, forms, users, entities
---


# Question
Title: How to theme view header Global: Text Area?
I'm trying to stick a flexbox in a view's Header Global: Text area and there's a wrapping paragraph tag that I'm trying to theme away. The views-view.tpl.php only has 'print $header' inside the 'view-header' div so the errant 'p' must be rendered into the $header variable.

I can trim the paragraph tags from the $header variable in template.php with a post render hook, but I'd rather modify a tpl file.

# Answer
> 2 votes
It seems the `<p>` tag is inserted on the `Global: Text Area` header, but not on the `Global: Unfiltered text`. In case it is acceptable for you to use this one, it might fix your issue.

(by the way, in version 8 of Views, the `<p>` tag is not inserted any more for the `Global: Text Area` header)

# Answer
> 0 votes
In settings.php add

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

```

View the source of the page and you will see the theme files being rendered and possible alternatives.

---
Tags: 7, views, theming
---


# Question
Title: Use custom marker when specific checkbox is checked
I am building an events page. The page is using Gmap, Locations and Views modules.

In the content type "Events", I have set a checkbox for "Featured Event", I want these events to stand out in the map, so I would like to use a different marker in the map if the event is a "Featured Event".

Please let me know how to do this. Thanks in advance

# Answer
I would use CSS for this.

* Add your featured checkbox field
* Add a `views-row` class, in the format settings, with the replacement pattern of the value for the checkbox

Now I can't remember if GMap will add that class to the marker rows too. If it does not, I would advise you to override the template for the view and in the class section, add `$fields['field_featured']`, making sure that there is a space before it

* Using that class, you can style it however you want using CSS and/or JS

Hope that helps!
> 0 votes

---
Tags: 7, views, location, google-maps
---


title: Back to the view

text:
# Question
Title: Back to the view
I have created a view that creates pages, each page display the terms of taxonomy of a vocabulary and their articles, how can i link the articles to those pages ?

For example :

* I have the Vocabulary Food : for which i generated a page /articles/apple
* Food has the terms of taxonomy : 'Apple'
* The article : 'Learn about appels' has the term of taxonomy 'Apple'

How do i display a link or breadcrumb for the users on the article 'Learn about appels' that redirect them to the list of 'Food' /articles/apple ?

p.s : i have many many articles, terms of taxonomy and vocabulary.

# Answer
> 2 votes
The default breadcrumb implementation is based on the path.

If you use Pathauto to generate aliases (with a pattern like /articles/\[node:field\_food\_category:entity:name\]/\[node:title\]), so that the resulting alias is /articles/apple/learn-about-apples, then the breadcrumb should just work.

The active menu trail will not, but you can use a module like https://www.drupal.org/project/menu\_trail\_by\_path for that.

A custom link will have to get the term and its URL, you can get that in preprocess\_node() and then print it out in the template wherever you want.

I don't now how you handle content in different vocabularies, if it's a separate node type, or using different category fields or even a single one), based on that it will be more or less complicated to define the pathauto pattern(s), but you could always set up a custom token like \[node:my\_custom\_category\_path\] to deal with that.

I'd suggest you ask more specific questions if some things are not clear yet as this gets too longer otherwise

# Answer
> 1 votes
Using views...

* Make a view block
* Add a field of your terms
* Edit that field's multiple display settings and uncheck "display multiple values in the same row"
* Rewrite that field with `Learn more about <a href="articles/{{Your replacement pattern}}">{{Your replacement pattern}}</a>`
* Include your view block on all content types of article.

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


# Question
Title: How to conditionally attach a stylesheet to a page, preventing anonymous users from getting a cached version?
I'd like to create a module capable of overriding some of the theme's css (for any theme). Think of small things like hiding the image, changing font sizes and colors, etc.

My initial thought was to toggle this using a session variable:

```
/**
 * Implements hook_library_info_build().
 */
function my_module_library_info_build() {
  $libraries = [];
  $libraries['override'] = [
    'version' => '1.0',
    'css' => [
      'base' => [
        'override.css' => [],
      ],
    ],
  ];
  return $libraries;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function my_module_preprocess_page(&$variables) {
  if ($_SESSION['override']['enabled']) {
    $variables['#attached']['library'][] = 'my_module/override';
  }
}

```

This works very well for logged in users, but for anonymous users it only caches the first version of the page (using the status of `$_SESSION['override']['enabled']` at that time). So some pages show the regular lay-out, and some only show the overridden version.

I realized that I probably have to add a cache tag, so I tried adding

```
$variables['page']['#cache']['tags'][] = 'override:' . $_SESSION['override']['enabled'];

```

Assuming this would allow 2 versions of the page to be cached, either for `override` enabled or disabled. But that does not work either.

What needs to be done to allow multiple versions of the same page to be cached and served, depending on a `$_SESSION` variable?

# Answer
Mostly thanks to Berdir I have managed to solve this problem.

I first implemented a custom cache context `cache_context.mymodule_override` (declared as a service) that is supplied with the value of the `$_SESSION`:

my\_module.services.yml

```
cache_context.mymodule_override:
  class: Drupal\my_module\Cache\Context\MyModuleCacheContext
  arguments: ['@request_stack']
  tags:
    - { name: cache.context }

```

src/Cache/Context/MyModuleCacheContext.php

```
class MyModuleCacheContext extends RequestStackCacheContextBase implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('MyModule Override');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return isset($_SESSION['override']['enabled']) ? $_SESSION['override']['enabled'] : 0;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

```

But that still did not work.

Then suddenly I realized that `my_module_preprocess_page()` was an invocation of `hook_preprocess_HOOK()` and that those hooks are probably not called when serving a cached page. So I swapped it with `hook_page_attachments()`:

my\_module.module

```
function my_module_page_attachments(array &$attachments) {
  $attachments['#cache']['contexts'][] = 'mymodule_override';

  if ($_SESSION['my_module']['enabled']) {
    $attachments['#attached']['library'][] = 'my_module/override';
  }
}

```

It works flawless now :)
> 1 votes

# Answer
Related: Cache context drupal don't work.

But your logic is actually depending on the session, and the internal page cache is disabled automatically for users with a session.

So it is more likely that you are having a problem with the dynamic page cache.

Your problem is that cache tags are *not* about caching multiple variations. They are about invalidating already cached things when something changes. So if you have configuration which override value should load which value, then you'd need a cache tag for that, so you can invalidate it when that happens. Also in 95%+ of the cases, you don't need to make up your own cache tags, but just use the default cache tags for entities, config objects and so on.

What you want is a cache context, either the default 'session' or make your own, that doesn't vary for the whole session content but only your key, whould is more efficient. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts

And you should also read https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays to understand when you need cache tags, contexts, ..
> 3 votes

---
Tags: theming, 8, caching
---


# Question
Title: Disable pathauto for nodes created with migrate module
I'm using migrate to import a bunch of nodes and I want to set the path alias during the migration. I am able to import the path alias just fine like so:

```
$this->addFieldMapping('path', 'url_alias');

```

When I look at the imported nodes I see the correct path in the `path` field, but the `Generate automatic URL alias` checkbox is still checked which means the setting is getting ignored.

How do I disable that setting on the node during migration?

# Answer
> 10 votes
You basically need to make sure the `$node` object is passed in with `pathauto` set to false when it is saved.

In your migration class:

```
function prepare(&$row) {
  $row->path['pathauto'] = 0;
}

```

# Answer
> 8 votes
```
$this->addFieldMapping('pathauto')->defaultValue(0);

```

Works for me. Pathauto: Perform aliasing (set to 0 to prevent alias generation during migration See 'drush ma' + name of your class for full description

# Answer
> 0 votes
If you'll sometimes but not always have an incoming path alias, then here's how you can trigger pathauto only when you haven't set an alias.

First, in the constructor, map both `path` and `pathauto`:

```
$this->addFieldMapping('path', 'path');
$this->addFieldMapping('pathauto', 'pathauto');

```

Then, in `::prepareRow()`, set the `pathauto` property depending on whether there's an incoming `path` value:

```
public function prepareRow($row) {
  parent::prepareRow($row);

  if (!empty($row->path)) {
    $row->pathauto = 0;
  }
  else {
    $row->pathauto = 1;
  }

}

```

The result is that if you've explicitly passed in a path that will be used for the alias, while if you haven't Pathauto will kick in.

---
Tags: 7, path-aliases, migrations
---