# Question
Title: Can't set a file->description field in a paragraph programmatically
I am running a drupal 7 migration into Drupal 8 paragraphs. I am retrieving the source fid, mapping from the file migration, getting the dest file id, getting the source file description, and then creating a new file paragraph that just contains a public\_file field.

Problem is that I can't find a way to set the description field of the file? I can create the paragraph with the file fine.

I have tried the following (where field\_files is the name of the field in the paragraph)

```
$file->set('description', $file_title);

```

.

```
$file->field_files[0]['description'] = $file_title;

```

.

```
$paragraph->set('field_files', $file);
$paragraph->set('field_files_descriptions', $file_title);

```

I have tried creating a test paragraph through the front end containing a description field and inspected the values, and there isn't anything obvious where I can set the value,

```
$testparagraph = $paragraph->getFields();
$testfile = $file->getFields();

```

The description value is only here in the paragraph entity

```
$testparagraph['field_files']->list[0]->values['description']

```

I'm at a bit of a loss where I can set this description.

# Answer
The answer was incredibly simple

```
$paragraph->field_files->description = $file_title;

```
> 2 votes

---
Tags: 8, entities, files, paragraphs
---


# Question
Title: (Drupal 6.28) Blocks list suddenly doesn't show correctly
I realized today that blocks list (admin/build/block page) doesn't correctly show all the blocks implemented in the site. Most of the blocks are set as disabled and others are set in the wrong region, while fortunately the site displays every block still perfectly. I have a custom theme (Zen subtheme). The only "strange" thing I did recently was the installation of a new module which involved the assignment of a new block to a region. Is there any way to restore the correct blocks list? Maybe if I don't make any change to blocks system (and save the new configuration), my site will always display correctly, but I would prefer to have the correct blocks list restored. Yes, I could draw a manual scheme of all blocks in the site (pages, views, etc.) and use it in case of disasters, but if I could restore it with a module it would surely be better Thanks

# Answer
That to me looks like an issue with theme update. Did you changed your theme recently. It yes, then try clearing your cache.
> 0 votes

---
Tags: 6, blocks
---


# Question
Title: How to set Form API date_select option values
Creating a date\_select field in a custom form, like this:

```
$date_format = "Y-m-d";
$form['birth_date'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => NULL,
    '#date_type' => DATE_FORMAT_UNIX,
    '#date_timezone' => date_default_timezone(),
    '#date_format' => $date_format,
    '#date_increment' => 1,
    '#date_year_range' => 'now:1910',
    '#date_label_position' => 'within',
    '#required' => TRUE,
);

```

The element it generates for the year dropdown is like this

```
<select>
  <option value="0">-Year</option>
  <option value="1">2017</option>
  <option value="2">2016</option>
  <option value="3">2015</option>
   .
   .
   .
  <option value="108">1910</option>
</select>

```

The year value returned in $form\_state\['values'\] is the value of the option, e.g. if 2017 is chosen the value returned is 1. Is it possible to somehow set the option values like this instead

```
<option value="2016">2016</option>

```

so that the actual year will be returned?

# Answer
This is how I get when I copied **your code without any change**. Option values are correct, but somehow the order got reversed.

```
<select class="date-year form-select" id="edit-birth-date-year" name="birth_date[year]">
    <option value="" selected="selected">-Year</option>
    <option value="1910">1910</option>
    <option value="1911">1911</option>
    <option value="1912">1912</option>
    .
    .
    .
    <option value="2017">2017</option>
</select>

```

Check your Date / Date API module versions. I'm using 7.x-2.8
> 1 votes

---
Tags: 7, forms, datetime
---


# Question
Title: User is notified when new content is created using Rules
I created two groups in one group type.

* Job Post
* Business

Each group has its own content type(same label) and group permissions.

User Story:

"As a user(Job Post) I would like to be able to create a job. A job should contain a description and a job type - for example, plumbing."

As a plumber(Business) I would like to be notified every time a new job is posted that is for plumbing, but not for any other types of work."

How specifically can this be achieve using Rules as I'm a newbie on this module and still trying hard to make setup on this problem.

# Answer
It really depends on your setup. A simple way to achieve this would be to assign business users with a role let's say "Business". Once that's done you can create a trigger on creation of new node, set conditions based on your requirement e.g. user role = "Business" and category = "Plumber" and action to send out an email.

You might need additional modules if you're looking at sending out HTML emails.

Let me know if you need any help.

Thanks
> 1 votes

---
Tags: 8, rules, group
---


# Question
Title: Is it possible to use the same content type field for more than one view?
I am new to Drupal environment. I have question about Views.

I created a view using title and body fields, and added some content. Later I created one more view using same fields (title and body) and added some extra fields.

In the second view, the first view content also displayed. How to avoid this thing?

# Answer
In your view, you can click on Filter and select Content: Type, then select the content type.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: How to implement Facebook style Notifications for Organic Group posts?
I am using Organic Groups, Drupal Commons. If someone posts in group, then all the members should be notified like in Facebook with the number of notifications. Similar to this screenprint:

How can I achieve that ?

**Notes**:

* By Posts I mean a creating new node of ***Post*** content type (default) in Organic Group (and commenting part is not required now).
* I have not implemented any rule for this, can you explain how can I achieve this using rules ?

# Answer
> 1 votes
Below is a blueprint of how you can make this work. To avoid writing a manual as an answer, and to avoid repeating myself, I use some links to other answers (not all of them are mine ...).

## Step 1: Get Rules involved

Use the Rules module to capture events about new nodes being created, which belong to some Organic Group. Have a look to either of the answers to "Get organic group name in a rule?", for 2 possible alternatives to "**`send an eMail`**" to each member of the group.

With that, all that's left is to replace the Rules Action to "send an eMail" with something that shows the number of notifications (as in your question), as further explained below.

## Step 2: Use Messages to create notification entities

Install/enable the Message module also. So that you replace the Rules Action from the previous step to "send an eMail" by a Rules Action to create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages later on (hang on: in a format like your shiny notification button ...).

Here is a summary of what you'd need:

1. Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes.
2. Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples.
3. Possibly you may also want to add a Rules Action to pass any relevant tokens, via Rules, as *Replacement tokens* that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
4. Use Views to display the created messages in the format you prefer.

## Step 3: Transform the view in a notification icon

The Menu Badges module can be used to add such notifications to any **menu item** and/or **menu tab** of your choice. Here are some details about it (from its project page):

> Provides a method for adding iOS-style badges to menu items. (see screenshot)
>
> ### Adding Badges to Menus
>
> Once enabled, go to `Administration > Structure > Menus`, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
>
> ### Adding Badges to Tabs
>
> For adding badges to menu tabs, there is a tab under `Administration > Structure > Menus` called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
>
> ### Badge Types
>
> The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like this:

1. Just create an appropriate view of it, create a menu item or menu tab for that view. Obviously, the view created in Step 2 is the view you want to use.
2. Do a 15 seconds Menu Badges configuration to tell it which menu item/tab you used for it in your view.

**Video tutorials**:

## Step 4: Updating the notification icon

After you completed the above steps, you'll have such shiny notification icon corresponding to the relevant messages. What's left is to implement something to get the icon (ie the counter shown in it) updated, as further explained below.

**Option 1** \- Make the Messages manage-able

This option allows a user to indicate which messages have been read already, and which ones are new (= unread). For that, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

1. Create a flag (using the Flag module).
2. Create a view 'Messages by user' (= improved version of the view specifications described above).
3. Use Rules to flag/unflag messages.
4. Trigger the Rules Component to mark messages (using the VBO module).
5. Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

**Option 2** \- Remove the notification icon after visiting some path

This option will remove the notification icon entirely, after the user visited the dedicated path to display all messages. Refer to the answer to "How to make menu badges count disappear after the page is viewed?" for details about how to do so.

# Answer
> 1 votes
FAB, this answer won't be finished for a while but it should let you get closer to FB functionality when it's done when added to Pierre's answer.

Pierre, I'll assume you're comfortable with Rules Link.

It outputs a JS toggle like below which we can hide with CSS.

```
<div class="rules-link-wrapper rules-link-messages_seen">
  <a href="/seen/1234/_Rr4IZddvsd5kl8VtuNUqFyHPUHQ3LAepC-I1WzujWg" class="rules-link rules-link-js rules-link jquery-once-1-processed" rel="nofollow" title="Seen">Seen</a>
<span class="rules-link-message" style="display: none;">Link executed</span></div>

```

If our menu item has the class `.menu_unread` and the badge is `.badge_unread`, we can do the following to fire our VBO rule.

```
  $('.menu_unread').click( function () {
              // Get the url from the JS link
              var rules_link_url = $('.rules-link-messages_seen a').attr('href');
              $.ajax({
              type: 'POST',
              url: rules_link_url,
              dataType: 'json',
              success: function () {
              // Hide Badge.. Or you could fake set it to zero
                    $('.badge_unread').hide();
                    //So the rule fires once only
                    $(' menu Identifier ').removeClass('menu_unread');
                }
              });
        });

```

This should also work with flag toggles but won't let us unflag immediately like the default behavior.

Why do this? Fire rules from clicks on any element.

---
Tags: 7, nodes, organic-groups, notifications
---


title: How to delete views_data_export_index_%

text:
# Question
Title: How to delete views_data_export_index_%
How to delete these tables "views\_data\_export\_index\_%" create by views data export module, the database getting huge.

# Answer
> 1 votes
The short answer here is to disable & uninstall the Views Data Export module. Once you uninstall it, all the tables should be wiped out. The longer answer is why worry so much about so much size? The `views_data_export_object_cache` seems like it should contain large chunks of data that can be cached from previous exports.

