title: How do I write migrate group files?

text:
# Question
Title: How do I write migrate group files?
I'm trying to create a Migrate group with following code. But it is not detected & listed in admin/structure/migrate. Both migrate plus & Migrate tools modules are installed. I"m trying to create migration from WordPress tables. The module is called migrate\_wordpress & migrate group is defined in config/install with the name migrate\_wordpress. migrate\_group.wordpress.yml

```
id: wprdpress
label: WordPress Imports
description: Import from WordPress blog
source_type: Custom tables

```

What is wrong with above Migrate group configurations? What is the correct way to write an migrate group configuration file in Drupal 8?

# Answer
> 7 votes
I believe that groups are a feature of the migrate\_plus module. In order for them to be recognised, the file needs to be named `migrate_plus.migration_group.<group_name>.yml`. The actual migrations also need to be formatted like this `migrate_plus.migration.<migration_name>.yml`.

One other issue I see is that your `id: wprdpress` should be `id: wordpress`. (Just in case that typo is in your code :) )

The last thing is that migrations are only defined on module install. This means that you have to uninstall and re-install every time. (Or you can implement some drush commands to do it for you. Check out this tutorial.)

# Answer
> 1 votes
In .yml file we define four major parts for Migration. These are *id, source, process and destination*. Id is to identify this Migration process Id to identify. Source is defined with the data source. Process define basically the mapping of fields in between destination and source. It seems you are missing process and destination. To define Migration group you can define it like this

*migration\_group: custom
destination:
plugin: entity:file*

You can refer this Migrate Module as well.

---
Tags: 8, migrations
---


title: Form alter not working

text:
# Question
Title: Form alter not working
I used custom module to alter comment form.in that module i write below code to remove required option for fivestar rating field. but it is not working.

```
$form['field_rating_comment']['und']['0']['value']['#required'] = FALSE;
$form['field_rating_comment']['#required'] = FALSE;

```

both are not working.

# Answer
If it's an entity then you can remove the required property from manage fields option in comment.

```
$form['field_rating_comment']['und']['0']['rating']['#required'] = FALSE;

```
> 1 votes

---
Tags: 7, forms, rating
---


title: Can I easily export content?

text:
# Question
Title: Can I easily export content?
Let's say I have a Drupal 7 website, with 3 taxonomies and 3 articles.

```
 - Cars
   - Sport
     - Porshe
 - Family
   - Taurus
 - SUV
   - Navigator

```

No modules, no nothing, just this content and taxonomies.

Is is it a fairly simple process?

# Answer
If you have nothing but that, yes, Drupal core migrate and migrate\_drupal\_ui module will easily do this.
> 1 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Images are not migrated and the body field is empty
I tried to migrate a site from Drupal 7 to Drupal 8.1 using drush (migrate-import --all) and the following modules:

* Migrate Plus
* Migrate Tools
* and the D8 core migrate modules.

It doesn't migrate the image of my nodes and the body field is empty. Do I have to create the same content types with similar fields first, or should I let the Migrate module do this?

The empty body looks like a problem with the text format filter. I use the full HTML text format with CkEditor on Drupal 7, but this filter exists on Drupal 8 too, so I don't understand why it happens.

# Answer
The solution for the body-field:

it must be a translation problem. I changed the language of the Drupal 8.1 site to the same language as the Drupal 7 site and now the body field isn't empty anymore.

But the images are still missing. I noticed that no files were imported. Under /admin/content/files there is nothing! any help in this case?
> 1 votes

# Answer
Body field of Node is a compound field so we define body field like this in .yml file.

```
process:
......
......
  'body/format':
    plugin: static_map
    bypass: true
    source: body_format
    map:
      1: plain_text
      2: restricted_html
      3: full_html
      4: full_html
  'body/value': body_value
  'body/summary': body_summary

```

Also in php class file that extends SqlBase for migration you need to define body.

```
public function fields() {
    $fields = $this->baseFields();
    $fields['body/format'] = $this->t('Format of body');
    $fields['body/value'] = $this->t('Full text of body');
    $fields['body/summary'] = $this->t('Summary of body');
    return $fields;
  }

```
> 1 votes

---
Tags: 8, migrations
---


# Question
Title: What are the tables that once were term_node & term_data?
In Drupal 6 there are the following database tables: `term_node` and `term_data`.

What are the equivalent tables for Drupal 8?

# Answer
> 3 votes
All tables by the taxonomy module are prefixed with taxonomy\_ since Drupal 7.

term\_data is now taxonomy\_term\_data but also taxonomy\_term\_field\_data, as it is a translatable entity. Never interact with those tables directly, use the entity API.

term\_node is taxonomy\_index, but it is only a secondary index you can read from there, but the primary storage are the entity\_reference fields that point from nodes or any other entity type to taxonomy\_term. So if you want to change values, you need use the entity API as well.

Taxonomy works very different than in Drupal 6, where you had to enable a vocabulary per-node type. Now terms work exactly the same as any other refeence, between nodes and other nodes, nodes and users and so on. The only left-over of the old system is that an index table is maintained specifically for node -\> taxonomy references.

---
Tags: 8, database
---


title: Filter using two taxonomy vocabulary

text:
# Question
Title: Filter using two taxonomy vocabulary
I'm running Drupal 8 with two taxonomy vocabularies, which are as follows:

* Color

+ Red
    + Blue
    + Green
* Containers

+ A
    + B
    + C
    + D
    + E
    + F

My content has 2 term reference fields

* Color
* Containers

The first term reference can have multiple tags. What I'm trying to do is use the first vocabulary (Color) as exposed-filter/menu and the second (Containers) as term reference list on my views. I want to be able to show the second vocabulary (Containers)reference list based on the first vocabulary (Color) tags. So if someone clicks Red it will only list the second vocabulary (Containers) which has the term tagged as red.

How can I achieve this?

# Answer
> 1 votes
If you have to use two taxonomy vocabulary instead one, you can do the following.

1. On the "color" vocabulary add entity reference to the "containers" vocabulary and for each color term set avaiable containers for it.
2. Using Drupal.settings you give information about relations between terms (as an assocated array, for example) to browser so that it would use information in JavaScript.
3. Add JQuery script, which intercepts a selection of a color term and delete redundant terms in the select box for containers. That is, for example, you have selected a color Green and JQuery script has immediately removed all elements from the select box for contaners, except "B" and "C".

You can add the JQuery script and send data to Drupal.setting using hook\_form\_alter for the node insert/edit form.

Of course, I'm not guarantee that this way is the rightest one, but if I were you I would try so at the beginning.

---
Tags: 8, views
---


title: How to add a link in Dropdown in drupal

text:
# Question
Title: How to add a link in Dropdown in drupal
I have some addresses in Dropdown list and now i want to add "Add new Adrress" link along with my Addresses in dropdown.And on link click i want to open cTools popup for form elements.how can i achieve this,please help.

```
$form['line_items'][$line_item_id]['default_address'] = array(
'#title' => 'Send To',
'#type' => 'select',
'#default_value' => $defualt_profile,
'#options' => $last_5_profile,
);

```

# Answer
> 0 votes
Try the Better Jump Menu module.

> Better Jump Menu is a module who provides:
>
> * The Drupal menu blocks with menu links in a select box instead of a list.
> * A Views style plugins to display links into a select box.
> * It can display any entity field in a select list, see features below.

Similar module Better Jump Menus

---
Tags: forms, commerce, javascript, ajax
---


title: Aegir login link not working

text:
# Question
Title: Aegir login link not working
I am trying to install Aegir on Ubuntu.

I followed the installation instructions

> ```
> sudo mysql_secure_installation
> echo "deb http://debian.aegirproject.org stable main" | sudo tee -a /etc/apt/sources.list.d/aegir-stable.list
> curl http://debian.aegirproject.org/key.asc | sudo apt-key add -
> sudo apt-get update
> sudo apt-get install aegir3
>
> ```

Everything got a `success`, but when I go to the login link that it provides me, the I get "server DNS address could not be found."

When I go to mydomain.com I get a 404 (which was working before).

Why is this happening? What am I missing?

# Answer
I hate providing a link answer, but in http://docs.aegirproject.org/en/3.x/install/#debianubuntu do steps 1-6 then you can install Aegir.

They main key being you need to do `sudo hostname yoursite.com` which was not mentioned in other docs.
> 1 votes

---
Tags: installation, aegir
---


# Question
Title: How to add a views block in a basic page via editor?
I have created a basic page through the editor of drupal 7 and I have started coding the body using the PHP code text format. So far so good, apart from the fact that I want to embed a block from a view (showing three nodes) and the code below which seems to work when I put it directly into a php file, doesn't activate within the body. I am using Bootstrap by the way.

```
<div class="third-box">
  <div class="col-xs-12">
    <?php print views_embed_view("mylatest_events", "block"); ?>
  </div>

  <div class=clear></div>
  <p class="text-center"><br><strong>Flavour text to describe the view here.</strong></p>
</div>

```

Any suggestions?

# Answer
Have you tried to use the simplest php-code inside your body field ? For example,

```
<?php print 'The simplest text'; ?>

```

It can be situation, where filter for content of your field is configured wrongly.

Moreover, it would be nice to try names of the view and view mode.
> 0 votes

# Answer
Try this way...

```
<?php
$block = block_load('views', 'your_block_name');
print render(_block_get_renderable_array(_block_render_blocks(array($block))));
?>

```
> 0 votes

---
Tags: 7, nodes
---


title: Can't find variable: Drupal

text:
# Question
Title: Can't find variable: Drupal
I've created a behaviours in JS but when I'm not connected as admin it show in the console this error:

> Can't find variable: Drupal

When I write `console.log(Drupal)` in the console explorer it show too the error.

How I can fix this error ?

Edit :

I've defined my library by this way :

```
myc_facebook:
  version: 1.x
  js:
    js/script.js: {}
    js/timeago.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

I integrate my library in a block by this way :

```
public function build() {
        $config = $this->getConfiguration();

        // Check if the conf
        if (empty($config['token']) || empty($config['pagename']) || empty($config['pageurl']) || empty($config['limit']))
            return array('err' => array('#markup' => t('You might configure this block.')));

        $build = [];
        // Create the wrapper to include facebook posts
        $build['facebook']['timeline']['#markup'] = '<div id="myc-fb-posts" class="slider"><ul class="slides"></ul></div>';
        // Push conf vars
        foreach ($config as $key => $value) {
            $build['#attached']['drupalSettings']['myc_fb'][$key] = $value;
        }
        // Includes libraries
        $build['#attached']['library'][] = 'myc_facebook/myc_facebook';

        return $build;
    }

```

# Answer
Sounds like you're simply missing the dependency on core/drupal (and posibly also core/jquery) in your library, so that Drupal and JQuery get loaded, which by default it doesn't for anonymous users.
> 4 votes

---
Tags: 8, javascript
---


# Question
Title: How to add link around each rows in views?
I have article' views with fields like this:

```
<div class="row">
 <div class="views-row">
   <div class="views-field views-field-field-image">Content Image</div>
   <div class="views-field views-field-field-date">Content Date</div>
   <div class="views-field views-field-title">Content Title</div>
   <div class="views-field views-field-view-node">Link to content</div>
 </div>
</div>

```

I can access to article by my link but I want to render clickable all of row to link .

This is my `views-view-unformatted.html.twig` file:

```
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}

{% for row in rows %}
 {%
   set row_classes = [
    default_row_class ? 'views-row',
  ]
 %}
<div class="row">
  <div{{ row.attributes.addClass(row_classes) }}>
   {{ row.content }}
  </div>
</div>
{% endfor %}

```

and I think I want this:

```
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}

{% for row in rows %}
 {%
   set row_classes = [
    default_row_class ? 'views-row',
  ]
 %}
<div class="row">

 <a href="path to node"

  <div{{ row.attributes.addClass(row_classes) }}>
   {{ row.content }}
  </div>
</div>

</a>
{% endfor %}

```

But I don't know how it's possible. Any known workarounds?

# Answer
> 2 votes
Sounds like it would be easier to create a View Mode for this. Add a View Mode under Admin \> Structure \> Display Modes, arrange the fields and configure their formatters. Then if you need to, create a `node--node_type_name--view_mode_name.html.twig` template to get the markup you want.

Back in the view, change the output to rendered entity, and select your new View Mode. This reduces complexity when it comes to displaying views that are basic entity fields, because that all happens in the View Mode configuration now instead of dealing with views fields and overwriting and theming.

In your new node view mode twig template, wrap your fields and use the appropriate twig function to wire it up:

https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

So, something like:

```
<article id="node-{{ node.id }}" class="{{ attributes.class }}"{{ attributes }}>
  <a href="{{ path('entity.node.canonical', {'node': node.id}) }}">

    // all node content fields + markup here
    {{ content|without('comment', 'links') }}
  </a>
</article>

```

Also note that your twig file name for the unformatted view will (I believe) affect all views using the unformatted display. You likely don't want that.

---
Tags: views, theming, 8
---


title: Behaviors not work for anonymous users

text:
# Question
Title: Behaviors not work for anonymous users
I have a script with a behavior which receive settings by a block. The problem is that when I'm logged as admin the behavior is executed but when I'm an anonymous user, the behaviors isn't executed.

Can you help me ?

I Define this block :

```
public function build() {
        $config = $this->getConfiguration();

        // Check if the conf
        if (empty($config['token']) || empty($config['pagename']) || empty($config['pageurl']) || empty($config['limit']))
            return array('err' => array('#markup' => t('You must configure the block.')));

        $build = [];
        // Create the wrapper to include facebook posts
        $build['facebook']['timeline']['#markup'] = '<div id="myc-fb-posts" class="slider"><ul class="slides"></ul></div>';
        // Push conf vars
        foreach ($config as $key => $value) {
            $build['#attached']['drupalSettings']['myc_fb'][$key] = $value;
        }
        // Includes libraries
        $build['#attached']['library'][] = 'myc_facebook/myc_facebook';

        return $build;
    }