# Answer
> 0 votes
Uninstalling the module is the brute force option since it means losing all settings data also. You can delete the entries of the database table `views_data_export_object_cache` via phpMyAdmin. Make sure the data is not in use.

I once had a lot of entries in that table after applying a buggy patch to Views Data Export. These entries could not get deleted by cron, even after DRUPAL\_MAXIMUM\_TEMP\_FILE\_AGE which is set to 6 hours on a standard install of Drupal. To get rid of the corresponding Watchdog entries I deleted all entries in the `views_data_export_object_cache`.

Regarding your concerns about Backup & Migrate, you can exclude tables from being exported by `backup_migrate` by going to `admin/config/system/backup_migrate/settings/profiles` and editing the standard or any custom profile. Here you can exclude tables or the data in tables from being exported. Some of the tables (cache data mostly, but also watchdog or accesslog) are excluded by default. It's a good idea to have a quick look at these settings whenever you installed contrib modules that come with an own cache data table.

---
Tags: views, importing-exporting
---


# Question
Title: How to save a field value according to another field value and with a user presave hook
I'm using Drupal 8

There are field\_a and field\_b. I'd like to field\_b have the same value with field\_a but different format after user submit his user edit page.

```
my_module_user_presave($account)

{
 $data = $account->field_a->value; // There is no value, since this user did not save yet. This is the problem.
 $account->field_b->value=format($account->field_a);//format function will change the format of field_a value, and this is not a problem
}

```

Since the user did not save yet, so there is no value for field\_a. So I am trying to use drupal\_register\_shutdown\_function as below.

```
my_module_user_presave($account)

{
 drupal_register_shutdown_function('_my_module_user_presave',$account);
}
_my_module_user_presave($account)

{
 $data = $account->field_a->value;
 $account->field_b->value=format($account->field_a); //format will change the format of field_a value.
}

```

Now the field\_a got the value. But field\_b value will not be saved since drupal\_register\_shutdown\_function.

What should I do?

Thanks!

# Answer
> 3 votes
To change a field according to another field:

```
function mymodule_user_presave($account) {

 $data = $account->field_a->value;
 $account->field_b->value = strtoupper($data);

 drupal_set_message($account->original->field_a->value . ' > ' . $account->field_a->value);
 drupal_set_message($account->original->field_b->value . ' > ' . $account->field_b->value);

}

```

To get the original values you would have to use $account-\>original. Otherwise you get the new values. To prove that it's working this is the output in messages from the code above after I entered `abcdef` in field\_a:

> abc \> abcdef
>
> ABC \> ABCDEF
>
> The changes have been saved.

---
Tags: 8
---


# Question
Title: Views filter on field being either empty or equal to uid
I have a views filter on a particular field being empty (`Is empty (NULL)`).

However, I would like to have it check on the field being either empty **or** equal to the current user's uid. I would like to do this programmatically in a custom module, so without installing a contributed module.

The field in question is `$node->field_quality_personal[LANGUAGE_NONE][0]['value']`. So this field can be either `empty`, or it can contain a `uid`.

# Answer
I found the way to fix this. The answer is twofold:

**First** create two filters: one for the field being empty and one for the field being equal to the string "uid". Then as a Filter Criteria option, choose `And/Or, Rearrange` and add the `Or` condition:

This is the result:

**Second** implement `hook_views_query_alter()` to replace the "uid" string we added earlier with the actual user `uid`:

```
/**
 * Implements hook_views_query_alter().
 *
 * Search for 'personal' field to be empty or equal to uid.
 */
function example_views_query_alter(&$view, &$query) {
  if ($view->name == 'myview') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'table.field_quality_personal' && $condition['value'] == 'uid') {
          global $user;
          $condition['value'] = $user->uid;
        }
      }
    }
  }
}

```

That's it!
> 3 votes

---
Tags: 7, views
---


# Question
Title: use two formatter for single field in view
I want to use two formatter 'url,as plain text' and 'count the click happened on this link' for single field in view page

# Answer
One way to use two formatter for single field in view is

1. Add same field two times in view.
2. Set different field formatter.
3. Exclude from display.
4. Add " Global: Custom text ".
5. Go to Rewrite results of " Global: Custom text ".
6. Use Replacement patterns to show that two fields.

How to add Global: Custom text?

For count the click you need to some js coding.
> 1 votes

---
Tags: 7, views, input-formats
---


# Question
Title: How can I change a form input to not be required?
I want to change a form from required = True to False

```
<input data-drupal-selector="edit-attributes-alt" type="text" id="edit-attributes-alt--SMq1dTLhZG8" name="attributes[alt]" value="" size="60" maxlength="2048" placeholder="" class="form-text required" required="required" aria-required="true">

```

I thought that using form alter is the right thing to do but how can i use the $form\_id if keeps changing ?

Here is my code :

```
<?php

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function alt_not_required_form_alter(array &$form, FormStateInterface $form_state, $data_drupal_selector) {
  if ($form_id == 'edit-attributes-alt--????') {
    $form['postal'] = array(
      // Don't make this field required. Use the validate hook.
      '#required' => FALSE,
    );
  }
}

```

# Answer
> 7 votes
The third argument to hook\_form\_alter is `$form_id` \- which will hold the id of the form, not an attribute. You need to know the form id of what you are trying to alter, which is not the literal id of a form input field.

Once you identify what form is showing this field, you can do:

```
function alt_not_required_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id_foo') {
    $form['input_to_affect']['#required'] = FALSE;
  }
}

```

Also, once you know what the form ID is, you can use hook\_form\_FORM\_ID\_alter and eliminate that if statement.

Plus, in your example, since we are altering existing form elements, you do not need to declare it as an array. You just access its properties. `$form['postal'] = array(...)` would take any existing form item named 'postal' and obliterate it, which will likely cause errors in validation or submission.

It might be helpful in learning to use xdebug or devel to dump arguments and variables so you can see what they are. Otherwise, it will be difficult for you to step through this.

# Answer
> 0 votes
This is the solution thanks to you all :

```
function alt_not_required_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'editor_image_dialog' ) {
$form['attributes']['alt']['#required'] = FALSE;
}
}

```

---
Tags: 8, forms
---


# Question
Title: How to add a "continue shopping" button after emptying cart in Ubercart?
This is really a weird issue. I get this on my ubercart page without any possibility for redirection:

One hint I'm eager to try is a drupal\_goto function.

But how do I add this to which file to which line specifically?

# Answer
> 1 votes
For this, you can override `uc_empty_cart()` function with `theme_uc_empty_cart()`; which returns your custom message on empty cart page.

You can get continuous shopping cart URL from Store \> cart setting using `variable_get('uc_continue_shopping_url', '')`.

Example:

```
  // Default function from uc_cart.module
  function theme_uc_empty_cart() {
    return '<p>'. t('There are no products in your shopping cart.') . '</p><a href="'.variable_get('uc_continue_shopping_url', '').'" rel="continuous-shopping">continuous shopping</a>';
  }

```

---
Tags: ubercart
---


# Question
Title: Theme import not changing the color scheme
I created a new theme in d8 and modified some color schemes.

Then I ported that theme to another site and placed in `/var/www-
drupal/themes` and enabled it.

The theme is ported. But the changes made to the color scheme is not ported. Any idea **how to import the color scheme**?

Its still in the default color scheme.

# Answer
> 2 votes
You have to export the color configuration from the old site and import it to the new site.

You can do this in UI. Go to */admin/config/development/configuration/single/export*, select configuration type `Simple configuration` and the configuration name `color.theme.mytheme`. Copy and paste the color configuration to the new site. Use here the single item import section.

If you want to do this automatically when installing the theme you can place the file `color.theme.mytheme.yml` in the `/config/install` folder of the theme.

---
Tags: theming, 8
---


# Question
Title: Fatal error "Cannot redeclare template_preprocess_select()" on every attempt to install modules or themes
> Fatal error: Cannot redeclare template\_preprocess\_select() (previously declared in /Users/ron/Sites/provgmc.dev/core/includes/form.inc:30) in /Users/ron/sites/provgmc.dev/core/includes/form.inc on line 37

This is not an issue with code I've written or altered. I'm just trying to install a theme using the user interface. I tried Bootstrap and Zymphonies, then a simple module or two; they give the same error when trying to install them.

I am using Drupal 8.2.6, running on Mac OS X Sierra, with PHP 5.6.28. I am not using OPCache, and there are no changes from Mac OS pre-installed versions.

I've used Drupal 7 (under El Capitan) in the past, and I have never had any issues like this.

# Answer
Mac OS X should have any of these possible reasons:

* Your site folder name is mixed case
* You cd'd into your site folder name with the wrong case i.e. cd ~/sites/myproject instead of cd ~/Sites/myproject
* Your groups are incorrect (use staff not wheel)
* Drush is using a different version of PHP from MAMP (Check the output of `php --version`.)

If you get a redeclare error running `drush cc all`, check one of the above issues. If `sudo drush cc all` does not produce the error, it could be one of them. In my case, changing the case of my project from ~/Sites/MyProject to ~/Sites/myproject made the issue go away.

For more in-depth discussion, see:
> 0 votes

---
Tags: 8
---


# Question
Title: How to print all Webform messages outside the form?
Does anybody knows how to print all messages (confirmations or error messages) outside the form (created using the Webform module, for example right after the body tag?

I've changed the markup of my alerts. I want them to be full screen, but I can't achieve this, when they're inside the form.

# Answer
> 0 votes
Yes, Webform is working on drupal default message

```
<?php if ($messages): ?>
  <div id="messages"><div class="section clearfix">
    <?php print $messages; ?>
  </div></div> <!-- /.section, /#messages -->
<?php endif; ?>

```

You need to put this code according to your requirement on the template (page.tpl.php).

Finally, webform submission thank you message will be shown on your content section which is coming on node.tpl.php

```
<?php print $links; ?>

```

---
Tags: 7, theming, webforms
---


# Question
Title: Programmatically build module permission list
I'm defining a few new roles in the install hook of my module and one of them is an "admin light" role, which will need some, but not all of the admin account permissions.

I need to pragmatically build a list of available permissions from a pre-defined list of modules (User, Node, Toolbar, etc) and assign them to the role. Without having to hard code all of the permission strings.

In Drupal 7 I could do something like:

```
$modules = array( 'user', 'node', 'toolbar' );
foreach( $modules as $module) {
 $permission_hook = $module . '_permisson';
 if( module_exists( $module ) && function_exists( $permission_hook ) ) {
  user_role_grant_permissions( $rid, array_keys( $permission_hook() ) );
 }
}

```

I'm struggling to find an solution as neat for Drupal 8 seeing as `hook_permssion` has been removed in favor of `$module.permission.yml`. Is there something I'm missing?

**EDIT: Final Solution:** This is the final implementation, just in case anyone else need to do this:

```
  // Define our new roles
  $roles = array(
    array(
      'id' => 'mymodule_client',
      'label' => 'Client',
      'mymodule_permissions' => array(
        'view project status reports',
      ),
    ),
    array(
      'id' => 'mymodule_agent',
      'label' => 'Agent',
      'mymodule_permissions' => array(
        'view projects',
        'view project status reports',
      ),
    ),
    array(
      'id' => 'mymodule_agent_manager',
      'label' => 'Agent Manager',
      'mymodule_permissions' => array(
        'view projects',
        'administer projects',
        'view project status reports',
      ),
    ),
    array(
      'id' => 'mymodule_employee',
      'label' => 'Employee',
      'mymodule_permissions' => array(
        'view projects',
        'administer projects',
        'view project status reports',
        'view project financial reports',
      ),
      // Assign all permissions for the listed modules to this role
      'provider_permissions' => array(
        'user', 'node', 'toolbar'
      ),
    ),
  );

  // At the default level all roles should have the same permissions as authenticated users
  $permissions = Role::load( Role::AUTHENTICATED_ID )->getPermissions();
  // Get permissions for all modules and add them to an array keyed by the module
  $provider_permissions = array();
  foreach( \Drupal::service('user.permissions')->getPermissions() as $key => $permission ) {
    $provider_permissions[ $permission['provider'] ][] = $key;
  }
  // Lets loop our new permissions and create them
  foreach( $roles as $role_values ) {
    // Merge our modules bespoke permissions with the authenticated role permissions
    $permissions = array_merge( $permissions, $role_values['mymodule_permissions'] );
    // Remove our module permissions before we create the role
    unset( $role_values['mymodule_permissions'] );
    // If the role needs access to other module permissions merge them in
    if( isset( $role_values['provider_permissions'] ) && is_array( $role_values['provider_permissions'] ) ) {
      foreach( $role_values['provider_permissions'] as $module ) {
        if( array_key_exists( $module, $provider_permissions ) ) {
          $permissions = array_merge( $permissions, $provider_permissions[ $module ] );
        }
      }
      // Remove the module_permissions before we build the role
      unset( $role_values['provider_permissions'] );
    }
    // Create the role
    $role = Role::create( $role_values );
    // Assign all the required permissions
    foreach( $permissions as $permission ) {
      $role->grantPermission( $permission );
    }
    // Save the role
    $role->save();
  }

```

This code uses the authenticated role as a base, then adds our module permissions (defined per role), and then adds any other modules permissions to roles that require them.

# Answer
You can list all available permissions with PermissionHandler:

```
$permissions = \Drupal::service('user.permissions')->getPermissions();

```

You'll find the module name in the `provider` property of the permissions:

```
$permissions_by_provider = [];
foreach ($permissions as $key => $permission) {
  $permissions_by_provider[$permission['provider']][] = $key;
}

```
> 7 votes

---
Tags: 8, users, installation
---


# Question
Title: Breadcrumb add content type data without any modules
How could I print content type like the breadcrumb, for example

> Home/Content type/Create

# Answer
It is possible using `theme_breadcrumb()`.

Example:

```
/**
 * Implements theme_breadcrumb().
 */
function theme_breadcrumb($variables) {
  // global variable
  $output = '';
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $nid = arg(1);
    $node = node_load($nid);
    $output = '<ul class="breadcrumb">';
      $i = 1;
      foreach($breadcrumb as $value) {
        $output .= '<li class="breadcrumb-'.$i.'">'.$value.'</li>';
      $i++;
      }
      if ($node->type == 'content_type') {
        $output .= '<li><a href="' . url() . '" rel="breadcrumb">' .  $node->type . '</a></li>';
      }
    $output .= '<li class="active">'. drupal_get_title() .'</li>';
    $output .= '</ul>';
    return $output;
  }
}

```
> 0 votes

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


title: "Unknown engine type outputformat"

text:
# Question
Title: "Unknown engine type outputformat"
I did a Drupal 7 update using `drush up` and received the following message, repeated numerous times:

> Unknown engine type outputformat

Since that update, Drush does not work, but rather returns the same message.

How can I fix this problem?

I have Drupal 7.52 and Drush 5.9.

# Answer
> 3 votes
You can install drush to latest version or specified version. I prefer drush 7, you can make this, first uninstall the current version of drush of your server.

i use debian, then i install with

```
sudo apt-get install drush

```

and you need remove

```
sudo apt-get remove drush

```

and later install again with composer

```
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo ln -s /usr/local/bin/composer /usr/bin/composer

sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush
cd /usr/local/src/drush
sudo git checkout 7.0.0  #or whatever version you want.
sudo ln -s /usr/local/src/drush/drush /usr/bin/drush
sudo composer install
drush --version

```

and ready to use drush version 7

# Answer
> 2 votes
Drush 5.9 is very out of date (the current stable version is 8.1.7) and if you updated Drupal several versions very likely broke because of a change long-since accounted for in new versions. There was an issue with similar symptoms reported in 2013 that was resolvable by clearing drush's cache (`drush cc drush`), but the real fix is move to a newer version of drush.

There are several upgrade paths depending on your setup, and how drush was installed the first time. For options see How to Upgrade Drush on Drupal.org and the official drush install directions.

# Answer
> 1 votes
drush 5.x and below fails with multiple **`Unknown engine type outputformat`** error messages when the **Missing Message Fixer** module is active. This module was developed specifically to deal with a problem that appeared when upgrading to Drupal 7.50. It's mentioned in the module's homepage:

> If you are stuck on an old version of Drush (5.x and below). If this module is enabled and you try to run any drush commands, you may get: Unknown engine type outputformat. I would recommend updating your drush or using the GUI version of this module and disabling the module

To me, disabling the module is the solution. Some people get `drush` as a package of LTS Linux distros such as Debian 7 (ships `drush 5.4`), Debian 8 or Ubuntu 14.04 (ship `drush 5.10`), and forcing them to upgrade to the newest is inconsistent with the concept of LTS releases, where every package must be maintained typically for 5 years.

---
Tags: drush, updating
---


title: File directories question

text:
# Question
Title: File directories question
I've started learning Drupal 8 and I have question about file directories.

Previously on D7 I've set directories like this:

files - /sites/all/files

modules - /sites/all/modules

themes - /sites/all/themes

Usually I don't make multisites, so can I set directories like this for D8?

files - /files

modules - /modules

themes - /themes

# Answer
> 3 votes
In Drupal 8, `/modules` and `/themes` are already in the root for you. Within them, you can also do `/contrib` and `/custom` for further organization.

I have never put files in the root, but I suppose *you could* as long as you ignore it with git.

See this answer for more detail: https://drupal.stackexchange.com/a/84851/57

---
Tags: theming, 8, files
---


# Question
Title: How to add jQuery code only to the node add/edit page?
I'd like to execute some jQuery code on a particular element in the node add/edit page of a particular content type. Currently I do that by putting

```
$(document).ready(function() {
    if (window.location.href.indexOf("node/add/CONTENT_TYPE") > -1) {
        ACTION;
    }
});

```

in the theme's .js file. It works, but I think the approach is probably not appropriate, as the test unnecessarily runs everywhere.

Could you please suggest an appropriate way?

# Answer
First, you need to convert your script to be a behavior. Drupal will call defined behaviors, so document ready is not necessary.

Second, you can add this script to specific form pages with drupal\_add\_js and hook\_form\_alter.

1. Use hook\_form\_alter to hook into node add and node edit forms. You can do a check on the `$form_id` argument to ensure it is a node form.
2. Use drupal\_add\_js to add your script file.

Example:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (preg_match('/node_form/i', $form_id) {
    drupal_add_js(drupal_get_path('module', 'my_module') . '/script.js');
  }
}

```

This file will only load when these forms are built, so, you can also remove the line that is checking the window href in the javascript.

The code above is untested, but a general start in the right direction. This code can be placed in a custom module, or, if your admin uses the same theme, you can place it in the template.php of the theme. I strongly recommend a simple custom module.

**Edit**

I believe the form id is preprended by the content type in 6. So, to isolate it to one content type:

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'content_type_node_form') {
    drupal_add_js(drupal_get_path('module', 'my_module') . '/script.js');
  }
}

```

Or you can use hook\_form\_FORM\_ID\_alter to target specific forms too:

```
function mymodule_form_content_type_form_alter(&$form, $form_state, $form_id) {
  drupal_add_js(drupal_get_path('module', 'my_module') . '/script.js');
}

```

Where `content_type` is the name of any given content type (article, page, etc).

Example behavior (mymodule/script.js):

```
(function ($) {
  // you can define multiple behaviors

  Drupal.behaviors.mymodule_behaviorname_one = function(context) {
    // this code should fire automatically when the page has loaded
    console.log('Hello!');
    alert('Hello!');

    // attaching to an element
    $("a", context).click(function(e) {
      e.preventDefault();
      alert('You clicked a link.');
    }
  }

  Drupal.behaviors.mymodule_behaviorname_two = function(context) {
    // this code should fire automatically when the page has loaded
    console.log('Behavior 2');
  }
}(jQuery));

```

More on JS in Drupal (there are some examples in here for 6.x): https://www.drupal.org/docs/7/theming/working-with-javascript-and-jquery
> 1 votes

---
Tags: 6, javascript
---


# Question
Title: How do I deal with discounts/refunds and a payment gateway to achieve accurate reporting for accounting?
First off, this seems like a fairly basic function required for ecommerce.

I was presented with a question today:

> "Will our new website give reporting so accounting can be done from within the website?"

The answer: "Yes! With Commerce Reporting module and Views."

Then came the followup question:

> "Great! So we will be able to add partial refunds, full refunds and discounts to existing orders within the site, have our payment gateway (PayPal) receive the discount/refund requests and have all of this show up in our reporting exports?"

The answer to that: "UMMMMMMM........"

**Simple example:** Customer purchases two items. Item #2 was a mistake. Customer requests a refund via good old fashioned email. We are presented with a question: Does the refund get issued from within Drupal Commerce or within the payment gateway?

What are the solutions for dealing with this?

Does the company still have to rely on the payment gateway (and its ever-changing, unstable export features) for reporting? If so, how does Drupal account for any changes made to an order (i.e. refunds, manual discounts)?

If not, **how do I set up Drupal Commerce to get the reporting accurate to include refunds and any line item price corrections?**

# Answer
> 1 votes
### Step 1 - Enable Commerce RMA

First of all, you need to get something in place to enable the tracking/registration of such refund requests within the Drupal Commerce ecosystem. For that, the Commerce Return Merchandise Authorization module appears to be the best alternative available today. Some more details about this module (from its project page):

> This module aims to extend Drupal Commerce with the Return Merchandise Authorization functionality. It's built on top of the nice Entity API library and using its own Entity Type (CommerceReturn).
>
> **Feature list**:
>
> * Exposes a return of goods workflow on customer side.
> * Ability to separate products that can and cannot be returned
> * Ability to specify a return period, after which the ability to create an RMA is not available.
> * Provide an Admin UI to manage customer returns. Admin can remove or add product and change the prices of returned product.
> * Ability to customize the customer reasons on both product and product type levels.

### Step 2 - Create custom Rules reacting to Rules Events about a CommerceReturn

By using the Commerce Return Merchandise Authorization module, you'll get the **`CommerceReturn`** entity types available. And because of those entity types, it opens up all sorts of custom business logic you may want to implement by using the Rules module. That will allow you to build custom rules that react on the typical entity-related Rules Events, such as:

* After deleting a CommerceReturn.
* After saving a new CommerceReturn.
* After updating an existing CommerceReturn.
* Before saving a CommerceReturn.

### Step 3 - Create custom Views about CommerceReturn entities

As per those CommerceReturn entities, you also get out-of-the-box reporting (and even charting ...) capabilites by simply using the Views module. So for anything that is not already covered by Commerce Reporting, just create the required custom Views.

### Step 4 - Create work-arounds for payment gateway limitations

I'm not aware of any solutions to also automagically take care of the payment gateway processing for such refunds. Especially because I think that there is no way to refund part of a transaction.

However, if you have the Rules module available (see above), you might create custom rules with Rules Actions that (eg) transform such CommerceReturn entities in (e.g.) User Points (piece of cake), so that they can be used to get discounts on future transactions.

### Summary

The above is not a perfect/complete solution, but at least an improvement as compared to the "*requests of a refund via good old fashioned email*" (as in your question). Actually it would at least keep track of such outstanding refunds to be processed.

**PS**: I'm assuming this is about D7.

---
Tags: commerce, payment-gateways, log-messages
---


title: Spanish Version Showing English In View

text:
# Question
Title: Spanish Version Showing English In View
I inherited maintenance of a Drupal 7 site and I don't have much experience with drupal but there is a content type called 'Materials' that we would like to be able to view it's listing representation in different languages. So /materials lists everything in English, but /es/materials should list everything in Spanish but it has both Spanish and English entries. How can I eliminate the English entries so only Spanish ones will show. And, why are English entries displaying in the first place?

Here is the language config for the Materials content type, followed by the Materials Views configuration:

# Answer
> 0 votes
Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the **User's Current Language** is available in the filter criteria form, then verify your configuration at *Configuration -\> Languages -\> detection and selection*: The order should be **URL, Default, User** and not something like **Default, URL, User** (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

**Note**: The Internationalizations Views module only has an **alfa** version for D7, but right now there are over 41K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because *+41K users can't be wrong*, right?

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


# Question
Title: Save patch changes after module upgrading
Am I need to apply patch after every module upgrading? I had a patch, I changed manually handler of views module but yesterday after upgrading Views module I lost all my changes.

Is it possible to apply patch only once?

# Answer
Well...no, not really.

When you apply a patch, you change the contents of the file. When you upgrade the module, you overwrite the contents of the file again, so your changes have been lost. This is a simple file-system issue and transcends Drupal's involvement entirely.

I guess you could set up some fancy file watching script which automatically applies your patch after files have been changed, or automate your upgrades in such a way that the patch is applied straight afterwards - but again that's nothing to do with Drupal as such, it's about your own workflow techniques. You'll also need to factor in the fact that your original patch may no longer apply to the newly updated file(s), so some manual intervention is probably wise.

Patches are of course unavoidable sometimes, but wherever possible don't alter core or contrib modules (for this very reason). 90% of the time you can find a clean way round the problem if you look hard enough
> 1 votes

# Answer
This is a late response, but here is a GIT repo that may help you in applying patches after future updates to a module. If the patch still applies, it gets patched to the module again. If the patch no longer applies, it will error out and not apply the patch - saving you from a major headache). Please see: https://bitbucket.org/davereid/drush-patchfile
> 1 votes