```

And here is my js :

```
jQuery(document).ready(function($) {
    console.log("hello 1");
    console.log(Drupal);
    Drupal.behaviors.myc_facebook = {
        attach: function (context, settings) {
            console.log("hello 2");
    };
});

```

And it's how I define my library :

```
myc_facebook:
  version: 1.x
  js:
    js/script.js: {}
    js/timeago.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/drupalSettings

```

# Answer
> 5 votes
You probably need to pass a reference of jQuery and Drupal in your js file like this:

```
(function ($, Drupal, drupalSettings) {

  ...

})(jQuery, Drupal, drupalSettings);

```

Btw. your js has {{{ but only }}. And you don't need document ready when you use drupal behaviors.

---
Tags: 8, javascript
---


# Question
Title: Programmatically place image field as default value in form plugin
I have a content type that has an image field that allows you to upload up to 4 photos. I'm creating a form for users to use that will allow them to edit existing items of this content type. The form fields need to be filled with the existing node field values by default. Retrieving fields such as textfields and supplying the default value works just fine, like so:

```
class EquipmentEditForm extends ConfigFormBase {
    private $imageNum = 4;

    protected function getEditableConfigNames() {
        return array(
            'equipment.form',
        );
    }
    public function buildForm(array $form, FormStateInterface $form_state) {
        $equipment_id = 10306;
        $node = NODE::load($equipment_id);

        $contact        = $node->get('field_contact')->value;
        $description    = $node->get('field_description')->value;

        $form = [
            'container'    => [
                '#type'       => 'container',
                '#attributes' => [
                    'class'      => ['equipment-entry'],
                ],
                'contact'      => [
                    '#type'       => 'textfield',
                    '#title'      => t('Contact Person'),
                    '#attributes' => [
                        'name'       => 'contact',
                    ],
                    '#default_value' => $contact,
                ],
                'description'    => [
                    '#type'       => 'textfield',
                    '#title'      => t('Description'),
                    '#attributes' => [
                        'name'       => 'description',
                    ],
                    '#default_value' => $description,
                ],
           ],
        ];
    }
}

```

This generates the form and populated the fields from the node just fine. However I'm not sure how to populate the image field. I've attempted the following with no luck.

```
    if ($node->get('field_equipment_photo')->entity != null) {
        $photos = $node->get('field_equipment_photo');
    }
    for ($i = 1; $i <= $this->imageNum; $i += 1) {

        $title = ($i == 1)?'Image '.$i:'Image '.$i.' (extra)';

        $form['image'.$i] = [
            '#type'            => 'managed_file',
            '#upload_location' => 'public://images/',
            '#title'           => t($title),
            '#name'            => 'image'.$i,
            '#default_value'   => $photos[$i],
        ];
    }

```

It just provides an error

> Recoverable fatal error: Object of class Drupal\Core\TypedData\Plugin\DataType\IntegerData could not be converted to string in Drupal\Core\Entity\ContentEntityStorageBase-\>buildCacheId() (line 659 of core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php).

I know I'm retrieving the images because if I perform a statement like this:

```
die(print_r($photos[1]->entity));

```

I do get a list of the information contained in the 2 uploaded image. Including the filename.

How would I programmatically retrieve the values of an image field array of a node and place them into the default values of a form field?

UPDATE: I'm able to discover the fid using

```
die(print_r($photos[0]->entity->fid->value));

```

but using $photos\[0\]-\>entity-\>fid-\>value as the default value leads to this error

> Warning: Invalid argument supplied for foreach() in Drupal\file\Element\ManagedFile::valueCallback()

# Answer
Turns out I needed to get the fid of the images and place them into an array. First I started by retrieving the images like I did before

```
    if ($node->get('field_equipment_photo')->entity != null) {
        $photos = $node->get('field_equipment_photo');
    }

```

Then I grabbed the fid and placed them into the default value like so

```
if ($photos[$i]->entity->fid->value != null) {
                $form['image'.$i]['#default_value'] = array($photos[$i]->entity->fid->value);
            }

```

For some reason even though the fid is just one value it still needs to be wrapped in an array when being used as the default value.
> 0 votes

---
Tags: forms, 8, media
---


# Question
Title: Get an image with style url from an URI in twig
So thanks to 4k4 I finally managed to get my original image URI in a field template via

```
item.content['#item'].entity.uri.value

```

and with

```
{{ file_url(item.content['#item'].entity.uri.value) }}

```

I would get the url of the original file.

I have the image style information via

```
item.content['#item']['#image-style']

```

that 'medium' is requested

A PHP solution is already available here, but how do I do this in TWIG?

There are some attempts on creating a filter for 8.1 here \- but that doesn't help me currently.

# Answer
You could put the php code in the preprocess function of the field template. You have all information you need in your question.

But then you would do coding, that is already in drupal. If you have #image-style set in the image render element, then the image field should be configured for the preprocess functions that come later in the image-formatter and image-style templates to put the right src attribute in the variables for `image-style.html.twig`. So you can use the code that is already there by overriding this template.

See the code in /core/module/image/image.module:

```
function template_preprocess_image_style(&$variables) {
  $style = ImageStyle::load($variables['style_name']);

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  $style->transformDimensions($dimensions, $variables['uri']);

  $variables['image'] = array(
    '#theme' => 'image',
    '#width' => $dimensions['width'],
    '#height' => $dimensions['height'],
    '#attributes' => $variables['attributes'],
    '#uri' => $style->buildUrl($variables['uri']),
    '#style_name' => $variables['style_name'],
  );

```
> 3 votes

# Answer
I just had a need to do this as well. The right approach here is to store the image URL of the styled image into a variable (through a preprocess function), and then that variable will be available in your twig file.

I've written a function that will get any field\_image file and return the original file name, or if you specify a style name, it will return the URL of the styled image.

Inside my `.theme` file:

```
function MYTHEME_preprocess_node(&$vars) {
  //get thumbnail images from field_image
  $vars['field_image_url'] = _var_image_url($vars, 'field_image', 'thumbnail');
}

//pull image field URL (original or styled)
function _var_image_url($vars, $field, $style_name = '') {
  if (!empty($vars['elements'][$field]['#object'])) {
    $fields = $vars['elements'][$field]['#object']->getFields();
    $image = $fields[$field]->getValue();

    if (!empty($image[0]['target_id'])) {
      $file = \Drupal\file\Entity\File::load($image[0]['target_id']);
      $uri = $file->getFileUri();

     if(!empty($style_name)) {
        $url = \Drupal\image\Entity\ImageStyle::load($style_name)->buildUrl($uri);
        return $url; //the styled URL
     } else {
        return file_create_url($uri); //original
     }
   }
 }
 return false;
}

```

Now in my twig file (node.html.twig, since I used the preprocess\_node function):

```
<div class="banner" style="background-image:url({{ field_image_url }}"></div>

```

This function `_var_image_url()` has to be called from the `THEME_preprocess_node()` function because it's expecting a certain set up in the first `$vars` argument. If you try calling it from `preprocess_page`, you would need to modify it.
> 3 votes

---
Tags: theming, 8, uri, media
---


# Question
Title: How create a file type field in custom entity programmatically?
This is how i create my field in my Entity content :

```
  $fields['fid'] = BaseFieldDefinition::create('file')
      ->setLabel(t('Photo'))
      ->setRequired(false)
      ->setDescription(t('Product image'))
      ->setSettings(array(
          'upload_location' => 'public://produits/',
          'upload_validators' => array(
              'file_validate_extensions' => array('png jpg jpeg'),
          ),
      ))
      ->setDisplayOptions('view', array(
          'label' => 'above',
          'type' => 'file',
          'weight' => -3,
      ))
      ->setDisplayOptions('form', array(
          'type' => 'file',
          'settings' => array(
              'upload_location' => 'public://produits/',
              'upload_validators' => array(
                  'file_validate_extensions' => array('png jpg jpeg'),
              ),
          ),
          'weight' => -1,
      ))

      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

```

The field is create in my form but when i try to upload a file :

I got this error :

> Only '.txt' extension is authorized

**Edit 1 :**

In fact my settings are never read, after upload a .txt for test, the directory is wrong.

Any idea about this ?

# Answer
Working example from something I'm working on:

```
'image' => BaseFieldDefinition::create('file')
      ->setLabel('Image')
      ->setSettings([
        'uri_scheme' => 'public',
        'file_directory' => 'credentialing_providers',
        'file_extensions' => 'png jpg jpeg',
      ])
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'file',
        'weight' => -3,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'file',
        'weight' => -1,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE),

```
> 4 votes

# Answer
The only way i have found is to move this param into the Entityform :

```
  $form['fid'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://produits/',
      '#default_value' => $entity->get('fid')->value,
      '#description' => t('png jpge jpg'),
      '#upload_validators' => array(
          'file_validate_extensions' => array('png jpg jpeg'),
      )
  );

```
> 1 votes

---
Tags: entities, 8
---


# Question
Title: How can I link a group of galleries through a single image using Views?
I found a great article titled "How to Create an Image Gallery in Drupal" and at the end the author was sketching the posibility of its intregration with Views.My intention is to display a grid View of single images that represents the full contents (the galleries) that I created thanks to that article,and when you click on each one they take you to its respective group of images.

# Answer
> 0 votes
You can just do the following on the View:

1. Add your custom "path" field and set it to be hidden (Exclude from Display).
2. Add The image field. Under "Rewrite results" set it to "Output this field as a link" and use the token for the previously hidden field.

This will allow you to define what will each image do when clicked.

---
Tags: 7, views, media
---


# Question
Title: How to create a view of counts of taxonomy reference fields by each user?
I have a content type that contains a taxonomy term reference field. each user can create unlimited nodes of this content type and select different term at each time. now we want make a view of count of this terms selected by users as a table like this:

is there any plugin to support create these type of tables in views? or we should do it programmatically? I appreciate any help.

# Answer
> 0 votes
In the Advanced \> Other section of the view, you should be able to enable aggregation.

# Answer
> 0 votes
To my knowledge there is no solution to create such kind of view using the Views module. But the Forena module (disclosure: I'm a co-maintainer) can be used for this type of reporting. More specifically by using its facility to create a Display of a table in ***crosstab*** format.

A ***crosstab*** table is a table with a special layout. It is formatted as a grid, with:

* the **rows** representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), etc.
* the **columns** representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
* the **intersections of rows and columns** containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) **include a hyperlink to a drill-down report**.

Below is a sample of such ***crosstab*** report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).

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


# Question
Title: MailChimp Error: API Key cannot be blank
I'm trying to install the mailchimp addon but are stuck on getting the error message above.

So far:

* I've installed/enabled the module with version 7.x-4.0
* Loaded the PHP Library to */sites/all/libraries/mailchimp*
* Added the API Key to */admin/config/services/mailchimp*
* Enabled the *MailChimp Signup* module

The error occurs after enabling the signup module and freezes the whole website with a blank screen even though error messages are being fully displayed. When I uninstall the signup module via drush and check the admin page for the service my API key is still set.

Any pointers what I'm doing wrong?

# Answer
> 0 votes
Mistake: I've not correctly installed the mailchimp php library. Instead of showing this in the status report page the module crashes the website.

# Answer
> 0 votes
You need to create a MailChimp account, go to your account, choose Extras / API Keys. Copy and p\[aste the API Key in the labeled field here: /admin/config/services/mailchimp

---
Tags: 7, emails
---


# Question
Title: programmatically enable and disable theme from update hook
I need to programmatically update my default theme and disable bartik on a live site. I know I need to update the config. In Drupal 7 I would have used `theme_enable()`, but I am not sure how to do this in Drupal 8. Below my function sets 'mycustomtheme' by default but it does not enable the theme. Thanks in advance.

```
  function mysite_deploy_update_8001() {
      \Drupal::configFactory()
      ->getEditable('system.theme')
      ->set('default', 'mycustomtheme')
      ->save();
    }

```

# Answer
Use the theme installer service to enable and disable themes .

Install a list of themes:

```
\Drupal::service('theme_installer')->install(['mytheme']);

```

Uninstall a list of themes:

```
\Drupal::service('theme_installer')->uninstall(['mytheme']);

```

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21ThemeInstaller.php/function/ThemeInstaller%3A%3Ainstall/8.2.x
> 11 votes

---
Tags: 8, updating
---


title: How to theme menus in a custom twig

text:
# Question
Title: How to theme menus in a custom twig
I've fetched the main menu for the website using the code below.

```
public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(0);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $build['menu'] = $menu_tree->build($tree);

return array(
      '#theme' => 'allofus_menu_footer',
      '#build' => $build,
    );
  }

```

I'm trying to put it as a block, but I want to show it as a 2 coloumn. In the first coloumn, first main menu and its sub menus and the rest of main and sub menus in the second coloumn.

I've created a twig but it does not print anything except markup. I've tried to foreach but it is not working.

`allofus-menu-footer.html.twig`:

```
{% if build %}
    <nav id ="secondary-menu" class="navigation" role="navigation">
        {{ build }}
    </nav>
{% endif %}