---
Tags: 7, updating, version-control
---


# Question
Title: .htaccess 301 redirects breaking clean URLs
I am trying to make a couple of (I think) very basic rewrite condition / rules in .htaccess.

I placed them as the first rule after `RewriteEngine on`. Things seemed fine locally, and the rules appeared to work in .htaccess tester under each scenario.

However, when I pushed the code live, clean urls stopped working. Everything was only accessible as its route, i.e. `/node/1234` instead of `/foo/page`.

Here are the rules I added:

```
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Custom redirects
  RewriteRule ^ptistore/control/interviews(.*) http%{ENV:protossl}://%{HTTP_HOST}/nurse-interviews [NC,L,R=301]
  RewriteRule ^ptistore/control/news(.*) http%{ENV:protossl}://%{HTTP_HOST}/cpn-numbers [NC,L,R=301]

```

So, any hit on either URL should 301 to the provided URL. I tested them locally and they appeared to work (and not break clean URLs), but when I pushed it up to our Acquia environments, URLs were no longer rewritten.

I wound up implementing a RouteSubscriber to get around this for the moment:

```
/**
 * Class RedirectSubscriber
 * @package Drupal\mymodule_redirects\EventSubscriber
 */
class RedirectSubscriber implements EventSubscriberInterface {

  public function redirectIndexPHP(GetResponseEvent $event) {
    $request = $event->getRequest();
    $uri = $request->getRequestUri();

    if (preg_match('/ptistore\/control\/interviews\/.*/i', $uri)) {
      $response = new TrustedRedirectResponse('/nurse-interviews', 301);
      $event->setResponse($response);
    }

    if (preg_match('/ptistore\/control\/news\/.*/i', $uri)) {
      $response = new TrustedRedirectResponse('/news', 301);
      $event->setResponse($response);
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('redirectIndexPHP', 39);
    return $events;
  }
}

```

Which works... but I really would rather it live in .htaccess.

Did I just place my rules too early in the file? How can I correct this?

# Answer
No idea how acquia hosting works, but I doubt they respect your .htaccess and possibly don't even use Apache.

Maybe they have their own configuration settings for that, I know that platform.sh (which uses nginx) does.

If not, then you don't really have a choice but to do it in Drupal.

You could also try the latest redirect release which has a new submodule that supports domain and wildcard based redirects.
> 1 votes

---
Tags: 8, .htaccess
---


# Question
Title: Edit meta tags per entity via field or entity property?
Is there a way in Drupal 8 to override the global meta tags at the entity (node) level when adding or editing content? I thought the option previously existed in 7.x, but I am not seeing it in 8.x.

If not, is there a way to alter the meta tags when preprocessing a node to inject them based on node fields in code?

# Answer
Yes, there is.

All you need to do is add the Meta tags field to the node types where you want to have this.
> 2 votes

---
Tags: 8, meta-tags
---


# Question
Title: Entity Query using conditions that ignore special characters
I have an entity query where I search the body for user provided text. I'm performing the query like so

```
$searchterm = 'test';
    $query = \Drupal::entityQuery('node')
            ->condition('status', NODE_PUBLISHED)
            ->condition('body', $searchterm, 'CONTAINS');

```

This gives me the results I need, but what if I run into a situation where the body contains the text 'test-1' but I want searches for 'test1' to bring up that result.

Is there anyway that I can write a query that ignores all special characters in the field I'm searching?

# Answer
> 3 votes
Drupal does not supply a solution to your problem out of the box. However you can create a list of all the permutations and create a condition for each of them.

---

## Code snippet

```
$searchterm = 'test-1_2 3';

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED);

// permutation generator function.
$permutations = function($source_term) {
  $result = [$source_term];
  $unprocessed_terms = [$source_term];
  $regex = '/[\W_]/'; // Selects all the non-alphanumeric characters and _

  while (!empty($unprocessed_terms)) {
    $unprocessed_term = array_pop($unprocessed_terms);
    $matches = [[]];

    // By using PREG_OFFSET_CAPTURE we get the position of the match.
    preg_match_all($regex, $unprocessed_term, $matches, PREG_OFFSET_CAPTURE);
    foreach($matches[0] as list($match, $pos)) {
      $result[] = $unprocessed_terms[] = substr_replace($unprocessed_term, '', $pos, 1);
    }
  }

  // the above algorithm will create duplicates.
  return array_unique($result);
};

// Create an OR condition group that contains a
// condition for each permutation term.
$query->condition($or = $query->orConditionGroup());
foreach ($permutations($searchterm) as $term) {
  $or->condition('body', $term, 'CONTAINS');
}

$nids = $query->execute();

```

---
Tags: 8, nodes, database
---


# Question
Title: How can I quickly re-save all the nodes on my site (to trigger a rule that activates on content update)?
I made some mistakes configuring a certain content type on my site. To fix these mistakes, I made a rule that performs some actions "when existing content is updated." However, I don't want to go through my site and manually save all the nodes again one by one. Is there a way to use Rules or Views Bulk Operations to quickly re-save all the nodes?

# Answer
> 22 votes
VBO has an "Execute PHP code" action. Run it, and input "node\_save($entity);" (without the quotes) in the textbox. That will do the trick, while handling the timeouts for you.

# Answer
> 14 votes
I don't know about rules or VBO but you could use a short code snippet to get the same result:

```
$nids = db_query('SELECT nid FROM {node}')->fetchCol();
foreach (node_load_multiple($nids) as $node) {
  node_save($node);
}

```

If you've got a lot of nodes that might take a bit of time so if your server allows it it'd be a good idea to extend the time limit at the start of that code, perhaps to unlimited if this is a one off:

```
set_time_limit(0);

```

# Answer
> 12 votes
You can use the node\_mass\_update() function:

```
module_load_include('inc', 'node', 'node.admin');
$nids = db_query('SELECT nid FROM {node}')->fetchCol();
node_mass_update($nids, array());

```

It's very good as you don't need to care about the time limit. Batch process for nodes update will start automatically if there are more than 10 nodes.

# Answer
> 5 votes
Update: I just created Resave All Nodes. For now it only contains a form to trigger a batch process to resave all nodes of selected node types. Currently in alpha. I plan to add a Drush command (beta) and some tests (stable) as well.

---

There's Resave Nodes. It's intended to used on cron runs. But you can also trigger it manually. Simply choose which content type's nodes should be resaved.

Before you can run the manual resave by hitting "Resave Nodes Now" you once have to "Save Configuration" (chose a cron type and content type).

# Answer
> 2 votes
Go to admin/content and filter by your content type - published only. Select all and then select "change value" from the operations drop down. Click 'execute'. On the next page, select 'status' from the properties and leave published. Click 'next' All the published nodes will resave with no changes.

Repeat for unpublished nodes (but select unpublished as the property).

---
Tags: rules
---


title: How to Migrate from SQLite to MySQL?

text:
# Question
Title: How to Migrate from SQLite to MySQL?
I built a Drupal 8 site using SQLite. Performance is awful, so I'd like to use MySQL instead. What's the best way to go about this?

A step-by-step guide would be nice, but any advice and tips are appreciated.

Thanks in advance

# Answer
It has been a while since I've used their product (MSSQL to MySQL) but a place to start might be here:

https://dbconvert.com/sqlite/mysql/

For me it worked flawlessly converting a MSSQL database with 10 years of data into MySQL so I could import it to Drupal 7. I would expect the same quality in this sister product, it's worth a look.
> 0 votes

---
Tags: 8, database, migrations, backups
---


# Question
Title: Creating Custom Modules tutorial doesn't work - help!
I'm trying to teach myself how to create a custom module using Drupal 8, and followed the instructions on their website at this Drupal.org documentation page

I created the folders, hello\_world.info.yml, hello\_world.routing.yml and HelloController.php pages and have been over them time and time again looking for typos, but can't find any.

I've got to the step to add add a routing file. The module appears in the Extend area, but when I enable it and click Install, after a short pause I get the error "The website encountered an unexpected error. Please try again later."

When I go back to thet Extend, the module is ticked and I presume installed.

However when I then try to display it using the URL "/hello", I get a "Page Not Found". Not only that, but every time I try to clear the cache, there is a delay and I get the same "Website encountered..." error again. I can only clear the cache by uninstalling the module.

I've included the content of the three files below:

**/modules/hello\_world/hello\_world.info.yml**

```
name: Hello world Module
description: Creates a page showing "Hello world"
package: Custom
type: module
core: 8.x

```

**/modules/hello\_world/hello\_world.routing.yml**

```
hello_world.content:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

```

**/modules/hello\_world/src/Controller/HelloController.php**

```
<?php
    namespace Drupal\hello_world\Controller;

    use Drupal\Core\Controller\ControllerBase;

    class HelloController extendes ControllerBase {

        public function content() {
            return array(
                '#type' => 'markup',
                '#markup' => $this->t('Hello World'),
            );
        }
    }

```

Does anyone have any suggestions what might be wrong?

# Answer
> 3 votes
```
class HelloController extendes ControllerBase {

```

You spelled extends incorrectly.

---
Tags: theming, 8, routes
---


title: Drupal Email Verfication

text:
# Question
Title: Drupal Email Verfication
How to verify email of registered users and only verified users are allowed to login. For that I have set up status of user to 'Blocked' immediately after registration so that they can't login. But when I access verification link I am getting 'Access Denied' error. How could I resolve this issue?

# Answer
Admin -\> Config -\> People -\> Account settings

Under "Registration and cancellation", select "Visitors, but administrator approval is required".
> 2 votes

---
Tags: 7, emails
---


# Question
Title: How to translate 'ago' in interval time formatter in views?
Googling the only thing I've managed to find is: https://www.drupal.org/node/2800563

What can I do to translate 'ago' or omit it from printing?

# Answer
can't we do like this?

```
  //Get today's date.
  $today = getdate();
  //Calculate the date "1 week ago".
  $start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 7), $today['year']);

```

Also, you can change those zeroes to make 'n' hours/ minutes/ seconds ago.
> 0 votes

---
Tags: views, 8
---


# Question
Title: Use a custom view for the front page without alias
I am a Drupal Newbie, I have not learn't all the features yet.

I want to do the following.

I have created custom `twig` template for the front page.

By default I have default `Frontpage` view. I deleted it.

I've created a new view. And I want to use it as my default view for the front page, but I can't figure out how to do this.

I know about setting front page url in global settings. But it requires alias. Or it uses default frontpage.

So basically my questions are

1. How to create a view without alias, not exactly without, but with `/` or nothing for the front page.
2. How to associate a pathless view with a front page ?

I would be grateful for any help.

# Answer
> 0 votes
> How to create a view without alias, not exactly without, but with / or nothing for the front page.
>
> How to associate a pathless view with a front page ?

1. You cannot create a pathless view **page**. (The default front-page view has a `/node` path)
2. Create a **block** View

Then go to blocks, and place your view block in a region. Content region perhaps?

Under Visibility settings check-mark "display only in" and put `<front>` so it only gets displayed in the front page.

# Answer
> 0 votes
As No Sssweat explained, you cannot create a pathless view page. I would recommend installing Empty Page module to get a blank front page and then assign a view to a content region.

You can have your url as / with empty page if you like. Give it a go and let me know if any issues.

---
Tags: views, theming
---


# Question
Title: Unable to choose an installation profile on a multi-site installation
I installed drupal 8 with the open social installation profile using composer. Now I want to turn this drupal install into a multi-site installation where some of the other sites don't use this installation profile. But when creating a new site (I know how to do this from my D6/7 days) I can't select an installation profile. Instead the Open Social installer is always run and it's installation profile always gets applied. I figured out it is probably due to the vendor stuff that composer does when installing drupal and open social. It changes some things in the vendor folder that change the drupal 8 installation procedure. But the question that remains is if it is possible to still use this install with the standard drupal installation profiles.

Or a perfectly acceptable alternative for me would be to make a base install of drupal8 and afterwards add the opensocial installation profile so I can still choose my installation profiles. I guess that would mean ditching composer? Or maybe not? I don't really know because I am not familiar with how composer changes the drupal workflow from the way I used to work with it in d6/7.

# Answer
> 2 votes
In the .info.yml file, do no put `distribution` statement, ss mentioned in this guide:

```
# Optional: Declare your installation profile as a distribution
# This will make the installer auto-select this installation profile.
# The distribution_name property is used in the installer and other places as
# a label for the software being installed.
distribution:
  name: Distribution Name

```

---
Tags: 8, multi-sites, installation-profiles
---


title: Custom block, dynamic based on URL

text:
# Question
Title: Custom block, dynamic based on URL
## Goal:

Custom block with dynamic non-entity content that varies with the URL.

Specifically, the block has a form with `select` elements, and the `selected` items should be determined by the current URL path.

## Problem:

The rendered block intermittently displays incorrectly, as though it was rendered for another URL different than the current URL.

## Code:

### Plugin:

```
<?php
/**
 * @file
 * Contains \Drupal\my_module\Plugin\Block\ViewsFiltersResources.
 */

namespace Drupal\my_module\Plugin\Block;

  use Drupal\Core\Block\BlockBase;
  use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a 'ViewsFiltersResources' block.
 *
 * @Block(
 *   id = "my_module_views_filters_resources",
 *   admin_label = @Translation("Resources: filters"),
 * )
 */
class ViewsFiltersResources extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs a new ViewsFiltersResources.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition
    );
  }

  public function getCacheContexts(){
    return ['url.path'];
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $request_url = \Drupal::request()->getRequestUri();
    $url_parts = explode('/', $request_url);

    return array(
      '#theme'       => 'my_module_block_views_filters_resources',
      '#issue_areas' => array(
        'all' => 'All Issue Areas',
        'area-one' => 'Area One',
        'area-two' => 'Area Two',
        ),
      '#resource_types' => array(
        'all' => 'All Resource Types',
        'news_story' => 'News Stories',
        'press_release' => 'Press Releases',
      ),
      '#active_area' => isset($url_parts[2]) ? strtolower($url_parts[2]) : NULL,
      '#active_type' => isset($url_parts[3]) ? strtolower($url_parts[3]) : NULL,
      '#active_keywords' => isset($url_parts[4]) ? urldecode(str_replace('+', ' ', $url_parts[4])) : NULL,
      '#attached' => array(
        'library' =>  array(
          'my_module/my_module-resource-filters'
        )
      ),
    );
  }
}

```

### Theme function:

```
function my_module_theme() {
  return array(
    'my_module_block_views_filters_resources' => array(
      'variables' => array('issue_areas' => NULL, 'resource_types' => NULL, 'active_area' => NULL, 'active_type' => NULL, 'active_keywords' => NULL),
      'template' => 'my-module-block-views-filters-resources',
    ),
  );
}

```

### Template:

```
<section{{ attributes.addClass('filters resources-filters bg-light-80') }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {% block content %}
    <div class="row">
      <div class="column">
        <form id="resources-filters-form" class="filters-form resources-filters-form clearfix views-exposed-form" method="get" accept-charset="UTF-8">
          <fieldset class="filters-fields resources-filters-fields">
            <label class="filters-label">Show Me</label>
            <div class="filters-issue-area filters-item form-item">
              <select class="filters-issue-area-select filters-select form-select" id="edit-area" name="area">
                {% for value, name in issue_areas %}
                  <option value="{{ value }}"{% if value == active_area %} selected="selected"{%endif %}>{{ name }}</option>
                {% endfor %}
              </select>
            </div>
            <div class="filters-resource-type filters-item form-item">
              <select class="filters-resource-type-select filters-select form-select" id="edit-type" name="type">
                {% for value, name in resource_types %}
                  <option value="{{ value }}"{% if value == active_type %} selected="selected"{%endif %}>{{ name }}</option>
                {% endfor %}
              </select>
            </div>
            <div class="filters-keywords filters-item form-item">
              <input type="text" class="filters-keywords-text filters-text form-text" id="edit-body-value" name="body_value" value="{{ active_keywords }}" maxlength="128" placeholder="Enter optional keywords...">
            </div>
          </fieldset>
          <div class="filters-actions form-actions" id="edit-actions">
            <input type="submit" class="button large filters-submit js-form-submit form-submit" id="edit-submit-resources" name="" value="Update">
          </div>
        </form>
      </div><!-- column -->
    </div><!-- row -->

  {% endblock %}
</section>

```

## Questions:

1. Any thoughts on what could cause incorrect caching here? Could this be related to https://www.drupal.org/node/2529980?
2. Is using `getCacheContexts()` supposed to result in the desired behavior? What's the difference between using `getCacheContexts()` vs using `'#cache'` in the render array?
I have searched and read the API docs on `getCacheContexts()`, but it's still not clear to me what exactly it does.
3. If `getCacheContexts()` is appropriate for this purpose, is it used correctly here?
In core, I've seen cases that look like this one, and other cases that merge a new value into the result of `parent::getCacheContexts()`.

# Answer
> 2 votes
**Answers**

1. No, your block is not empty
2. `#cache` is bubbleable metadata the same as `#attached`. So if you use one of them you can use both.
3. If you use `getCacheContexts()` then you extend the parent method and it's correct OOP to merge the result from the parent.

Merge contexts:

```
 public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), ['url.path']);
  }

```

**Question 2. + 3. in more details**

If you build a render array then the straightforward thing to do is to attach the correct metadata, because the render array should not be restricted to a block. It should contain all metadata it needs to work in all places. On the other hand if you build a block plugin and you don't know what kind of render array it contains if any, then it's better to use `getCacheContexts()`. This is part of the cacheable interface all object have, that are cacheable in Drupal:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Cache%21CacheableDependencyInterface.php/interface/CacheableDependencyInterface/8.2.x

**Debugging**

Look in the database table `cache_render`. After clearing the cache as you visit pages with different urls there should be cache entries for the block that vary by the cache context `[cache_context]`.

```
entity_view:block:block_name:[cache_context]=...

```

---
Tags: 8, blocks, caching
---


# Question
Title: Implementation of drupal behaviours in drupal garden sites
If it possible to implement drupal behaviours in drupal garden site? if yes then what will be the syntax for it?

# Answer
Drupal behaviors are just javascript functions, so the answer is pretty simple:

If the service you're using allows you to add javascript to your pages, then yes, you can use behaviors. If it doesn't, you can't.

Syntax will be identical unless the service uses a patched version of Drupal core. If you have reason to believe they might do, it would be wise to get in touch with them directly and ask.
> 1 votes

---
Tags: javascript
---


title: Set value after unpublishing content

text:
# Question
Title: Set value after unpublishing content
I'm using drupal 8 and the scheduler module to automatically unpublish custom content after x days have passed.

While unpublishing a boolean field from the custom content needs to be enabled/disabled.

So far I tried rules module *after\_a\_node\_has\_been\_unpublished\_by\_scheduler with Condition: Entity has field* with *Action: Set a data value* Unfortunatelly the action does nothing.

What else could I try?

# Answer
You can create your custom code in a hook\_cron, and you can handle your verifications following the date of publication.
> -1 votes

---
Tags: 8, rules
---


# Question
Title: Change a normal submit 'input' type to 'button' type with button tag
Is it possible in Drupal 8 to change a regular form submit button from Drupal into a button tag?

This is the output I need to achieve:

```
<button type="button" class="search-box__button">
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

```

# Answer
Well that was quick... I used my intuition and was able to accomplish it by doing the following:

### In mytheme.theme:

```
/**
 * @param $suggestions
 * @param array $variables
 */
function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-twig-suggestion'];
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

```

### In input--submit--search-results-submit.html.twig

```
{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<button{{ attributes }}>
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

```

Form still submits and functions as expected. Is this the general approach or at least acceptable? I will go with this unless there is a better way.
> 16 votes

# Answer
You simply could use `inline_template`.

```
$build['hello']  = [
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="search-box__button">
     <svg class="icon search-box__open">
       <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/build/img/svg-sprite.svg#icon-search"></use>
     </svg>
   </button>',
];

```
> 6 votes

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


title: How can I translate the menu item?

text:
# Question
Title: How can I translate the menu item?
I have installed the Internalization module and after that edit the Main menu setting and select the translate and locale.

and add translate as per menu item. But when I switch the language its all the menu item still shows in english

Have a look I have only these options:

# Answer
> 4 votes
Below is how I resolved this before, for a multilingual D7 site with menus in multiple languages. In this case for the "main menu", but you can do this for any menu.

# Step 1

Use a single "main menu" that contains all menu items for all languages, so not 1 main menu for only EN menu items and another main menu for only (e.g) FR menu items.

# Step 2

Configure the multilingual options of the menu via the Menus administration page and follow the "edit menu" link to the menu in question. For the Main menu that would be `admin/structure/menu/manage/main-menu/edit`.

For "Translation Mode", use the option "Translate and Localize". So that menu items with language will allow translations, and menu items without language will be localized.

# Step 3

Add the links for any of your languages to the single menu, but make sure to specify for each of these links for which specific language you want the link to be shown. Or as an alternative, if you have menu items that should be shown for all languages, make sure such link is marked as "Language Neutral".

# Summary

For any language the very only (single) "Main menu" is shown. However based on the selected language, only those menu items in it will be shown that match the selected language.

Not sure if it is the best/most elegant way to make this work, but IMHO it works like a charm ...

# Answer
> 1 votes
Did you check those checkboxes? This screen you will find at this URL admin/config/regional/language/configure

Please checked those option after you need to create a menu in both languages like create menu in a single language after using translate tab translate it.

When you check your site in your language, Please check that language postfix is added in URL Like(/en = English, /de = German)

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


# Question
Title: Duplicate paragraphs from node type FOO to node type BAR
I have two content types: FOO and BAR. These content types have a field called "field\_paragraphs" of type "paragraph". And other fields of course.

Now in a situation my user can click a button (that call one of my function defined via hook\_menu) and "copy" content of type FOO to a new content of type BAR, so I need to copy, NOT CLONE, field\_paragraphs from FOO to BAR: I need to create a standalone copy of "field\_paragraphs"; like two different insert.

I have searched on google but all talk about "clone", but in my case I need to copy so I can not use "clone" module.

How can I do this ?

M.

# Answer
> 2 votes
EDIT: You can now find a better explanation with the code here.

I know this is old but maybe someone comes here looking for an answer like me, this is tested on Drupal 8.

I found this issue and after looking at last patch, I implemented :

```
$nodeDuplicate = $node->createDuplicate();

foreach($nodeDuplicate->field_paragraphs as $field){
    $field->entity = $field->entity->createDuplicate();
}

$nodeDuplicate->save();

```

And I got a duplicate node with duplicated paragraphs fields. If you look at the patch you will see how to add a button to Drupal etc.

Just a note `field_paragraphs` is the name of my field in the content type, change it with your own.

I didn't have any problem doing it this way, maybe someone has a better way but I did not find it, also at the time of writing this there is still no ported modules for cloning nodes in Drupal 8.

# Answer
> 0 votes
This is an example that could give you an idea how to do it.