```

# Answer
I just did a lot of this with Menu Block. I prefer Menu Block as it is a little more flexible and offers more template suggestions and hooks than the core menu module. It kind of looks like you are building your own block above, I can't tell, but you can save time by using Menu Block in that case.

In one of my menus, this is the twig file that handles the output. I did not do any preprocess or extra stuff, just built around the macro concept used in `menu.html.twig`. Every parent item has children, and if those children items exceed 7, it will start a new list. For example, if the menu link has 14 children, then my code will have a drop down consisting of 2 unordered lists with 7 links each. Our style then makes them into columns. This is a little different from your use case, but should get you on the right track.

```
{#
/**
 * @file
 * Theme override to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    <ul>
      {% for item in items %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}

        <li{{ item.attributes.addClass(classes) }}>
          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.submenu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}
        </li>
      {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

{% macro submenu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  <div class="global-top__submenu">
    {% for chunk in items|batch(7) %}
      <ul class="global-top__submenu-col">
        {% for item in chunk %}
          <li{{ item.attributes }}>
            {{ link(item.title, item.url) }}
          </li>
        {% endfor %}
      </ul>
    {% endfor %}
  </div>
{% endmacro %}

```
> 2 votes

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


# Question
Title: Is there some way to compress CSS and Javascript only for certain users?
When I check the source of my web pages I am appalled at the amount of Javascript links in the page, but I have disabled the CSS and JS compression as I am often in development mode.

Is there some way to disable the compression for admins and developers and enable it only for viewers?

# Answer
> 6 votes
You're looking for AdvAgg. If the user has the correct permissons you can add ?advagg=-1 to the URL and all CSS/JS files are un-aggregated for that page request. You can also set a cookie on the `admin/config/development/performance/advagg/operations` page so you no longer need to add that to every URL.

---
Tags: 7
---


# Question
Title: Why there are two payment for one order with same remote ID
Right now, I am using Commerce Paypal to capture payment. But I found there is a order which shows me two logs for capturing payment. However, I just find one in my paypal account and also I found the Remote ID in both two logs are same. The customer bought one item which costs $17, but the total shows on drupal is $34. What is the exact total price for this order? Does anyone know why this happened? Is there something wrong during my config?

Here is a screenshot for this strange order:

# Answer
For some reason the IPN for that payment triggered the creation of a second payment transaction within Drupal Commerce. Couldn't tell you exactly why it happened, though it could've been the result the customer's page request and the IPN request being processed simultaneously. The module ought to filter out IPNs to not duplicate transactions like this, so if you see it again, file a bug report in the module's issue queue.

To answer your direct questions, the order cost $17, the balance is now negative (meaning it appears overpaid within Drupal Commerce, even though it wasn't), and it would be safe to delete one of the transactions (but you'd need to be logged in as an administrator).
> 1 votes

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: How to test upgrade availability with drush exit codes?
I need the test to only do a backup before an upgrade will take place. I use version 8.01 and I use the following command:

```
drush up -n

```

This seems to return zero when there are no updates and 75 when there are, but I need to be sure about this.

Apparently 75 means user abort. Apparently on an up-to-date site, the upgrade process is not interrupted by the "-n" because there is nothing to upgrade and it exits normally.

On an outdated site "-n" will cause the upgrade process to be interrupted and 75 exit code is returned. Please confirm this reasoning is correct, so that I can use it in my script.

# Answer
> 0 votes
The exit codes are defined in includes/drush.inc. Your logic seems sound, but I can't verify that is correct/always will work.

---
Tags: drush
---


# Question
Title: How can I add relative path to a pdf file link in drupal menu
I have created menu link for a pdf file. I can use a full path like "http://website/sites/all/myfiles/file.pdf", but if I try to put a relative link such as "sites/all/myfiles/file.pdf" it does not work. If anyone has idea please tell me.

# Answer
The thing with the menu system is that what you are typing is not a relative path, but an internal Drupal URL.

Since what you are after is not a Drupal path, but instead a static file server outside of Drupal by your webserver your options are limited.

* You can write the full url like you tried yourself
* You can create a module/theme where you can make this possible, either by adding the extra link or creating a drupal path that redirects to the static file.

Of these, I personally think that a an absolute path is the lessor of evils, unless you need to do this a lot of times.
> 6 votes

# Answer
Just use the Menu Token module. Copy your absolute PDF url to your path textfield and replace the servername with \[site:url\]. Also make sure the uses tokens checkbox is activated and save your menu item... In combination with the Menu Attributes module you could even link your PDF's to a blank browser tab/window if you like so.
> 5 votes

# Answer
Drupal uses "clean URLs" so when you're on the `node/123` page and you are visualizing a link such as:

```
<a href="sites/all/myfiles/file.pdf">PDF file</a>

```

Your browser will interpret it as "node/123/sites/all/myfiles/file.pdf" which won't work. You have to put a "/" at the beginning of the URL:

```
<a href="/sites/all/myfiles/file.pdf">PDF file</a>

```

Of course, if your site is in a subdirectory, you need to append it; the safest way is to use `l()`:

```
<?php echo l('PDF file', 'sites/all/myfiles/file.pdf'); ?>

```

**Edit Dic, 18:** use `l()` as per kiamlaluno advice.
> 4 votes

# Answer
* Create a new content type (e.g. "file download")
* Give it a field URL (a link, or a regular text field)
* Override the template file used in your theme (e.g. node--file-download.tpl.php)
* In this file, put the PHP code to load the field with the URL of file, and then put the following code:

```
Header("Location: file_address");

```
* Create a pattern in the Pathauto module for this kind of content type (e.g. "file/download/name" or "download/file\_id")
* Then, you can put it in the menu without problems

I bet there's an easier way, but this should also do the work. It should be double considered in a matter of security.
> 0 votes

# Answer
Just use the Pathologic module, and your relative links will work just fine.
> 0 votes

# Answer
You can also use Menu HTML module together with **Special Menu Items** module . This will allow you to place anchor pointing to you file as Menu link title, and **nolink** tag as menu path.

Just take a look at the screenshot:
> 0 votes

---
Tags: routes
---


# Question
Title: Image styles not working, uploads to to files directory
Image styles are not being applied. I have the /files/ directory set to CHMOD 777, GD Library is installed. When you upload an image, it just goes to the /files/ directory, none of the styles are generated into their styles folder. Reports -\> status report is clean. Image uploads, but it stays in files directory, no thumbnails are generated, all paths are broken to the image even to the thumbnail in the Media page.

Hosted on AWS EC2 Linux/Apache

.htaccess in /files dir:

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

# Answer
**It's because you do not have the correct folder owner/group.**

You need to `cd` into your `/sites` folder. Once there:

If you're using Ubuntu do:

`sudo chown www-data:www-data -R default`

For CentOS it's:

`sudo chown apache:apache -R default` and disable SELinux

---

**PS:** Never give your files folders permission of 777, set it to 775
> 3 votes

# Answer
* Firstly, provide 775 permission to files folder. `chmod 775 -rf sites/default/files/`
* Custom image styles(created by you) are stored in files/styles directory. To have an image style, create it from `/admin/config/media/image-styles`.
* If you are searching for the images you uploaded, they are placed in the directory mentioned in field storage structure which you can see from manage field of a content type under **File Directory**. Ex- `/admin/structure/types/manage/article/fields/node.article.field_image`. By Default, \[date:custom:Y\]-\[date:custom:m\] is set in "File Directory".

Hope, it makes sense to you. Sorry, for 777 it's 775
> 0 votes

---
Tags: media
---


title: Compile LESS files to CSS

text:
# Question
Title: Compile LESS files to CSS
How can i preprocessor or compile at runtime the LESS files in the latest version of Drupal 8?

I am using the LESS starterkit theme of Bootstrap. The **Less CSS Preprocessor** is currently not ported to Drupal 8.

The next two guides says that i need NodeJS and the less package to compile it, but it is not at the runtime of Drupal:

```
lessc less/style.less > css/style.css

```
1. Creating a Bootstrap subtheme for Drupal 8
2. How to build your Drupal 8 theme using Bootstrap & Less

# Answer
> 3 votes
If you don't want to wait for the port of the Less CSS Preprocessor module to run the less compiler at run time, you can execute the command line tool from **settings.php**

```
exec('lessc themes/mytheme/less/style.less themes/mytheme/css/style.css > /tmp/less-debug 2>&1');

```

This is only for development, remove this from the production settings.php.

# Answer
> 2 votes
`lessc` is referring to this npm package:

http://lesscss.org/

You could either install it globally, or have it at the theme level with your own package.json and execute it from the theme directory.

To install globally with npm:

```
npm install -g less

```

`lessc` is then a command available at your command line and then your compile command will work.

See: http://lesscss.org/#using-less-installation

---
Tags: 8, theming
---


# Question
Title: Language switcher in a modal window (pop-up)
I really got quite far on this issue. Using Drupal 8's Modal API. Having a button in a block that triggers the modal with Drupal's language switcher inside. Everything looks fine EXCEPT for the URLs this modal returns. Every URL gets appended with `?ajax_form=1&_wrapper_format=html` which breaks the whole functionality. For example `http://d8.dev/fr/node-41-article?ajax_form=1&_wrapper_format=html`.

I also tried it with a Controller instead of a Form. But then the URLs look even worse, since then they only take the controller path to create the langswitch URLs.

I already started to guess I'd need to start over using a more independent approach. But maybe you folks know a way to get it working with my current approach? Is there a way I can simply cut off the query? Here is what I have so far:

```
<?php

/**
 * @file
 * Contains \Drupal\langswitch_modal\Form\LangswitchModal.
 */

namespace Drupal\langswitch_modal\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;

/**
 * Class LangswitchModal.
 *
 * @package Drupal\langswitch_modal\Form
 */
class LangswitchModal extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    $form['actions']['#type']  = 'actions';
    $form['actions']['submit'] = [
      '#type'  => 'submit',
      '#value' => $this->t('Switch language'),
      '#ajax'  => [
        'callback' => '::open_modal',
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function open_modal(&$form, FormStateInterface $form_state) {

    $block   = \Drupal\block\BlockViewBuilder::lazyBuilder('languageswitcher', 'full');
    $render  = \Drupal::service('renderer')->renderPlain($block);
    $title   = $this->t('Choose language');
    $content = $render;
    $options = [
      'dialogClass' => 'popup-dialog-class',
      'width'       => '300',
      'height'      => '300',
    ];

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

    return $response;
  }
}

```

# Answer
Got it! All I needed was a little JS to get rid of the query:

```
$(document).ajaxComplete(function() {
  var $link = $('a.language-link');
  $link.each(function(i,el){
    $(el).attr('href', $(el).attr('href').split('?')[0]);
  });
});

```
> 1 votes

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


# Question
Title: I have WYSIWYG and CKEditor 3.6.6.1 and want to install the latest CKEditor 4.6.1
My goal is to paste images (best if copied from word together with text) directly without uploading them first.

I got a D7 site with WYSIWYG installed. The module tells me it uses the CKEditor 3.6.6.1 library. In fact, there is no CKEditor module installed, but in the libraries path I see a ckeditor folder.

I tried to install the module pasteFromWord, and I found it didn't work with my a local copy of my site. So I looked around, and I found there is a newer version of CKeditor (4.6.1) rewritten with lots of features like embedding pictures, and it is open source too. There is only an older version of CKEditor as a Drupal 7 module, and it is driving me nuts to install anything that works.

I read about problems with WYSIWYG and I disabled it, but I cannot uninstall it, so I cancelled the whole directory under modules. I installed the latest Drupal CKEDitor (Dev) but all I see in my text field is htmlcode in full html mode. There are no editor icons. I put higher values for the memory settings in settings.php, restarted the server, cleared the cache, tried all sorts of thing suggested in Why does the Wysiwyg module and Ckeditor library not show the CKEditor when editing a node?

All tests are done as user1. By now, I get a simple text field in plain and filtered HTML mode; in full HTML, the text box body simply vanishes.

In Mozilla the Console gives: TypeError: a(...).on is not a function js\_8iXNyfjLJ1tJPju6nAtk8ETos8oLn9Arp0f2Z5uBPaQ.js:850:1412 TypeError: CKEDITOR.dialogCommand is not a constructor plugin.js:4:43 in http://localhost:8080/drupal7bis/sites/all/modules/ckeditor/ckeditor/plugins/SimpleImage/plugin.js which is one of the few plugins I enabled so far (nearly all are installed though because indeed I took the full package) and it reads: CKEDITOR.plugins.add( 'SimpleImage', { icons: 'simpleimage', init: function( editor ) { editor.addCommand( 'simpleimage', new CKEDITOR.dialogCommand( 'simpleimageDialog' ) ); editor.ui.addButton( 'SimpleImage', { label: 'Add a image', icons: 'simpleimage', command: 'simpleimage' });

```
    CKEDITOR.dialog.add( 'simpleimageDialog', this.path + 'dialogs/simpleimage.js' );
}

```

});

When I disable this plugin, only the first error remains. The body does not vanish any more in full mode, but still no editor appears. There are no recent records in watchdog...

# Answer
Mostly thanks to Kevins help I finally managed to get it working. I started over with a new local copy of my D7 site, cancelled the wysiwyg profiles, disabled and then uninstalled the module (this time it showed up in the uninstall tab) and cancelled its directory as well as the ckeditor folder (in \sites\all\libraries). I then downloaded the latest **full** ckeditor library (4.6.1) from Ckeditors site (don't customize because other plugins did not work with D7/wysiwyg, just the plain full version) and copied the unzipped ckeditor folder back to the libraries folder. Don't install the ckeditors drupal **module**. You must install the wysiwyg **DEV** module instead. Be aware that it is not enough to choose the ckeditor for your wysiwyg profiles because the editor would not have any plugin button enabled and you would not see any button.

I found that pasting from word text including images without uploading the images first did work only in internet explorer, while in mozilla I had to copy first the text and then the images seperately. In Chrome instead of an image I got an empty rectangle only, but I try to find solutions for that too.
> 1 votes

# Answer
As far as I know, you need to use the dev version of the WYSIWYG module in order to use CKEditor 4.x. You also need to grab the 'full build' of CKEditor and not a stripped down one. You do not need the *CKEditor* module if you are using the WYSIWYG module. WYSIWYG looks for editors in the given paths (usually libraries) - you have to go get it from ckeditor.com.

The second thing you are describing is adding custom or non-core plugins to CKEditor, which is not as straightforward. "Paste from Word" should be available though once you get WYSWIYG and CKEditor 4.x setup in Drupal 7.

I wrote a plugin integration once for CKEditor 4.x under WYSIWYG. I do not recall needing any module other than WYSIWYG and the full CKEditor library for getting WYSIWYG to show up. You shouldn't need any other CKEditor modules. But if you are looking to add other plugins on ckeditor.com - you need to get comfortable with the WYSIWYG API in order to properly integrate it if someone else hasn't done so already.

The reason your CKEditor may not be showing on the edit page is likely due to a JS error - I am going to guess either because you are not using WYSIWYG dev branch, or CKEditor is not the right version, or CKEditor is not installed in the correct path. Please add the error from the browser console to the original question along with any watchdog errors.
> 2 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Tags for content type and search by this tags
i created a vocabulary called "Tags" and then a field on my content type using this vocabulary. I can create my content and add the tags, but then i search for the tags that im using and i get no results on the search. Somebody can help me? Thanks! Drupal 7.44

# Answer
You can try to use the Term Search module
> 0 votes

---
Tags: 7, taxonomy-terms, search
---


# Question
Title: How to add a new condition to access callback function in hook_menu_alter?
I need to add a new condition to access callback function for a menu path.

For it I write hook\_menu\_alter and redefine there new access callback function.

```
function mymodule_menu_alter(&$items){
  $items[node/add']['access callback'] = 'mymodule_custom_callback';
}

```

And I have a question. I want this function to not overwrite previous access callback function, but add a new condition, which would be added to previous conditions for access callback.

How to do it most correctly ?

And is it possibly to do it not knowing the name of default access callback function ? For example, default access callback function for path node/add is \_node\_add\_access().

# Answer
You can call *default access callback* function in your *custom access callback* and if *default access callback* `return TRUE`, then you can check your own conditions and return TRUE/FALSE. Check example below:

```
function mymodule_custom_callback() {
  // If node access return TRUE.
  if (_node_add_access()) {
    // Do your processing here.
    if (condition) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  return FALSE;
}

```

> And is it possibly to do it not knowing the name of default access callback function ? For example, default access callback function for path node/add is \_node\_add\_access().

In such cases, you can either find it by debugging (`print $items['node/add']; exit;`) or you can append that as an access argument and call it from your custom callback. Something like below:

```
function mymodule_menu_alter(&$items){
  $items['node/add']['access arguments'][] = $items['node/add']['access callback'];
  $items['node/add']['access callback'] = 'mymodule_custom_callback';
}

function mymodule_custom_callback($function) {
  // If node access return TRUE.
  if (function_exists($function) && $function()) {
    // Do your processing here.
    if (condition) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  return FALSE;
}

```
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: How to pull the value of a taxonomy term into the html.tpl.php files
How does one pull the value of a taxonomy term into the `html.tpl.php` file?

I know this needs to be done in the `template.php` file, no?

# Answer
> 2 votes
You should use the function template\_preprocess\_html in your `template.php`.

For example.

```
function yourtheme_preprocess_html(&$vars){
    // $tid - id of your taxonomy term
    $term = taxonomy_term_load($tid);
    $vars['head_title'] = $term->name;
}

```

Also, copy the `html.tpl.php` file to the directory in your theme, where all the template files are located. And clear cache.

---
Tags: 7, theming, taxonomy-terms
---


# Question
Title: How are current anonymous users calculated?
I have a site running Drupal 6. When I log in to add new articles, it shows *Current Anonymous / Authenticated Users*.

How is this number computed?

# Answer
> 1 votes
Have a look at what's written in Comment nr 5 of issue nr 799262, ie:

> Basically, the anonymous user count in Drupal core's "who's online" block counts how many sessions are stored in the database, minus the number of authenticated sessions.
>
> If you haven't correctly configured PHP to periodically cleanup the active sessions, the table will continue to grow. I just cleaned one today with ~75,000 old anonymous sessions. This not only causes confusion in the who's online block, but also has a severe performance impact on your site if it's mildly busy.
>
> This article shows you what you need to put in settings.php to ensure your anonymous sessions are being cleaned: https://techcommons.stanford.edu/topics/drupal/sessions-table-cleanup

---
Tags: users, 6
---


# Question
Title: Session variable lost after setting it in ajax call
In my custom `.js` code included into administration panel via my custom module I have AJAX call:

```
... //call this on click or sth
jQuery.post("sites/all/...mycustommodule/ajax/here.php", function(result){ alert(result); }

```

And `here.php` defines some custom session variable:

```
<?php
sesssion_start();
$_SESSION['test_module_test'] = 'test';
echo $_SESSION['test_module_test'];
?>

```

When I hit `here.php` with POST request thanks to my `.js` code I get alert with session variable outputed:

> test

But then, when I try to `print_r($_SESSION['test_module_test'])` inside my custom module code, I always get some session variables, but without my `test_module_test`:

```
Array
(
    [views_seed_time-...] => 1482412682
    [views_seed_name-...] => 1482412682
)

```

I don't know if the session gets destroyed in between or there's something else going on here.

# Answer
> 2 votes
I'd assume those are 2 different sessions; use `session_id()`in both contexts to confirm.

To make sure you're using the same session, just implement your AJAX path inside Drupal, with `hook_menu()`

---
Tags: 7, ajax, sessions
---


# Question
Title: Trying to access PHP library from within another namespace
I'm a little new to the concept of Namespaces in PHP/Drupal, and I'm trying to figure out where I am going wrong here.

I've got this custom PHP library under the /libraries folder - let's call it `ilib`. And inside of ilib, there is another directory called `lms`.

Anyway, I've written a little module that will connect with ilib (or I am attempting to get it to connect with it), called ilib\_connect.

I am trying to do a test function inside a custom page with a controller for the page, as such:

```
namespace Drupal\ilib_connect\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use ilib\lms;

/**
 * Controller routines for page example routes.
 */
class iLibController extends ControllerBase {

function ilib_connect_test() {
  $lms = new \ilib\lms;
  \Drupal::logger("ilib_connect")->notice("<pre>" . $lms . "</pre>");
  $lms->AddLMSActivity();
  return "fake markup";
  }

}

```

However I am getting the error:

```
Error: Class 'ilib\lms' not found in Drupal\ilib_connect\Controller\iLibController->ilib_connect_test() (line 17 of modules/custom/ilib_connect/src/Controller/iLibController.php).

```

So I'm sorta having trouble pulling any classes from ilib into scope.

How exactly do I pull a third party library into scope in a situation like this? What about in a .module file?

What exactly am I misunderstanding here?

EDIT: Oh and just to be clear, this is how I am registering the custom library with Composer:

```
"autoload": {
"psr-4": {"ilib\\": "web/libraries/ilib"}
}

```

EDIT 2 - question to Clive:

Ah, so say I've got a file named AddLMSActivity.php inside of libraries/ilib/lms, setup like this:

```
namespace ilib\lms;

class AddLMSActivity
{

}

```

How would I access it exactly?

ilib\lms\AddLMSActivity?

# Answer
> 1 votes
When you use `use` you need to provide namespace + classname. This is what you are doing already, so

`use ilib\lms;`

Should be replaced with

`use ilib\lms\AddLMSActivity;`

If you want to use the `AddLMSActivity` class.

---
Tags: 8
---


# Question
Title: How to get a dynamic Google map with filtered views and show a marker related to the selected item?
I plan to create a real estate agency website. In the front page, users can select the type of contract and specific other things to get a list of all the nodes that fit those criteria. So the result is a view (filtered).

I want to get a Google map with marker related to this result. This is possible, but the thing that I can't do is this: when I select an item from this filtered view (with a checkbox for example) I want to recalculate the Google map with only this or those items selected.

About the modules I'm using: in fact until now I use nothing, this is why I post the question, to know if a module (such gmap or simple Google Maps) is better for doing such kind of stuff.

# Answer
> 1 votes
Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.

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


# Question
Title: Import external modules yaml config through own hook_update_N implementation
I am trying to update a module on an old project of mine. In the meantime the module's devs added new configuration and schema yaml files but did't write the update functions for already existing sites.

How would you import all schema and config changes automatically? Do I need to import the yaml files though `Yaml::parse` and then use `\Drupal::configFactory()` and `\Drupal::entityDefinitionUpdateManager()` in my hook\_update\_N function? Or is there an easier way?

# Answer
> 1 votes
If you have no data then reinstall the module.

If you want to keep the data then this depends what you have changed in the configuration. You can try how far you can get with the method you've described. If you only add fields, this will probably work. Also minor changes to a field can work. But if you change how a field is stored in the database this will not work.

The official way to do this is described here https://www.drupal.org/node/2554097.

---
Tags: 8, database, updating
---


# Question
Title: How to put a custom form inside node form with own submit button?
I have a small custom form which has its own submit button.

```
$form['activity']['submit'] = array(
      '#type' => 'button',
      '#value' => t('Execute'),
      '#name' => 'test_button',
      '#submit' => array('my_custom_form_submit')
    );

```

I placed this in the page manager in the node edit form.

But the problem is the function `my_custom_form_submit` is not get executed. Instead the node form gets submitted and redirected to node view page.

Is there any way to to execute 'my\_custom\_form\_submit' function on clicking on the custom form submit button?

**Note**: I don't need ajax, I want it without ajax.

# Answer
> 1 votes
you should use an ajax in inner form on submit like :

```
  $form['activity']['submit'] = array(
  '#type' => 'button',
  '#value' => t('Execute'),
  '#name' => 'test_button',
  '#ajax' => array(
    'callback' => '_handle_form_submit',
    'effect' => 'fade',
),
);

 function _handle_form_submit($form, $form_state) {
 // your stuff here
 }

```

you can see ajax example modules Ajax Examples

# Answer
> 0 votes
I think the problem is in submit type.

**Code** -

```
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Execute'),
  '#name' => 'test_button',
  '#submit' => array('my_custom_form_submit')
);

```

---
Tags: 7, forms, nodes
---


# Question
Title: filter view by parent of a taxonomy term
In drupal 7, how can I filter content of node type by the parent of a taxonomy term, such that if the content has a child of this taxonomy term it will come out if the parent is chosen as the filter ?

I want to be able to add children without having to modify the view each time as to which terms are in the filter, having it rely only on the parent as the filter by term.(can be done using depth level from the parent term)

# Answer
There is a view filter as **Content: Has taxonomy terms (with depth)** which describes as -

Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.

You can select one of the parent term and set the depth of its child terms too.
> 4 votes

---
Tags: 7, views
---


title: FillPDF syntax for multiple webforms

text:
# Question
Title: FillPDF syntax for multiple webforms
I have a single PDF form with fields specified to several webforms. I can successfully generate a PDF for each form individually. using the url http://mydomain.dd:8083/fillpdf?fid=58&webform\[nid\]=19 and http://mydomain.dd:8083/fillpdf?fid=58&webform\[nid\]=33.

How do I combine the two NIDs into one FID=58?

Thanks for your help.

# Answer
After many back and forths, I figured out the syntax for using multiple webforms (and this can be applied to NIDs). The syntax would be:

http://yourwebsite.dd:8083//fillpdf?fid=61&webforms\[0\]\[nid\]=33&webforms\[1\]\[nid\]=19

You can increment the webform number and continue to add NIDs. I am pretty sure that this syntax works with SIDs as well, but I have no need for anything other than the most current submission at this time.

Additionally, note that as of the writing of this... this does NOT work the production version (7.x-1.10) of FillPDF but ONLY with the development version (7.x-1.x-dev).
> 0 votes

---
Tags: files
---


title: On Autocomplete empty

text:
# Question
Title: On Autocomplete empty
I have a project that I need to display some help text to the user if an autocomplete text comes back empty.

Right now, the autocomplete is on a custom form, and I'm using an autocomplete like:

```
function autocomplete($string) {
  $result = autocomplete_lookup($string);
  $matches = array();
  // Save the query.
  foreach ($result as $row) {
    // Perfom my logic rows here.
  }

  drupal_json_output($matches);
}

```

Is there a way I can run a check at some point in the process to display a pop up or something if the autocomplete doesn't return anything?

# Answer
> 1 votes
Not sure if it would help or not, but if your looking for trying to tell the user nothing exists in the database, you can always add logic to the autocomplete that will return something to the field that indicates no results are found.

# Answer
> 0 votes
You can consider using select2 module. It can take charge of your autocomplete field and will show a message something as 'No Result Found' or similar, but not any pop-up.

---
Tags: 7, ajax
---


# Question
Title: I have the following errors in my configuration page
I uninstalled a few modules.

```
    ~/apps/drupal/htdocs/modules$ drush pm-uninstall relaxed
    The following extensions will be uninstalled: relaxed
    Do you really want to continue? (y/n): y
    relaxed was successfully uninstalled.                                                                                [ok]
    bitnami@ip-172-26-15-109:~/apps/drupal/htdocs/modules$ drush pm-uninstall replication
    The following extensions will be uninstalled: replication
    Do you really want to continue? (y/n): y
    replication was successfully uninstalled.                                                                                [ok]
    bitnami@ip-172-26-15-109:~/apps/drupal/htdocs/modules$ drush pm-uninstall multiversion
    The following extensions will be uninstalled: multiversion
    Do you really want to continue? (y/n): y
    multiversion was successfully uninstalled.
    bitnami@ip-172-26-15-109:~/apps/drupal/htdocs/modules$ drush pm-uninstall views_rest_feed
    The following extensions will be uninstalled: views_rest_feed
    Do you really want to continue? (y/n): y
    views_rest_feed was successfully uninstalled.

```

And now I see errors. I see following errors, how should I proceed with fixing them? Entity/field definitions Mismatched entity and/or field definitions The following changes were detected in the entity type and field definitions. Comment

```
The Comment entity type needs to be updated.

```

File

```
The File entity type needs to be updated.

```

Content

```
The Revision ID field needs to be installed.
The UUID field needs to be updated.

```

Shortcut link

```
The UUID field needs to be updated.

```

Taxonomy term

```
The Taxonomy term entity type needs to be updated.

```

User

```
The UUID field needs to be updated.

```

Custom menu link

```
The Custom menu link entity type needs to be updated.

    Running drush entity-updates gives
    The following updates are pending:

    comment entity type :
      The Comment entity type needs to be updated.
    file entity type :
      The File entity type needs to be updated.
    node entity type :
      The Revision ID field needs to be installed.
      The UUID field needs to be updated.
    shortcut entity type :
      The UUID field needs to be updated.
    taxonomy_term entity type :
      The Taxonomy term entity type needs to be updated.
    user entity type :
      The UUID field needs to be updated.
    menu_link_content entity type :
      The Custom menu link entity type needs to be updated.

    Do you wish to run all pending updates? (y/n): y
    Drupal\Core\Entity\EntityStorageException: The SQL storage cannot change the schema for an existing entity type (comment) with data. in    [error]
    Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->onEntityTypeUpdate() (line 303 of
    /opt/bitnami/apps/drupal/htdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).
    Failed: Drupal\Core\Entity\EntityStorageException: !message in                                                                             [error]
    Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema->onEntityTypeUpdate() (line 303 of
    /opt/bitnami/apps/drupal/htdocs/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php).
    Cache rebuild complete.                                                                                [ok]
    Finished performing updates.

    drush watchdog-show
     ID   Date          Type      Severity  Message
     147  22/Dec 15:57  php       error     Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column
                                            'base_table.vid' in 'field list': SELECT base_table.vid AS vid, base_table.nid AS nid

     146  22/Dec 15:57  php       error     Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column
                                            'base_table.vid' in 'field list': SELECT base_table.vid AS vid, base_table.nid AS nid

     145  22/Dec 15:57  cron      notice    Cron run completed.
     144  22/Dec 15:57  cron      notice    Execution of update_cron() took 9.97ms.
     143  22/Dec 15:57  cron      notice    Starting execution of update_cron(), execution of system_cron() took 15.01ms.
     142  22/Dec 15:57  cron      notice    Starting execution of system_cron(), execution of search_cron() took 4.15ms.
     141  22/Dec 15:57  cron      notice    Starting execution of search_cron(), execution of node_cron() took 30.37ms.
     140  22/Dec 15:57  cron      notice    Starting execution of node_cron(), execution of history_cron() took 1.82ms.
     139  22/Dec 15:57  cron      notice    Starting execution of history_cron(), execution of file_cron() took 11.11ms.
     138  22/Dec 15:57  cron      notice    Starting execution of file_cron(), execution of field_cron() took 3.38ms.

```

Also accessing http://ipaddress/admin/modules/uninstall gives

```
    The website encountered an unexpected error. Please try again later.

```

Apache error log shows

```
    [Thu Dec 22 15:06:52.683333 2016] [core:notice] [pid 13291:tid 139826185398080] AH00094: Command line: '/opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf'
    [Thu Dec 22 15:06:58.953491 2016] [proxy_fcgi:error] [pid 13300:tid 139825856366336] [client 123.201.127.176:49572] AH01071: Got error 'PHP message: PHP Fatal error:  Call to a member function id() on null in /opt/bitnami/apps/drupal/htdocs/modules/multiversion/src/WorkspaceCacheContext.php on line 44\n'
    [Thu Dec 22 15:12:39.540744 2016] [proxy_fcgi:error] [pid 13299:tid 139825386374912] [client 123.201.127.176:49808] AH01071: Got error 'PHP message: Uncaught PHP Exception Drupal\\Core\\Database\\DatabaseExceptionWrapper: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'revision.revision_id' in 'field list': SELECT revision.revision_id AS revision_id, revision.langcode AS langcode, revision.revision_log AS revision_log, base.id AS id, base.type AS type, base.uuid AS uuid, CASE base.revision_id WHEN revision.revision_id THEN 1 ELSE 0 END AS isDefaultRevision\nFROM \n{block_content} base\nINNER JOIN {block_content_revision} revision ON revision.revision_id = base.revision_id; Array\n(\n)\n" at /opt/bitnami/apps/drupal/htdocs/core/lib/Drupal/Core/Database/Connection.php line 671\n'
    [Thu Dec 22 15:14:41.556451 2016] [proxy_fcgi:error] [pid 13299:tid 139825428338432] [client 123.201.127.176:49828] AH01071: Got error 'PHP message: Uncaught PHP Exception Drupal\\Core\\Database\\DatabaseExceptionWrapper: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'revision.revision_id' in 'field list': SELECT revision.revision_id AS revision_id, revision.langcode AS langcode, revision.revision_log AS revision_log, base.id AS id, base.type AS type, base.uuid AS uuid, CASE base.revision_id WHEN revision.revision_id THEN 1 ELSE 0 END AS isDefaultRevision\nFROM \n{block_content} base\nINNER JOIN {block_content_revision} revision ON revision.revision_id = base.revision_id; Array\n(\n)\n" at /opt/bitnami/apps/drupal/htdocs/core/lib/Drupal/Core/Database/Connection.php line 671\n'

```

Have run drush cr The errors remain in admin/reports/status

After reinstalling multiversion, above report status errors are fixed. I get an error when I create an article Following is apache log

```
    Thu Dec 22 18:20:11.742576 2016] [proxy_fcgi:error] [pid 13299:tid 139825604585216] [client 42.109.14.45:43240] AH01071: Got error 'PHP message: Uncaught PHP Exception Drupal\\Core\\Entity\\EntityStorageException: "SQLSTATE[HY000]: General error: 1364 Field 'vid' doesn't have a default value: INSERT INTO {node_revision} (nid, langcode, revision_timestamp, revision_uid, revision_log) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array\n(\n    [:db_insert_placeholder_0] => 1\n    [:db_insert_placeholder_1] => en\n    [:db_insert_placeholder_2] => 1482430811\n    [:db_insert_placeholder_3] => 1\n    [:db_insert_placeholder_4] => \n)\n" at /opt/bitnami/apps/drupal/htdocs/modules/multiversion/src/Entity/Storage/ContentEntityStorageTrait.php line 152\n', referer: http://52.91.79.10/node/add/article

```

Have run sudo drush entity-updates again, I get the following

```
           No entity schema updates required                                                                                [success]
    Cache rebuild complete.                                                                                [ok]
    Finished performing updates.                                                                                [ok]

```

Running drush updb gives the following sudo drush updb No database updates required \[success\]

I am using AWS lightsail bitnami drupal instance.

# Answer
> 1 votes
The error is on uninstalling multiversion module.

The error that you got in the log was due to no values inserted to revision\_log column in node\_revision table.

It's advised that you install multiversion module right after installing your site (or before adding content).This module will convert all of the content entities on your site to be revisionable.

I suggest you to take a fresh new drupal setup to resolve this as you will again and again face such type of fatal errors.

---
Tags: 8, configuration
---


# Question
Title: Programmatically load 'add content' form for custom content type in form or block plugin
I understand that users could use 'add content' from the admin menu, but I'm building a custom block plugin or form so the add content form can be displayed in a block on the page instead of requiring users to use an actual admin page. I've done this before by manually creating forms in a render array in a form plugin that save the field values into a node upon form submit, but it'd nice to actually be able to just grab the actual add node form and render it directly.

In my research I found code to do this for Drupal 7

```
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'yourContentType';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form('yourContentType_node_form', $node_form);
return $form;

```

But I need a way to do this in Drupal 8. I've loaded custom form controllers before like so

```
$content = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');

```

But I'm not sure how I would add a specific 'add content' form. How would I get the form of any 'add content' for a specific content type?

UPDATE: I found a path to something called 'NodeForm' and I tried to use it like so

$content = \Drupal::formBuilder()-\>getForm('Drupal\node\NodeForm\publication');

Where publication was a content type I wanted to load the form for. But I receive an error

> The form argument Drupal\node\NodeForm\publication is not a valid form

And out of curiosity I tried

```
$content = \Drupal::formBuilder()->getForm('Drupal\node\NodeForm');

```

But that gives me the error

> Fatal error: Call to a member function getEntityTypeId() on null in /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

# Answer
Entity forms are built by EntityFormBuilder::getForm(). The parameter is an entity not a form class. This can be an existing entity or a new entity to add content.

For example to add content for the content type article you create this entity:

```
$node = \Drupal\node\Entity\Node::create(['type' => 'article']);

```

Use the new entity to build the form:

```
$form = \Drupal::service('entity.form_builder')->getForm($node);

```
> 5 votes

---
Tags: nodes, forms, 8
---


title: How to insert form into node/add page

text:
# Question
Title: How to insert form into node/add page
I am currently developing a module with a custom content type. In the node/add for this content type, I need to be insert a form that can retrieves data from an API, that will later be displayed on the page.

What is the best way to insert that form into the node/add page?

Should I use a hook\_form\_alter? Or should I make a custom field? This portion of the form will most likely involve AJAX, so I don't know if that will change anything.

Let me know if I need to clarify anything, and thanks in advance!

# Answer
> 2 votes
Whether you create a custom field then modify it later, or create it completely in code, you need to use hook\_form\_alter in your custom module and add/edit your field that way and add the ajax call inside this function.

If you create a custom field in config, then there's now a config dependency you will need to somehow move from your dev environment to production (either thru Features or Configuration modules). On the other hand, if you add all through your custom module you won't need to worry about config changes, so IMO that is a better way.

---
Tags: 7, forms, ajax
---


# Question
Title: Get Field Manage Display configuration in node preprocess
I am preprocessing the data and I have overridden the node template, during the preprocessing I am not able to figure out how can I respect "Manage Display" configs. As an example if date field is configured to have a specific format, or image field is configured to have specific Image Style.

So my question is how can I call the Manage Display configurations during node preprocessing.

# Answer
> 1 votes
As @googletorp commented, the field should be rendered automatically considering the Manage Display configuration.

In my case \[I was a node which has reference to paragraph A and A has reference to paragrapgh B which has a date field. The twig template markup needs heavy customisation so I was preprocessing the data to make it consumable by custom twig templates, now in order to get the date field show on node I have to load referenced paragraph entites and map the fields, because of which the fields was not rendering through the '#theme' =\> 'field' and Manage Display configs were not working.

But in order to make it working while mapping the field values we can can actually call for rederable field definition, something like

```
$date = $entity->field_date->view('full');

```

# Answer
> 0 votes
You can get the view mode

```
$viewmode = \Drupal\Core\Entity\Entity\EntityViewMode::load('node.teaser')

```

or the display options

```
$displayoptions = \Drupal\Core\Entity\Entity\EntityViewDisplay::load('node.article.teaser');

```

If you want to debug the configuration use `$viewmode->toArray()` or `$displayoptions->toArray()`.

In most cases you don't need this information in preprocess, because you have the result from the field formatter in the variable `content` and you would not want to build this from scratch again. If you want to change how a field is built use a custom field formatter.

---
Tags: 8
---


# Question
Title: Tabledrag in Drupal 7 admin pages only working in Firefox
For some reason, in the last couple of days any table that is tabledrag enabled (in core admin interfaces like the menu editor, as well as custom modules) only works in Firefox.

In IE and Chrome there are no errors reported in the console, the row is highlighted on mousedown, but nothing happens when you drag.

Has anyone else encountered this and know of a fix?

# Answer
> 3 votes
There was a regression introduced in 7.52 related to dragging in the admin interface. It's fixed in the 7.53 release. It may be as simple as upgrading to the latest version of core.

The 7.53 release page, https://www.drupal.org/project/drupal/releases/7.53.

---
Tags: 7
---


# Question
Title: Is it acceptable to change the vid column of a term programmatically in the database?
I need to move some terms from one vocabulary to another by retaining all their data: translations, aliases, and node references.

Is it acceptable to change its `vid` column value directly in the database? The terms don't have hierarchy relationships which needs to be handled.

# Answer
## Database

It's possible to do a lot of things in Drupal simply by making SQL queries, either through Drupal or externally. Generally, you never want to take this approach. There are some cases where it can work just fine, but most of the time there is no reason to do it this way.

## API

Drupal has a rich API, this is true for Drupal 6, 7 and 8, as they has always been a key feature in Drupal. In your concreate example, you could use `taxonomy_term_load` and `taxonomy_term_save` to facilitate an update of a term. Doing it this way, you can edit any data part including the `vid`. Just because you do it with API's doing *forbidden* things wont just automatically work, but the chance of things going well is drastically improved.

In this concrete example the API doesn't do anything that is necessarily needed. It sets some internal data on the term and invoke hooks letter module know that is has been updated.

You should note that things can break, if the term you want to change is part of a hierarchy. Things can also break for nodes referencing the term, if the field is not allowed to reference terms in the new vocabulary.

## Migration

Migration of data is the bullet proof solution, and unless you have a huge data set, it can be developed and executed pretty easily. The idea is to create a new term and migrate the content you want to migrate and then delete the old term. As an update hook, sample code could look like this:

```
/**
 * Put in modules .install file, replace xxxx with 7000 or higher
 */
function MODULE_NAME_update_XXXX(&$sandbox) {
  $term = taxonomy_term_load(CONSTANT_WITH_TID);
  $new_term = clone $term;
  unset($new_term->tid);
  unset($new_term->tid);
  $new_term->vid = CONSTANT_WITH_VID;
  taxonomy_term_save($term);
  // Find all nodes we want to update and update them.
  // If there is a lot of nodes, can use $sandbox to make this a batch job.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->fieldCondition('field_which_is_term_reference', 'tid', $term->tid);
  $result = $query->execute();
  foreach (node_load_multiple(array_keys($result['node'])) as $node) {
    $node->field_which_is_term_reference[LANGUAGE_NONE][0]['tid'] = $term->tid;
    node_save($node);
  }
  // Migration all done - delete the old term.
  taxonomy_term_delete($term->tid);
}

```

Please note that the above code is pure example code, written by heart. Might have syntax error or other errors and makes a lot of assumptions. This is just to illustrate an idea and demonstrate that a migration might not be a big deal.
> 11 votes

# Answer
It is ***not advisable*** to do direct database changes when working with Drupal. But Yes, if we know where all it can impact and do necessary changes accordingly, it is *OK* to do direct changes in database. Because in this case this is not possible through UI. ***NOTE:*** *If you've nodes associated with Term, you'll have to manually handle that as well.*

Check out this link that explains how we can change the term vocabulary in Drupal 7: Change the vocabulary of a taxonomy term in Drupal 7 using the database.
> 4 votes

# Answer
I would not recommend to change that term the way you described it in your question. Instead I'd use an alternative approach to achieve a similar result (in the order specified), which is further detailed below.

### Step 1 - Start using the new term in future node updates

Create a new taxonomy term field, so that "from now on" any future node updates (or new nodes being created) will use that new field. I assume these terms are used for nodes (if you use it for some other entity type, like users, etc), the same approach can be used for those entities also.

Use the Rules module to create a rule like so:

* Rules event: `before saving content`.
* Rules conditions:
    + `entity has field`, with field = the old field.
    + AND NOT (`entity has field`, with field = the new field).
* Rules Action: `set Drupal message`, which contains some instructions that the old field must be blanked out, and the new field should contain the appropriate value(s).

### Step 2 - Use Rules to speed up the process

Obviously, the approach in Step 1 will take "some" time if this has to be done manually, 1 node at a time. But using Views (to build a list of similar nodes to be updated) and VBO (to mass update such lists) you might (should!) be able to speed up this process quite a bit.

Especially if you'd use Rules to create a custom bulk operation for such VBO view, as explained in the answer to "How to use Rules to create a custom bulk operation for a VBO view?". Here is a prototype of a Rules Component that should help to implement such custom bulk operation (in Rules Export format):

```
{ "rules_replace_a_term_field_by_another_term_field" : {
    "LABEL" : "Replace a term field by another term field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_sample_tags" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } },
      { "data_is" : { "data" : [ "node:field-demo-tags" ], "value" : "1" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-sample-tags" ], "value" : "31" } },
      { "drupal_message" : { "message" : "Term updated in node with id = [node:nid]" } }
    ]
  }
}

```

Some more details to explain the above prototype:

* It uses a node as a parameter.
* These are the Rules Conditions:

+ check if the entity (= node) has a field `field_sample_tags`.
    + check if the entity (= node) has a field `field_demo_tags`.
    + check if the value of the field `field_demo_tags` corresponds to the term we want to replace (in this example, the term has id = `1`). Note that if this condition is not satisfied, no Rules Actions will be performed.
* These are the Rules Actions:

+ Set the value of field `field_sample_tags` equal to the term with term id = `31` (which is the term in the newly created vocabulary that matches the term in the vocabulary that is to be replaced).
    + Display a message on the site like `Term updated in node with id = 72`, whereas `72` is the node id of the updated node.

If you want, adapt the machine names of the field names in the above prototype, and the used term IDs. Then import it in your own site (using the Rules UI), and QA-test it using the "execute" link to the right of the imported Rules Component (and enter some node id to test it, after you switch to "direct input mode" to be able to specify a node id). If during your testing you don't get such a `Term updated in node ...` message, it must be because the node you selected did not use the term value specified in your rules Condition.

### Step 3 - Use VBO as the finishing touch

After you're finished QA-testing this Rules Component from Step 2, create a VBO-view of nodes to be processed, in which you refer to the Rules prototype above (or a variation of it to fit your needs).

### Benefit of this approach

Using this approach, you minimize the risk to introduce data inconsistencies (as compared to updating the database directly), with zero custom code involved (you'd only use the Views UI and Rules UI).
> 4 votes

# Answer
I know that you say programmatically but if you want to use a module you can use Taxonomy Manager

> 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
> 2 votes

---
Tags: 7, taxonomy-terms, database, entities
---


# Question
Title: How to move a taxonomy term from one vocabulary to another?
How can I change vocabulary of some taxonomy term? And keep all its data - tid, references, fields, alias and translations (except hierarchy)?

# Answer
Term merge module seems to be what you are looking for. Just adding some features as is from its project page on D.O.

> Updating term references in the field values, swapping values from the branch term to the trunk term. We support taxonomy term reference, entity reference, and any other field types that correctly define their foreign keys.
>
> Keeping/Removing branch terms: you decide whether to keep or remove branch terms after the merge.
>
> Merging field values: you can specify a list of fields and during merge the values of those fields from branch terms will be added to the values of the trunk term. This way you can keep field values of the branch terms after deleting them.

So all you'll need to do is to create a new term to that other vocabulary and do a merge with the old term from the other vocabulary. As for the tid I don't think that is possible to be kept or even if there is any meaning in trying to do so since all data will be transferred to the new term.
> 1 votes

# Answer
You can use the Taxonomy Manager module

> 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.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Requestee user cannot remove a one way User Relationship with requester user
I have a one-way User Relationship which also can be reciprocated, and I have run into an issue where users cannot remove a one-way relationship with another user that they have previously approved.

For example, User B sends a one-way relationship request to User A. User A approves it. Then, User A decides they no longer want to have that relationship with User B, and they click the link to remove that relationship (for example, https://mywebsite.com/user/778/relationships/requested/3338/remove). The relationship is not removed, and User A is presented with this message: "No action has been taken". There is nothing in the Recent Log Messages that would point to any specific issue, and all of the Have/Maintain/Request/Delete permissions are enabled for Authenticated and other specific user roles that these users have.

How can I fix this, so that User A has total control over which approved relationships they have with User B?

# Answer
> 0 votes
I applied the patch listed here (https://www.drupal.org/node/1328170#comment-6980582) and that resolved the issue.

---
Tags: 7, users
---


# Question
Title: How to convert Mutual User Relationship to Reciprocal?
I had a relationship set up on my website (let's call it "Friends"), and many of my users have used it. It was a Mutual relationship. That relationship is being used to provide access to the user's nodes via Panels... for example, if User A and User B become friends, then User A can see User B's nodes, and User B can see User A's nodes.

I recently converted the (mutual) Friends relationship to One Way with the possibility of Reciprocation, because I now need to allow User A to request access to User B's nodes without giving User B access to User A's nodes. If User B then decides to request access to User A's nodes, they can do so because of the reciprocation setting.

That functionality is working fine for any new Friends. The problem I am having is that any Friend relationships that existed before the relationship was changed from Mutual to One Way/Recip are not acting like reciprocated relationships; they are acting like One Way relationships. Therefore, if User A was the one who requested the original mutual Friend relationship, they now own the One-Way relationship with User B, and User B does not own a reciprocal relationship with User A.

I need for the formerly Mutual Friend relationships to now be One Way with Reciprocation. How can I do this? Is there a way for me to edit it in the database perhaps? I definitely cannot ask all of the users to un-friend and re-friend their existing relationships.

Thanks!

# Answer
I found the issue... I had to update the Relationship IDs in the database for the originally-Mutual relationships because they shared the same RID, thus making each RID unique. The one-way/reciprocal relationships do not/cannot share the same RID.
> 0 votes

---
Tags: 7, users
---