```
   function copy_node_foo($node) {
      if ($node -> type == "FOO") {
          $node_bar = new stdClass();  // Create a new node object
          $node_bar->type = 'BAR';  // Content type
          $node_bar->language = LANGUAGE_NONE;
          node_object_prepare($node_bar);  //Set some default values
          $node_bar->title = 'Your node title';
          node_bar->field_paragraphs = node->field_paragraphs;
          /* others properties .... */
          node_save(node_bar);
      }
    }

```

---
Tags: nodes, entities
---


# Question
Title: How can I make a template for a product type in Commerce?
I want to be able to write my own markup for the fields (see image below) of each product type – how do I do this? My main reason for this is that I want to group them with my own HTML rather than the default provided.

I've tried using `<?php print render($content['field_available_colors']); ?>` and `<?php print render($content['product:field_available_colors']); ?>` in the regular node--\[content\_type\].tpl.php and that didn't work.

I've also tried making a template specific for the product type, but nothing happens. I've been looking at the latest post in this thread, but I can't get any of the suggestion to work either...

I'd very much appreciate some help here, what am I missing?

---

Tried to add the following to template.php, but have no clue what to do with it really. Haven't worked in this way before at all, and this seems pretty steep.

```
function mythemename_preprocess_node(&$vars) {
  $product_display_types = commerce_product_reference_node_types();
  if (isset($vars['type']) && isset($product_display_types[$vars['node']->type])) {
    $vars['theme_hook_suggestions'][] = 'node__product__type__' . $vars['node']->type;
    $vars['classes_array'][] = 'node-product-type';
    if ($vars['view_mode'] == 'product_list') {
      $vars['theme_hook_suggestions'][] = 'node__product__type__product__list';
      $vars['classes_array'][] = 'node-product-type-product-list';
    }
  }
}

```

# Answer
> 1 votes
I believe that it is a product reference field, and therefore, the template suggestions are different. That is why creating random node template files is not having any effect. What you want to target is the entity being referenced.

You should check what templates or theme hooks exist in Commerce, and derive the templates from that. You can also add your own suggestions when preprocessing.

Here are some threads that will help:

Note that if you add to template.php or introduce new templates, you will need to clear your caches so it is picked up by Drupal.

A bulletproof way to find out would be to do `mytheme_preprocess_entity($variables)` in your themes template.php file, and dump out `$variables` when it is preprocessing a product entity. Within it, you will see possible template suggestions *for the product entity itself*.

The same applies for fields as well. `template_preprocess_field`: https://api.drupal.org/api/drupal/modules%21field%21field.module/function/template\_preprocess\_field/7.x

---
Tags: 7, theming, entities, commerce
---


# Question
Title: the WYSIWYG editor doesn't show up, drupal 7
I installed the CKEditor in Drupal 7, following the steps in the documentation. I set up the right permissions and the text options and I cleared the caches, but when I want to add or edit some content, I have only the plain textarea.

However, when I navigate to *Administration » Configuration » Content authoring » CKEditor*. and edit the Filtered and Full HTML, the WYSIWYG editor shows up as it should when I expand the *Editor Appearence* tab, so I assume it's well installed.

What I find peculiar is that when I navigate to *Administration » Structure » Content types*, select a content type and click *manage fields* and *edit* for the `body` field the area just below the text: "The default value for this field, used when creating new content." is still the old textarea. I don't find any option to change it, as if the WYSYWYG editor wouldn't exist.

Anyone has an idea, a solution? Is it something I miss here?
Thanks a lot for your help.

# Answer
It sounds as if you've selected "Plain text" instead of "Filtered text" as your default text processing option. To change this, navigate to *Administration » Structure » Content types*, select the content you experience problems with and click *manage fields* and *edit* on the `body` field (and other text fields you want to use the wysywyg editor). Make sure that the preset text format for that text field is set to to one of the formats configured for wysywyg (e.g. *Filtered HTML*).

To make sure that *Filtered HTML* is selectable, you need to make sure that the setting for "Text processing" is set to *Filtered text* (not *Plain text*):

Press *Save settings* after changing this.

Make sure that when you create content, a text format that is set up to use use WYSYWYG (e.g. *Filtered HTML*) is selected. The screen dump below shows how the pull-down menu immediately below the text field for content should look like:

**Other thinks to try when debugging a CKEditor setup:**

Here are some more tips on debugging a CKEditor setup. They probably don't apply to you, but may help others that arrive at this question while searching for a cure for CKEditor blues:

1. Clear the cache:

Remember to clear the cache after you've changed *any* setting that has something to do with wysiwyg. Not clearing the cache is probably the most common source for CKEditor not showing up as you would expect.
2. Check out that roles are configured correctly:

Navigate to your text formats: *Administration » Configuration » Content authoring » Text formats* and ensure the roles are configured correctly.

* Add the roles you want to use wysiwyg to *Filtered HTML* and *Full HTML*.
3. Check out that profiles are set up right:

Navigate to your ckeditor profiles: *Home » Administration » Configuration » Content authoring » CKeditor*

Go to the profiles, and verify that the text formats for the profile are set, and the editor appearance is set properly.

* Under *Basic Setup*, check the text formats that apply
    * Under *Editor Appearance*, set default state to enabled, and show the toggle.

PS: For a secure use of WYSYWYG, I recommend using a custom text format filtered with the WYSIWYG Filter. How you do this is described in this tutorial. However, *first* get it working, *then* start tweaking to make it secure.
> 2 votes

# Answer
Sometimes, when I create a WYSIWYG field, and doesn't load the editor I do the following:

1. Check the *Enable by default* for the *Filtered HTML* profile:

*Home » Administration » Configuration » Content authoring » Wysiwyg profiles » CKEditor profile for Filtered HTML*

2. Set the Text processing in the Content Type settings:

*Home » Administration » Structure » Content types » Article » Manage fields Content*
> 0 votes

---
Tags: 7, wysiwyg
---


title: Using attributes in templates Twig

text:
# Question
Title: Using attributes in templates Twig
I am a newbie. I have experience working with `Twig` but in Drupal it is used in another way.

I have seen a lot of code like that

```
<section{{ attributes.addClass(classes) }}>

```

And of course I read this article https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

There are a lot of examples and that is great.

But why do I need this, how could I use them to improve readability and flexebility ?

You should agree that `attributes.addClass(classes)` method is doing something like adding class to the existing attributes, but not returning the output of all attributes.

Could you tell me please why this attributes variable is useful, how can I use it to provide better decoupling or whatever it is used for. Why not just to keep classes directly in a template file, is it possible to add them from admin panel ? Thanks

# Answer
> 2 votes
A general reason is that contributed modules or theme code can hook in and add attributes in. Outputting `{{ attributes }}` ensures that they are all printed without hardcoding them all in templates.

Here is an example.

I want to add a class and data-attr to an input field on a particular form. Instead of hardcoding it, I add to the `#attributes` key, and they are rendered out for me since `{{ attributes }}` is printed on the element:

```
/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

```

My class and data-attr are added to that element automatically. I don't need to know what twig file is rendering it, I just need to provide the attributes I want to add on to, or print out.

Here are some links that explain a bit more in depth what Attributes are:

I heard that in 8.3.x it will be easier to work with attributes, but I can't find the thread offhand.

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


title: hook_form_alter multiple Content Type

text:
# Question
Title: hook_form_alter multiple Content Type
How I use hook\_form\_alter with multiple Content Type..

```
function custom_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'register_node_form' || 'session_node_form'){

  if(empty($form['field_event_ref']['und'][0]['nid']['#default_value']))
     {
    $form['field_event_ref']['und'][0]['nid']['#default_value'] = arg(3);
     }
    $form['field_event_ref']['und'][0]['nid']['#disabled'] = True;
     }
  }

```

I want Here to Get Both Of (Register) and (Session) Content type to be alter..

# Answer
> 2 votes
The code is incorrect, it should be:

```
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'register_node_form' || $form_id == 'session_node_form') {
    // code here that alters forms for both content types
  }
}

```

The if statement is missing the second `$form_id`.

Also, I wouldn't name the module `custom`. If you are doing that as a demonstration purpose, a typical convention is to use `mymodule_` in posts.

A more readable way:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $content_type_forms = array('register_node_form', 'session_node_form');

  if (in_array($form_id, $content_type_forms)) {
    // code here that alters forms for certain content types
  }
}

```

# Answer
> 0 votes
You can use hook\_form\_BASE\_FORM\_ID\_alter

```
function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Run with all form  content type
}

```

---
Tags: 7, hooks, forms
---


# Question
Title: How to specify which form mode to use for a content type
I created a **`new_form_mode`** for a content type in **D8** and removed some fields in that form mode from **`Manage form display`** tab of the **`content type`** by selecting that **`new_form_mode`** . But how can i select that form should be displayed for that content type instead of **`default`** form mode?

# Answer
Unlike view modes you can't select form modes out of the box. To manage form modes you need a module. You can try one of these:

https://www.drupal.org/project/form\_mode\_control

https://www.drupal.org/project/form\_mode\_manager
> 9 votes

---
Tags: 8, forms
---


# Question
Title: User profile fields: Get count of fields with value XYZ
All user profiles contain these fields:

* **field\_age** (integer)
* **field\_category** (list: "Category A", "Category B", …, "Category Z")

I want to get the number of users with the value "Category A", "Category B" etc. for the landing page.

**How can I get the count of users for each answer?** I want to display the number on the landing page for every visitor.

---

The data **does not need to be live data**. It may be read from a file that is re-generated every 24 hours.

# Answer
You can create a view as a block using users as the base table (Structure\>Views\>Add View and set show=Users and check "Create a Block"). Then turn aggregation on in the advanced settings. Then add the field\_category field and select "Group Field". Next add field\_category a second time and select "Count". This should give you a column of each category, and the count of how many users exist in each category.

Finally, add the block to the frontpage in the Block Layout.
> 0 votes

---
Tags: views, 8
---


title: Permissions wiping themselves

text:
# Question
Title: Permissions wiping themselves
I have a weird problem and was hoping maybe someone on this community experienced it before or would know a better way to debug the issue.

I help manage a large group of multi-sites in Drupal 7.52. There are currently 9 websites and thousands of nodes, so its not a tiny system. we have 13 roles (including the basic - 6 are custom).

Two of these roles are checked to see "View Interactive Information Bar". Description of this permission is "Allow users to view the IIB. This may allow users to perform administrative tasks.".

There are a bunch more but I will use the above as the example to the issue. We will go say 2-3 weeks with no issues and then all of a sudden this permission will become un-checked ONLY for our custom roles. This applies to a bunch of other permissions as well, what is odd is its not ALL the permissions. It is only a few and they keep repeating, the above permission is one.

I will go in and check it back on, it will be fine for a day and then boom, unchecked again. I will repeat this for maybe 2-3 days and then it will be fine for weeks.

I've checked the logs, error logs etc... and nothing is coming up. I've tried checking CRON to see if it happens when CRON runs but nothing. It almost seems random.

Has anyone ever come across this before? Or know of a way to possibly debug this?

Thanks!

# Answer
To debug, add a user update hook and check if they role is being unchecked, then log the $edit to your watchdog log then you should be able to see who/what is causing this change. This is a very rough example and you'd have to customize it to fit your roles etc.

```
function YOURMODULE_user_update(&$edit, $account, $category) {
   if (user_has_role($YOUR_ROLE_RID, $account) {
     debug($account, 'account', true);
     debug($edit, 'edit request', true);
     // maybe add an email notification letting you know the event fired
   }
}

```

You can then test it by manually disabling that role and see if the debug messages appear in your log. Then if it works, just wait and see what happens when the mysterious permissions troll strikes again.
> 0 votes

---
Tags: 7, users
---


# Question
Title: "The 'entity_type:block_content_type' plugin does not exist." Why? How?
My boss and I have inherited a Drupal 8 site from another developer, and every attempt to do database updates or cache rebuilds triggers a fatal exception: ‘The “entity\_type:block\_content\_type" plugin does not exist.’ We’ve updated lots of modules, redownloaded dependences, etc. and still it persists.

We're both pretty new to Drupal 8, and Google hasn't turned up much *general* advice on "plugin does not exist" errors. The Custom Block (block\_content) module is enabled, and I think I can see where the plugin is declared, in a big comment in `core/modules/block_content/src/Entity/BlockContentType.php`. Beyond that, I have no clue what would make a plugin fail to be found. Can anyone shed some light on this for us?

Full stack trace:

```
$ drush cache-rebuild
exception 'Drupal\Component\Plugin\Exception\PluginNotFoundException' with message 'The "entity_type:block_content_type" plugin  [error]
does not exist.' in /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52
Stack trace:
#0 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryCachedTrait.php(25):
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition(Array, 'entity_type:blo...', true)
#1 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Plugin/Factory/ContainerFactory.php(16):
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('entity_type:blo...')
#2 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Condition/ConditionManager.php(50):
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('entity_type:blo...', Array)
#3 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Plugin/DefaultLazyPluginCollection.php(81):
Drupal\Core\Condition\ConditionManager->createInstance('entity_type:blo...', Array)
#4 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Component/Plugin/LazyPluginCollection.php(80):
Drupal\Core\Plugin\DefaultLazyPluginCollection->initializePlugin('entity_type:blo...')
#5 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Condition/ConditionPluginCollection.php(26):
Drupal\Component\Plugin\LazyPluginCollection->get('entity_type:blo...')
#6 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Component/Plugin/LazyPluginCollection.php(148):
Drupal\Core\Condition\ConditionPluginCollection->get('entity_type:blo...')
#7 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Plugin/DefaultLazyPluginCollection.php(114):
Drupal\Component\Plugin\LazyPluginCollection->getIterator()
#8 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Condition/ConditionPluginCollection.php(33):
Drupal\Core\Plugin\DefaultLazyPluginCollection->getConfiguration()
#9 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(320):
Drupal\Core\Condition\ConditionPluginCollection->getConfiguration()
#10 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(434):
Drupal\Core\Config\Entity\ConfigEntityBase->preSave(Object(Drupal\Core\Config\Entity\ConfigEntityStorage))
#11 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Entity/EntityStorageBase.php(389):
Drupal\Core\Entity\EntityStorageBase->doPreSave(Object(Drupal\block\Entity\Block))
#12 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(259):
Drupal\Core\Entity\EntityStorageBase->save(Object(Drupal\block\Entity\Block))
#13 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Entity/Entity.php(364):
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object(Drupal\block\Entity\Block))
#14 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php(637):
Drupal\Core\Entity\Entity->save()
#15 /var/www/sites/beprobeproud/htdocs/core/modules/block/block.module(156): Drupal\Core\Config\Entity\ConfigEntityBase->save()
#16 [internal function]: block_rebuild()
#17 /var/www/sites/beprobeproud/htdocs/core/lib/Drupal/Core/Extension/ModuleHandler.php(402):
call_user_func_array('block_rebuild', Array)
#18 /var/www/sites/beprobeproud/htdocs/core/includes/common.inc(1133): Drupal\Core\Extension\ModuleHandler->invokeAll('rebuild')
#19 /var/www/sites/beprobeproud/htdocs/core/includes/utility.inc(51): drupal_flush_all_caches()
#20 /usr/local/share/drush/commands/core/cache.drush.inc(300): drupal_rebuild(Object(Composer\Autoload\ClassLoader),
Object(Symfony\Component\HttpFoundation\Request))
#21 [internal function]: drush_cache_rebuild()
#22 /usr/local/share/drush/includes/command.inc(422): call_user_func_array('drush_cache_reb...', Array)
#23 /usr/local/share/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#24 [internal function]: drush_command()
#25 /usr/local/share/drush/includes/command.inc(199): call_user_func_array('drush_command', Array)
#26 /usr/local/share/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#27 /usr/local/share/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#28 /usr/local/share/drush/drush.php(12): drush_main()
#29 {main}

```

# Answer
> 4 votes
How old is the site exactly before you started updating it?

Does it have the ctools module enabled? Someone at some point used/defined an entity\_type:block\_content\_type condition, and ctools use to define those, but it was renamed a long time ago from entity\_type:block\_content\_type to e.g. entity\_bundle:block\_content. By me, actually.

If your site is that old, then you will have to manually fix your configuration. Try drush cex to export the config, then search for that string and similar ones, probably all in block.block.\* files. Likely those are empty condition configurations anyway, then you can just remove that part of the configuration. Then import again with drush cim, and then hopefully it will work.

---
Tags: 8, plugins
---


title: How to import taxonomy from Json format

text:
# Question
Title: How to import taxonomy from Json format
I have taxonomy in Json file. I need import this file into Drupal into exist vocabulary.how can I import data from Json file to exist vocabulary?

# Answer
Here are some resources if you opt to use Migrate Framework in 7.x to do this (which is how I would personally approach it).

There are examples in Migrate/Migrate Plus on getting it setup. It looks like migrate\_source\_json was deprecated in favor of migrate\_plus, but I included it for any historical references in it's issue queue.

There is probably a solution via Feeds as well but as stated, I am not experienced with Feeds.

If you can convert your format to CSV, there is also this one off module, Taxonomy CSV.
> 1 votes

# Answer
You can use Taxonomy Manager module, it give you very good features to work with taxonomies.

Description from module's page :

> This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.
>
> The Taxonomy Manager has following operations and key features:
>
> ```
> dynamic treeview
> mass deleting
> mass adding of new terms
> moving of terms in hierarchies
> merging of terms (using the Term merge module in 7.x)
> fast weight changing with up and down arrows (and AJAX saving)
> AJAX powered term editing form
> simple search interface
> CSV Export of terms
> i18n support for multilingual vocabularies (per language terms)
> Double Tree interface for moving terms in hierarchies, adding new translations and switching terms between different vocabularies
>
> ```
>
> For using the Taxonomy Manager you should have JavaScript and automatically load of images enabled in your browser.

**And about solution for what you asked:**

with getting help from https://json-csv.com/ | https://konklone.io/json/ ( or another one from plenty Json to CSV convertor) convert your Json terms to CSV then import them with Taxonomy Manager with copy/paste CSV result on taxonomy import option.

Also you can import from CSV with Taxonomy CSV module.
> 1 votes

---
Tags: 7, taxonomy-terms, importing-exporting
---


# Question
Title: Drush db connection issues after upgrading to MAMP 4?
Upgraded to MAMP 4 yesterday and cannot get Drush to connect for the life of me. I believe I had a similar problem with MAMP 3, but the following fixed the issue. No luck this time.

```
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

```

Any ideas? I have Drush installed globally with Composer. Here's the error:

```
    Command pm-update needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'pm-update' could not be executed.                 [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.50
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  ba_dev
 PHP executable         :  /usr/local/bin/php
 PHP configuration      :  /usr/local/etc/php/5.5/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /Users/ja/.composer/vendor/drush/drush
                           /drush.php
 Drush version          :  8.1.3
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/ja/Sites/ba/public_html
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

```

# Answer
> 4 votes
Figured this out by adding the following to my .bash\_profile file and modifying the PHP versions to match what's in MAMP. Working just fine again.

```
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.4.45/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.5.38/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php5.6.25/bin:$PATH"
export PATH="/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php7.0.10/bin:$PATH"

```

After this run:

```
source ~/.bash_profile

```

# Answer
> 1 votes
After some hours of search, I finally found the final piece. Hope this help someone :D.

MAMP PRO on Mac

---
Tags: database, drush, 7
---