# Question
Title: How to automatically unpublish / move to archive an article or node?
I need to have a functionality that allows users to create an article and choose for how long the user wants it to be published (for example 7 days or 2 weeks). After this time the node will automatically move to archive.

How can I achieve this in Drupal 7? I know that there were some modules (Node expire?) in Drupal 6, but I am not sure about Drupal 7. Any advice?

# Answer
> 8 votes
I think you can easily archive your goal with a bunch of module.

I guess with Rules that gonna help you to make some actions when the article will be unpublished. Flag module will help you to set a flag 'Archived article' and finally Scheduler that let your user to choose when the article will be archived.

# Answer
> 3 votes
I went round the houses with this and ended up using a HOOK\_cron function in a custom module. Here it is - hope it helps someone:

```
function mymodule_cron() {

// we only want to deal with messages (a content type)
$message_type = "message";

// grab all messages
$message_nodes = node_load_multiple(array(), array('type' => $message_type));
// set up the timestamp for the expiry
$message_search_date = strtotime("- 30 days"); // UNIX timestamp for 30 days ago

// now loop through messages, & if they are old, expire them
  foreach($message_nodes as $m) {

    $obj = entity_metadata_wrapper('node', $m);

    // when was it last updated, & is it still published?
    $last_update = $obj->changed->value();
    $published = $obj->status->value();

    // if it's still published & it's not recent, then unpublish it
    if(($message_search_date > $last_update) && $published<>0) {
        $obj->status = 0;
        $obj->save();
    }
  }
}

```

# Answer
> 1 votes
These days there is a 7.x release of the Node Expire module, however you can also use the Rules module, as further explained below.

# Part 1 - Unpublish the node

Use the Rules module together with `Rules Scheduler` (a sub-module of it), as explained in the steps below. These steps are based on the assumption that your content type is `article` (adapt to whatever else fits).

### Step 1: Create a field to store the expiration date

Add a field to the article content type (to store the "expiration" date), with these specs:

* Machine name (say) `field_expiration_date`.
* Use "date" as field type, for which the date module (and data API) needs to be enabled first.
* Allow only 1 date.

### Step 2: Create a Rules Component

Here is the **Rules Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_unpublish_a_node" : {
    "LABEL" : "Unpublish a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_to_be_unpublished" : { "label" : "Node to be unpublished", "type" : "node" } },
    "DO" : [ { "node_unpublish" : { "node" : [ "node-to-be-unpublished" ] } } ]
  }
}

```

### Step 3: Create a Rule using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste, then "enable" the rule also):

```
{ "rules_schedule_the_unpublish_of_a_node_as_requested_by_author" : {
    "LABEL" : "Schedule the unpublish of a node as requested by author",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_expiration_date" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_unpublish_a_node",
          "date" : [ "node:field-expiration-date" ],
          "identifier" : "Unpublish-node-[node:nid]",
          "param_node_to_be_unpublished" : [ "node" ]
        }
      }
    ]
  }
}

```

Note that the above rule refers to the *Rules Component* from the previous step. Make sure to only perform the import of this rule only **after** you completed step 1, if not the import will fail ... Should you want to use another machine name, then change `field_expiration_date` in the rule above to what you prefer, prior to importing this rule.

**Be aware**: the above rule is only triggered once, i.e. when the node (of type article) is first created (as in the question). It will right away schedule the unpublish of the node (as requested in the expiration date). If the node gets edited later on, and/or the expiration date is changed afterwards: too bad, that won't change anything to when the scheduled unpublish is going to happen. Also, from the question it isn't really clear if the expiration is optional or mandatory, so if needed make the expiration date a mandatory field.

# Part 2 - Move to archive

Your question doesn't really explain what you mean with "move to archive". Maybe just "unpublish" is already sufficient to consider it as archived right away. If not, you could use the Flag module. It would be straight forward to also flag the node via an additional Rules Action that you add to the above Rules Component.

And with those "flagged" nodes, you can then select from various approaches to actually implement such move to archive. Just to mention a few:

---
Tags: 7, nodes
---


title: How do I get the logo path?

text:
# Question
Title: How do I get the logo path?
I am creating custom theme for Drupal 8. I am uploading the logo from theme setting, but I am not able to print the path of that logo. What I am doing to print the full path of logo is using `{{ logo }}`, but it is not working.

In Drupal 7 we can get the full path of logo with the following code.

```
 <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

```

What is the equivalent for Drupal 8?

# Answer
The class implementing the block showing the theme logo, in `SystemBrandingBlock::build()` contains the following code.

```
  $build['site_logo'] = array(
    '#theme' => 'image',
    '#uri' => theme_get_setting('logo.url'),
    '#alt' => $this->t('Home'),
    '#access' => $this->configuration['use_site_logo'],
  );

```

So, for the path of the logo, you can simply use `theme_get_setting('logo.url')`, which returns `"/core/themes/bartik/logo.svg"`, in my test site.

If you want a relative URL for the logo file, for example because you want to use it for the `src` attribute of the `<img>` tag, you can do as `template_preprocess_image()` does.

```
$relative_url = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));

```

For an absolute URL, you can use the following code.

```
$absolute_url = file_create_url(theme_get_setting('logo.url'));

```

That code needs to go in a preprocess function, where it initializes a variable. For example, if I wanted the relative URL of the logo file in html.html.twig, I would use the following code.

```
function mytheme_preprocess_html(&$variables) {
  $variables['relative_logo_url'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));
}

```

And in the template, you would just use `{{ relative_logo_url }}` to get it.
> 14 votes

# Answer
In Drupal 8, the site logo was moved in a block.

In block layout, you place a branding block in a region, which you then can configure to contain the logo, the site name and/or the slogan. You can place multiple branding blocks to use site branding elements in different regions.
> 2 votes

---
Tags: theming, 8
---


title: Dont cache hook_form_form_id_alter

text:
# Question
Title: Dont cache hook_form_form_id_alter
I made a form, with a few fields. In the hook form alter I add some info text depending on the value of a $\_GET variable. Only the hook alter is only called the first time. I want is to be called every time the form is viewed.

Am I using the wrong hook?

# Answer
> 4 votes
You need to either disable cache entirely with max-age = 0 or to make it vary based on the GET argument value, which is the better way unless your GET argument unique for everyone or most people.

Something like `$form['#cache']['max-age'] = 0`;

See https://www.drupal.org/developing/api/8/render/arrays/cacheability for the documentation.

---
Tags: forms, 8, caching
---


# Question
Title: Unset a SQL condition with query builder
I try to remove a where condition to a query statement. To resume, I build a query and add geographical coordinates condition to get POI in a specific area. I execute the query and if there is no result, I remove the condition to get all the POI. Here the script :

```
//Declare the statement
$statement = $this->connection->select('table', 't')
            ->fields(/*...*/)
            ->range(/*...*/);

//Add the condition
$statement->condition("lat", [$GPSbounds['lat_min'], $GPSbounds['lat_max']], "BETWEEN");
$statement->condition("lng", [$GPSbounds['lng_min'], $GPSbounds['lng_max']], "BETWEEN");

// launch the SQL query
$statementInterface = $statement->execute(); // Execute the statement
$results = $statementInterface->fetchAll(\PDO::FETCH_OBJ); // Get all the results

```

So, if there is no result, I do this :

```
if (sizeof($results) == 0) {

    //We remove the bounds conditions
    //=& is reference equality, changes applicated to $conditions are applicated to $statement->conditions();
    $where =& $statement->conditions();
    foreach ($statement->conditions() as $index => $condition) {
        if (array_key_exists('field', $condition)) {
            if ($condition['field'] == 'lat' || $condition['field'] == 'lng') {
                unset($where[$index]);
            }
        }
     }

     //dump $statement->conditions() : condition is removed
     $statementInterface = $statement->execute(); // Execute the statement
     //dump $statementInterface->getQueryString() : condition is in the query so the result are empty again (as the first execution)
     $results = $statementInterface->fetchAll(\PDO::FETCH_OBJ); // Get all the results
}

```

If I do a *var\_dump()* of *$statement-\>conditions()* before *execute()*, the condition has been removed (not in the array). But after the *execute()*, if I dump the query string, the condition is present and the query result 0 result again (because of the condition restriction). What can I do ?

# Answer
Executing the same query builder object twice is not supported.

Instead, build the query with everything except the the two conditions, clone it, add the two conditions, if you have nothing, execute the original (or the clone, depending on which object you picked to execute first).
> 3 votes

---
Tags: 8, database
---


# Question
Title: How to properly declare module settings with options list
In my ConfigFormBase derived class I want to add select list to settings form.

How should I declare it in mymod.config.yml file?

I've tried:

```
mymod.config:
  type: config_object
  label: 'Settings'
  mapping:
    test_mode:
      type: checkbox
      label: 'Turn on test mode'
    country_code:
      type: multiple
      label: 'Action site'
      value:
        - 1
        - 22
        - 34
        - 56
        - 107
        - 168
        - 181
        - 209
        - 228

```

and can I specify list as key -\> value pairs also?

# Answer
Config schema doesn't know about allowed values. It's a about the structure of the stored configuration, *not* how it is displayed to the user.

It's up to you to implement the form for that, using e.g. a #type selection and #options.

For the config schema, it's type: boolean, not type checkbox. And type: integer, what you tried to use there doesn't exist.
> 3 votes

---
Tags: 8
---


# Question
Title: How to create a content type with associated products and customized attributes?
I am creating a little CRM at work and I have two content types:

1. Offers - with some text fields and references to users and companies.
2. Products - very simple with SKU, Title, Price

Now I want to attached some products to Offers and then alter their attributes like price, add quantity and then display all this as a view with the total amount of all prices sum together.

The final goal is to have multiple offers referencing products but with own price and quantity.

I hope this is not to confusing? I tried already entity reference but then I cannot at a custom price or quantity to those products.

# Answer
You can use the Field collection module

> Provides a field-collection field, to which any number of fields can be attached.

And create a Field collection field (in your Offer Content Type) with a reference to Product and a field named quantity and other named custom price.

So in your Offer you can have many Products with theirs quantities and custom prices.
> 1 votes

# Answer
I have a similar set up, using Businesses and Events. Events have a Entity Reference Field which links it to whichever business is selected. On the View for this display, I added a Relationship using the Entity Reference field:Content and the Contextual Filter:Content ID this will get any "items" directly related to the Business associated with it.

Not sure this answers what you're looking for. But hope it helps a little bit.
> 0 votes

---
Tags: views, nodes
---


title: Disabling backups after "drush up"

text:
# Question
Title: Disabling backups after "drush up"
I use `drush up` for sites on a shared server and development sites.

Within some months, my inode volume went from about 25% to 96%. Given I have already 30 days backwards of backup service, I don't really need this specific backup.

How can you disable the automatic backups created by Drush each time `drush update` is executed?

# Answer
> 4 votes
Yes, use the `--no-backup` option with your command.

```
drush --no-backup up myproject

```

If you're you're looking to make this a default option, you can do something like Bash aliasing and just run that alias instead:

```
alias drush-no-bup='drush --no-backup'

```

Then run:

```
drush-no-bup up myproject

```

---
Tags: drush, backups
---


# Question
Title: Unable to upgrade from version 5.10.0 to version 8
I tried upgrading from Drush 5.10.0 to Drush 8 using `sudo composer global require drush/drush:~8`, but it doesn't update anything.

> Changed current directory to /home/lupiyardo/.composer
> Running composer as root/super user is highly discouraged as packages, plugins and scripts cannot always be trusted
> ./composer.json has been updated
> Loading composer repositories with package information
> Updating dependencies (including require-dev)
> Nothing to install or update
> Generating autoload files

As confirmation Drush wasn't updated, the output of `drush --version` is *Drush 5.10.0*.

I looked at the composer.json file and it contains `'require': { }`.

How can I upgrade Drush?

# Answer
> 0 votes
The following code works for me in Linux Machine:
cd /usr/local/bin mkdir drush-8 cd drush-8 composer require drush/drush:8.x ln -s /usr/local/bin/drush-8/vendor/bin/drush /usr/local/bin/drush8

Let me explain a little bit:

* Go to folder `/usr/local/bin`
* Create a new folder `drush-8` * go to the folder above
* Install drush (here more info: https://docs.drush.org/en/master/install/ )
* Finally, create a Symbolic Links that point to new `drush` version

---
Tags: drush, composer
---


# Question
Title: Field Template Loop Counter Override Problem
I'm using a template override for field.html.twig

I'm simply trying to generate a data-depth attribute that takes the index of the loop and multiplying it by 0.2.

Here is the Twig markup:

```
<div{{ attributes.addClass(classes, 'field--items') }}>
  {% for item in items %}
    {% set i = loop.index %}
    {% set depth = i * 0.2 %}
    <div {{ item.attributes.addClass('field--item') }} {{ attributes.setAttribute('data-type', 'test') }} {{ attributes.setAttribute('data-depth', depth) }}>
      {{ item.content }}
    </div>
  {% endfor %}
</div>

```

Here is the HTML output:

```
<div data-quickedit-field-id="paragraph/2/field_test/en/default" class="field field--name-field-test-image field--type-image field--label-hidden field--items">
  <div class="field--item" data-type="test" data-depth="0.2">
    <img src="/sites/default/files/2016-08/5.png">
  </div>
  <div class="field--item" data-type="test" data-depth="0.2">
    <img src="/sites/default/files/2016-08/4.png">
  </div>
  <div class="field--item" data-type="test" data-depth="0.4">
    <img src="/sites/default/files/2016-08/3.png">
  </div>
  <div class="field--item" data-type="test" data-depth="0.6">
    <img src="/sites/default/files/2016-08/2.png">
  </div>
  <div class="field--item" data-type="test" data-depth="0.8">
    <img src="/sites/default/files/2016-08/1.png">
  </div>
</div>

```

As you can see the first two iterations are the same - they have 0.2 as the data-depth which is incorrect it, the sequence should be 0.2, 0.4, 0.6, 0.8 and 1.0. Is this is a bug with drupal? Or am I totally missing something here.

Thanks in advance.

# Answer
> 1 votes
I just tested this and it works for me:

```
   {% for item in items %}
        {% set counter = ( counter | default(0) ) + 0.2 %}
        <div{{ item.attributes.addClass(item_classes) }} data-depth="{{ counter }}">{{ item.content }}</div>
      {% endfor %}

```

This renders as:

```
<div class="field field--name-field-gallery-ref" data-depth="0.2">
...
<div class="field field--name-field-gallery-ref" data-depth="0.4">
...

```

Note, I did not get the repeating depth numbers as you did above.

---
Tags: theming, entities, 8
---


# Question
Title: How can I override the string programmatically in forum topic list?
I am using the Forum module in Drupal 7. I want to change `"Topic"` with `"foo"`, for example, in the *General discussion* forum page.

>

### Where did I search for this

1. I did check the template in the forum module file and for this page it is `forum-topic-list.tpl.php`. There I found that, it is printed by following code,

```
<thead>
    <tr><?php print $header; ?></tr>
</thead>

```

And in the description, the following statement has been provided.

> Available variables:
>
> * $header: The table header. This is pre-generated with click-sorting information. If you need to change this, see `template_preprocess_forum_topic_list()`.

Hence, there is nothing called "Topic" which I can just change as this header coming from the $header.

Now, I did check `template_preprocess_forum_topic_list()` but it does not have provision to Change "Topic" string.
2. Lastly, I did check the forum.module where I found the following function starting at line 914.

```
 function forum_get_topics($tid, $sortby, $forum_per_page) {
   global $user, $forum_topic_list_header;

   $forum_topic_list_header = array(
     NULL,
     array('data' => t('Topic'), 'field' => 'f.title'),
     array('data' => t('Replies'), 'field' => 'f.comment_count'),
     array('data' => t('Last reply'), 'field' => 'f.last_comment_timestamp'),
  );

```

Now, in the above function you can see `t('Topic')`. I could simply replace it with `t('foo')`, but I think this is not the right way.

Any suggestion, how can I override this? Thanks.

# Answer
> 1 votes
If you check the code in `template_preprocess_forum_topic_list()`, you can see the `$header` is built with the global variable `$forum_topic_list_header`. It is possible to override it.

Most of the code here is copy from `template_preprocess_forum_topic_list()`. Only the part of code for building `$header` is needed.

```
/**
 * Implements hook_preprocess_forum_topic_list().
 */
function mymodule_preprocess_forum_topic_list(&$variables) {
  global $forum_topic_list_header;
  $forum_topic_list_header[1]['data'] = t('foo'); // Change "Topic" string

  // Create the tablesorting header.
  $ts = tablesort_init($forum_topic_list_header);
  $header = '';
  foreach ($forum_topic_list_header as $cell) {
    $cell = tablesort_header($cell, $forum_topic_list_header, $ts);
    $header .= _theme_table_cell($cell, TRUE);
  }
  $variables['header'] = $header;
}

```

# Answer
> 1 votes
You could do it using the String Overrides module.

> Provides a quick and easy way to replace any text on the site.

---
Tags: 7, nodes
---


# Question
Title: How to add image field to module install file
How to add image field to database in module install file? I found on api documentation, that type is image, so tried the following code:

```
function profile_bg_schema() {

$schema = array();

$schema['profile_bg'] = array(
  'description' => 'The table containing backgrounds',
  'fields' => array(
    'bid' => array(
      'description' => 'The primary identifier for the background.',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'image' => array(
      'description' => 'The background image.',
      'type' => 'image',
      'not null' => TRUE,
      'default' => '',
    ),
    'class' => array(
      'description' => 'The class added to div.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => '',
    ),
  ),
  'primary key' => array('bid'),
);

$schema['profile_bg_unlock'] = array(
  'description' => 'User - background - active table',
  'fields' => array(
    'uid' => array(
      'description' => 'User ID.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
     'bid' => array(
      'description' => 'Background ID.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'status' => array(
      'description' => 'The primary identifier for the background.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => '0',
    ),
  ),
);

return $schema;

}

```

First I was getting an error about image field, now module becomes ON, but nothing changes in database.

---- EDIT ---- Error below. It looks like Drupal do not know what type of field should create in database.

```
   Notice: Undefined index: image:normal w DatabaseSchema_mysql->processField() (linia 205 z C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\drupal\includes\database\mysql\schema.inc).
    PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL COMMENT 'Background Img.', `class` VARCHAR unsigned NOT NULL DEFAU' at line 3: CREATE TABLE {profile_bg} ( `bid` INT unsigned NOT NULL COMMENT 'bg ID.', `image` DEFAULT NULL COMMENT 'Background Img.', `class` VARCHAR unsigned NOT NULL DEFAULT '' COMMENT 'css class for the background.', PRIMARY KEY (`bid`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'background table'; Array ( ) w db_create_table() (linia 2720 z C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\drupal\includes\database\database.inc).

```

# Answer
You are reading the wrong documentation. Please read Data Types instead. There is no `image` type for database field.

The available data type are:

* serial
* int
* float
* numeric
* varchar
* char
* text
* blob

Since Drupal manage file (including image files) in `file_managed` table with key `fid`. What you need is to create a `int` column for storing the value of foreign key `fid`. The column definition should be:

```
'image_fid' => array(
  'description' => 'The {file_managed}.fid being referenced in this field.',
  'type' => 'int',
  'not null' => FALSE,
  'unsigned' => TRUE,
),

```
> 1 votes

# Answer
There's no actual "image" field type in your database. You'll want to create it in hook\_schema() as a regular "int" field. Then on the form that will process the image, you'll have a "managed\_file" form element that processes the file. Finally, in your form submission, save the file FID number in the "int" field in your database.

Something like the below should work:

```
function mymodule_form($form, $form_state) {

    $form['logo_upload'] = array(
        '#type' => 'managed_file',
        '#title' => t('Logo'),
        '#description' => t('Upload a logo.'),
        '#upload_location' => 'public://',
        '#default_value' => $entity->logo, // make sure to set the default value to the current file FID saved in your database field
    );

    $form['actions'] = array('#type' => 'actions');

    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_form_submit'),
    );

    return $form;
}

function mymodule_form_submit(&$form, &$form_state) {
    // $form_state['values']['logo_upload'] is the file FID number, but it is
    // still in temporary status. So load the file, and update the status to permanent.

    $file = file_load($form_state['values']['logo_upload']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    $form_state['values']['logo'] = $file->fid;

    // at this point, $form_state['values']['logo'] is the file FID of the uploaded
    // file. Save this value in your "int" field in the database.
}

```
> 0 votes

---
Tags: 7, media, installation
---


# Question
Title: ajax pager working depends on if js file is loaded in module .info file
I'm using the code I've outlined in my blog post for a custom image search, and I'm having a problem with the pager, but only on one site. The first page of results renders just fine, but when I try to go to a subsequent page, I get a white screen with JSON; the page modal window is not rendered.

Here's the relevant code where it breaks:

```
  $form_state['values']['title'] = t('Search Results - Page !page', array('!page' => $pager + 1));
  $output = ctools_modal_form_render($form_state['values'], $build);

  print ajax_render($output);
  drupal_exit();

```

What's weird is that I have this exact same code working on two different sites, and it works fine on one, but not the other. I've looked at every possible variable I can think of, and they're all the same:

* Drupal core version
* jQuery version
* module code (custom and contrib, Filefield Sources in this case)
* form output sent to ajax\_render
* returned output from ajax\_render

What else could I be missing that causes the JSON not to be rendered? I'm not looking for code specific info, just bigger picture items I could be missing.

Thanks.

**UPDATE**: So it looks like the problem has to do with the loading of my Drupal behaviors js file (seen at the bottom of this post. If I load it in the module .info file, the pager works fine, but if I attach it anywhere else - either to the node edit form or the ctools modal form - the pager chokes. I've inspected the page, and my js file is loaded in the page and ctools classes assigned to the pager buttons before clicking the pager, so it's not like they're not there. Unfortunately, for some reason, loading this file in the .info file causes other problems, so we can't do it globally.

But why would the method of loading the file make a difference as long as it's loaded?

# Answer
> 0 votes
It is the Drupal behavior JS code copied form your blog post.

```
(function ($) {
  Drupal.behaviors.addCtoolsModalClass = {
    attach: function (context) {
        $('#modalContent .pagination ul li a').addClass('ctools-use-modal');
        $('#modalContent .pagination ul li a').addClass('ctools-modal-imgsearch-modal-style');
    }
  }
})(jQuery);

```

The most meaningful thing I can find here is the class name `ctools-use-modal`. Obviously, this class name is used for ctools module. So I search this class name and find below snippet from `js/modal.js` in ctools module (version 7.x-1.9).

```
  Drupal.behaviors.ZZCToolsModal = {
    attach: function(context) {

      $('area.ctools-use-modal, a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);

```

Now we have the full picture.

In your JavaScript code, you want to add a class name which is required for Ctools JavaScript code. AJAX does not work because the Ctools JavaScript code is run before adding the class name, so `Drupal.CTools.Modal.clickAjaxLink` never bind to the link.

Yu can fix it by manually run the attach behavior again after adding classname.

**Solution**

```
(function ($) {
  Drupal.behaviors.addCtoolsModalClass = {
    attach: function (context) {
        $('#modalContent .pagination ul li a', context)
          .addClass('ctools-use-modal')
          .addClass('ctools-modal-imgsearch-modal-style');

        Drupal.behaviors.ZZCToolsModal.attach(context);
    }
  }
})(jQuery);

```

**Note**: since all the code inside `Drupal.behaviors.addCtoolsModalClass` is wrapped with `jQuery.fn.once`, which means every code inside is only be implemented once if the selector finds the element. So you don't need to worry about binding the same event twice.

---
Tags: 7, forms, javascript, ajax, chaos-tool-suite
---


# Question
Title: how can I manipulate functionality or the structure of an existing form?
How can I manipulate functionality or the element's structure of an existing form in a different way and create my own template?

For example, I can use below code to display a user login form page, but this code doesn't have any flexibility and doesn't allow me to edit or customize each part of this form element separately and I can't change the look and order of this form straightforwardly.
Imagine that I want to add show password checkbox and other visual effect and style to that's form element.

**Page--user.html.twig**

```
{{ page.content }}

```

# Answer
You should separate functional and visual changes.

All the functional changes should done by hook\_form\_alter and the rest with preprocess functions (if needed) but rather with twig.

If you use devel module, you can use the kint() function in twig, so you will see you can also filter page.content. But if that's not enough you can make an own template to this particular form, you will need twig debug enabled, which will show you HOW TO change a part of the dom (once again preprocess function and template naming convention suggestions).
> 0 votes

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


# Question
Title: How can create a template for user login form?
how can I create twig template for user login form page: **/user/login**
Is there any Twig Template naming suggestion for that?
thank's for any help.

# Answer
> 4 votes
Use `page--user--login.html.twig` for targeting `user/login` page.

You can also enable Twig debugging to see naming suggestions for different page components.

> The markup of each Twig template is surrounded by HTML comments that contain theming information, such as template file name suggestions.

# Answer
> 0 votes
You can use below twig template naming suggestions:

* page--user.html.twig
* page--user--login.html.twig
* page--user--password.html.twig

I suggest you to use `page--user.html.twig`, for all of this pages.

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


# Question
Title: Aggregating but not taking the first result
I have a set of profiles, and some users have two of the same type.

Well one of the views gets around these duplicate profiles by aggregating them. The problem is that it grabs the first of the two duplicates.

Provided that programmatically removing the extra member profiles isn't really feasible, is there a way to grab the second of the two duplicates?

A sample of the query is here:

```
select DISTINCT p.pid, p.type, p.uid, u.name from profile as p
join users as u on (u.uid = p.uid)
where p.type = "member"
group by u.uid
order by p.uid, p.pid DESC

```

# Answer
> 1 votes
You can use the Views Field View module, like so:

1. Create a view "user profile" master (not page)

* use contextual filter user UID
    * In the pager: Display a specified number of items : 1 item and set offset to 1
2. Create the main view

* add global field view
    * use user uid as a contextual filter

**The problem with this is that if user have only one profile then you may encounter a problem** but maybe you can change it for more detail on how to create view inside view check Drupal Views Inside Other Views.

---
Tags: views
---


# Question
Title: Adding Boolean or Tag to Image File Field
I am using File Entity and have added a boolean to the image file field. This checkbox is to check when I want to make a favourite photo.

My problem is, I'm not seeing this on the node creation page, I upload the image(s) and I just still have alt and title fields available and no boolean.

I have gone through manage form display, manage display and I can see it there for Default and Thumbnail view modes.

What step am I missing?

Drupal 8

# Answer
> 0 votes
The module File Entity has it's own field widget "Editable file".

You have to change the image field to use this widget in manage form display of the content type.

Then add a new image in the node creation page and a button will appear to edit the custom fields inline.

The widget has no preview image. So you have to choose, if you want inline fields or preview images.

The File Entity module is a basic solution with a very simple user interface.

A complete media solution for D8 will be provided by the Drupal Media Initiative, here are the latest news:

http://janezurevc.name/releases-of-various-drupal-8-media-modules

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


title: How to make users default in searches?

text:
# Question
Title: How to make users default in searches?
When a user tries to search for another user, the search returns no result, however, when it searches for a node e.g article, questions etc it returns a matching value immediately with search autocomplete. What is wrong?

Permissions are ok and user is set as default in settings. I want users to be able to search users, nodes, location or whatever available and matches their query.

# Answer
In order to allow non-admin users to search for other users on your site, you'll need to give the appropriate user role (typically "authenticated users") permissions to "view user profiles" and "use advanced search". To access User search, you can utilize the "Advanced search" link in the Search block, or use the URL `/search/user`

Note, these permissions will also allow users to see other users' profile pages, so make sure this is acceptable for your use case.

If you need to search both nodes and users from the same text box, you'll need more than Drupal's Core search functionality to do so. See How to search both Users and Nodes simultaneously in drupal 7 for some suggestions.
> 1 votes

---
Tags: 7, users, search
---


# Question
Title: Drupal 8.0 to 8.1.8 upgradation is not working
When i tried to update drupal to latest version (**8.1.8**) am getting the following error

But in the **`status report`** page it shows as upgraded to **8.1.8**

Any idea how to resolve this ??

# Answer
> 0 votes
The message is a notice not a error so updating of core just went on. So you core is now on the latest version.

You should however solve the error.

---
Tags: 8, upgrading
---


# Question
Title: Rewrite a Views Field to get rid of accents. I need roman alphabet characters for a csv export
I'm using Views Data Export to generate CSV files for end-users to use and then re-upload using Feeds. I need Vietnamese characters like `â ỏ ể` to be converted to `a o e` before export as these are in users' names.

I tried `utf8_decode` in Views Data Export settings but it doesn't work for all characters and even then, changing Feeds to use `ISO-8859-1` still results in a "This isn't a UTF-8 file" error.

It seems that changing a setting in Excel can fix this but that isn't an option for me for usability reasons. I'm not the one who will be using these CSV files so I need these names to be exported properly.

# Answer
> 2 votes
Setting "Character encoding conversion" in the data export view's CSV file settings to:

`ISO-8859-1//TRANSLIT`

should accomplish what you're attempting. That will convert the names to the ISO-8859-1 character set, with transliteration of characters not included in the set to something that appears similar.

---
Tags: 7, feeds, importing-exporting
---


# Question
Title: Admin permissions wiped out after git branching
I've encountered a strange issue whereby creating a new git branch on a Drupal 7 site and switching to it causes admin users' permissions to seemingly disappear. After performing the git branch, all admin users (who normally have near full access) see the admin toolbar but only have the ability to add content. All other links are missing.

I have tried visiting admin pages directly and that yields access denied. I have tried rebuilding permissions and clearing cache as well. Has anyone encountered this?

# Answer
> 0 votes
I was able to determine that rows strangely went missing from the `roles` table (in particular admin roles) upon creating a new git branch. I have not tracked down *why* this happens, but I suspect that something in either one of the features or custom modules is causing this to happen.

---
Tags: users, version-control
---


# Question
Title: Why I can't I drop field_data and field_revision table in phpmyadmin?
I wanted to delete a filed named `MyField`.

So I first deleted the corresponding record for `MyField` in `field_config` table and `field_config_instance` table.

And now I'm trying to drop these tables by using phpmyadmin.

```
field_data_field_MyField
field_revision_field_MyField

```

But even if I drop them they are still there. It seems that they can't be droped.

Isn't it possible to delete fields directly in DB?

# Answer
@hampercm explained why directly deleting records and tables from database is not recommended. It is so true that everyone is encouraged to use admin UI or Drupal API to remove the fields and field instances.

But, I guess you know what the best practise is and wanna do that by SQL query with some reason (e.g. company policy. YES, I faced this stupid requirement before)

You are on the right track. Drupal save field and field instances config in `field_config` and `field_config_instance`. **BUT, Drupal also cache these data in `cache` table**.

So, you need to truncate the `cache` table.
> 3 votes

# Answer
Attempting to deleting fields by dropping the database tables is not recommended. It's likely Drupal is recreating those tables when it discovers they're missing; that's why you can't seem to delete them.

The recommended way of deleting fields in Drupal is to remove them from **all** Content Types that use them using the Fields UI (the "manage fields" links from `admin/structure/types`). Then, Drupal will automatically clean up the DB tables during a future Cron run.

Note: this answer assumes you added the fields manually to one or more Content Types. If you instead did so by defining a Content Type programmatically (i.e. you created a custom module to define it), different steps will be needed.
> 2 votes

---
Tags: 7, database, entities
---


title: Installing Drush 8 in ubuntu 16.04

text:
# Question
Title: Installing Drush 8 in ubuntu 16.04
I am having problems installing drush 8 in ubuntu 16.04. when i insert the following command in the terminal

```
composer global require drush/drush:dev-master

```

i get the following error

I have also tried the documentation from drush.org

```
php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush

```

but i get the following error msg

> bash: drush: Is a directory

I am currently stuck.

# Answer
`drush/drush:dev-master` is not Drush 8, it is Drush 9. To install Drush 8, try `composer global require drush/drush`, or better yet, use cgr.

For notes on installing Drush 9 via Composer, please see drush dev-master requires codegyre-robo.
> 1 votes

# Answer
You have to use `sudo`.

```
sudo composer global require drush/drush:dev-master

```

The composer is to install the drush at `/usr/local/share` which folder's owner is `root`. In Ubuntu, `sudo` is a must for granting the `root` privilege.

And, as what @greg\_1\_anderson said, `dev-master` is the branch for Drush 9, if you want Drush 8. Please use.

```
sudo composer global require drush/drush:8.x

```
> 1 votes

---
Tags: drush
---


# Question
Title: How to change permission for dynamic routes?
I am able to change permission callback perfectly for static urls: eg: Works fine:

```
if ($route = $collection->get('entity.taxonomy_vocabulary.collection')) {
  foreach ($vocabularies as $vocabulary) {
    $perms['administer ' . $vocabulary->id() . ' vocabulary terms'] = array(
      'title' => t('Administer %name vocabulary terms', array('%name' => $vocabulary->label())),
    );
    $route->setRequirement('_permission', 'administer ' . $vocabulary->id() . ' vocabulary terms');
  }
}

```

But same logic does not work for dynamic routes i.e route having a variable say taxonomy machine name.

Does not work:

```
if ($route = $collection->get('entity.taxonomy_term.add_form')) {
        foreach ($vocabularies as $vocabulary) {
            if($taxonomy_vocabulary == $vocabulary->id) {
                $route->setRequirement('_permission', 'administer ' . $vocabulary->id() . ' vocabulary terms');
            }
        }
      }

```

Please suggest how to alter/change permission callback for taxonomy add/view etc routes.

# Answer
> 4 votes
The `_permission` route setting isn't a callback function like the access callback in Drupal 7; it defines one or more permissions that are checked before granting access to the route. There's nothing dynamic about the setting. Adding one (or more) 'administer *taxonomy\_id* vocabulary terms' permissions will restrict access if the user doesn't have those one or more permissions.

If you need to define a dynamic access check, you'll need to utilize `_custom_access` and define your own callback function that takes into account a specific permission check based on the context (see *Structure of routes* for more information).

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


# Question
Title: How to change front page template based on url alias?
I have many homepages and template file for every homepage and also a custom template for the front page the problem is when I change the default front page in admin/config/system/site-information to any other alias the page still have the page--front.tpl.php styles not the custom node style page--node--68.tpl.php , any help please ?

# Answer
In Drupal 7, template suggestions are added/modified in the preprocess function, in this case `HOOK_preprocess_page()`.

Add this to the template.php file in your theme root directory; you may need to create this file.

The problem is that the page--node--id suggestion is *weaker* than page--front and does not get used. We need to move the page--node--id suggestion to the end of the `theme_hook_suggestions` array, so it overrides page--front.

Add this snippet. I have added comments to explain what each line of code does. Replace *ThemeName* with your theme name.

```
/**
 * Override or insert variables into the page template.
 */
function ThemeName_preprocess_page(&$variables) {

  // Check if this is the front page and a node is the front page.
  if ($variables['is_front'] == TRUE && isset($variables['node'])) {

    // Foreach over the theme_hook_suggestions array.
    foreach ($variables['theme_hook_suggestions'] as $key => $value) {

      // Does the suggestion match the current node?
      if ($value == 'page__node__' . $variables['node']->nid) {

        // Match, unset the template suggestion.
        unset($variables['theme_hook_suggestions'][$key]);

        // Push the template suggestion onto the end of the array, this will give
        // it precedence over page--front.
        $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->nid;
      }
    }
  }
}

```

I think this is the easiest/quickest way to *move* an array item to the end, where it will override page--front.
> 4 votes

# Answer
Hope this work on you this will allow you define/add your custom tpl base on url alias,

Example: you have url alias /sample then your custom tpl should be page--sample.tpl.php if you dump the variables variable in theme\_preprocess\_page you will notice that there's a new tpl suggested in theme\_hook\_suggestions 'page\__sample' you jus need to create a new tpl in templates directory name it page--sample.tpl.php

```
/**
 * Implements template_preprocess_page().
 */
function exmaple_preprocess_page(&$variables) {
  if (module_exists('path')) {
    $url_alias = drupal_get_path_alias(str_replace('/edit', '', $_GET['q']));
    foreach(explode('/', $url_alias) as $path_part) {
      $template = 'page__' . $path_part;
      $variables['theme_hook_suggestions'][] = $template;
    }
  }
}

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Group by taxonomy term, show node multiple times for every reference
I have a Content-Type called `client` and a Taxonomy term called `Service`. Inside the view I am showing content of type: node and grouping the nodes by the taxonomy reference field. Right now it is shown like this.

```
**Term Name1**
 node1
 node2

**Term Name2**
 node3
 node4

```

The problem is the term reference field is allowing multiple and I want to show the node referenced by more than one Term, under each term instead of views creating a new term grouping.

So say I reference node3 with `Term Name2` as well as `Term Name1` I get the following results:

```
**Term Name1**
 node1
 node2

**Term Name2**
 node4

**Term Name1, Term Name2**
 node3

```

How can I avoid this functionality and have the view show this instead?

```
**Term Name1**
 node1
 node2
 node3

**Term Name2**
 node3
 node4

```

# Answer
> 6 votes
In the taxonomy term's settings, you need to uncheck the option for displaying the values in the same row.

# Answer
> 1 votes
Create a new view of content, show fields.

Under Advaced, relationship, add `taxonomy terms on node` and checkmark your tax term name and checkmark `require relationship`

In fields add field of `Taxonomy term: name` and checkmark `hide from display`

Next to Unformatted List click on `Settings` for **Grouping field Nr.1** select `(term) taxonomy term name`

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


title: How can I call the javascript plugin

text:
# Question
Title: How can I call the javascript plugin
How can I call a JAVASCRIPT plugin in Twig template?
I try to use something like this code in my `html.html.twig` template, but it seems that this not work correctly:

```
<script>
  $(document).foundation();
</script>

```

Is there any difference between html and twig?

# Answer
> 4 votes
Do it properly in a file (the plugin initialisation), add the file via a library, then load the library in the template file using twig:

```
{{ attach_library('mytheme/mylibraryname') }}

```

See https://www.drupal.org/developing/api/8/assets

---
Tags: theming, 8, plugins
---


# Question
Title: How do I create a link in the node template?
I have a *news* content type, and the node--news.html.twig template.

I have some fields, but I can not create links to node for text-field from teaser-view. How can I achieve this?

# Answer
> 9 votes
Node templates have `url` variable which you can use in your template in the following way:

```
<a href="{{ url }}">{{ label }}</a>

```

(See `node.html.twig` for an example.)

In general, you can use `link` function in twig template:

```
{{ link(item.title, item.url, { 'class':['foo', 'bar', 'baz']} ) }}

```

(See Functions - In Twig Templates for a short list of twig functions provided by Drupal. Also take a look at `TwigExtension` for their source.)

---
Tags: theming
---


title: Display Suite node field in layouts

text:
# Question
Title: Display Suite node field in layouts
Well it might be a simple solution but I don't get it.

I have a field in my content type "field\_color". I can get the value of that field in my page.html.twig with {{ node.field\_color.value }}

It works really good.

With Display Suite I created several layouts, but how to I access the field value within the layout.

I already tried:

```
{{ node.field_color.value }}
{{ ds_content.field_color.value }}
{{ ds_content.field_ }}
{{ ds_content.0 }}
{{ ds_content.1 }}
{{ ds_content.3 }}

```

nothing works.

Drupal 8, DS 2.5 stables

In my layouts.yml

```
sw_default_text:
  label: 'Text 1col Collapse'
  category: 'my cat'
  class: '\Drupal\ds\Plugin\DsLayout'
  template: layouts/sw_default_text/sw-default-text
  regions:
    middle:
      label: Content

```

My sw-default-text.html.twig:

```
{#
/**
 * @file
 * Template for a 1 column layout.
 *
#}
<div {{ attributes.setAttribute('id', settings.css_id).addClass('row shrink', 'sw-default-text', settings.css_classes) }}>
  <div class="small-12 columns">
    {{ content.middle }}
  </div>
</div>

```

# Answer
> 1 votes
My suspicion is you are having an issue because you are trying to access this in a Display Suite template, rather than from a page template.

You can probably access it via `{{ ds_region.field_color.0 }}` in the ds-3col.html.twig file. Some notes:

1. Replace ds\_region with the name of the ds\_region you want - e.g. `middle`.
2. The `0` will mean it prints the first item in the array - if you only have one item, this should be enough
3. You will need to have the field in the region on your Manage Display page.
4. Once done, you can then print `{{ left|without('body') }}`.
5. Make sure to clear your cache

I hope this helps.

You could also try to `{{ dump }}` the variables and see what is available for you (or better still `{{ kint }}` if you have the devel module installed), that will help you drill down through the options to get the one you need.

---
Tags: theming, entities, display-suite
---


# Question
Title: Use an exposed filter in Views to list all nodes with same title
I want to use an exposed filter in my view to allow users to list all nodes with the same title.

I have tried the link below but I have to manually pass the argument via the URL to get it to work.

Views related nodes with same Title

# Answer
> 0 votes
It is possible that your other two nodes have spaces at the end of the title. Check that, and if it is not the issue - try changing your exposed filter operator to `Contains` instead of `Is equal to` and see if you get 3 nodes as the result.

---
Tags: entities, views
---


# Question
Title: I want to add a prefix to my database Drupal8 how?
I want to add a prefix to my database Drupal8 how? I change the file setting.php but it appears an error

# Answer
> 3 votes
Changing the `$databases['default']['default']['prefix']` setting does not change your database. You'll have to either manually prefix your existing DB tables or run the installer again while placing the **d8\_** prefix in the **Advanced Options \> Table name prefix** field of the D8 installer.

---
Tags: 8, database, configuration
---


# Question
Title: Creating multiple custom blocks in drupal 8
```
├── hello_world
│   ├── hello_world.info.yml
│   ├── hello_world.module
│   ├── hello_world.routing.yml
│   └── src
│        ├── Controller
│        │   └── HelloController.php
│        └── Plugin
│             └── Block
│                  └── HelloA.php
│                  └── HelloB.php

```

I have used the above file structure to create blocks in Drupal 8. Both the blocks, HelloA as well as HelloB works, but only one at a time. I see block HelloA, if I remove HelloB.php and see Block HelloB when HelloA.php is deleted. I am trying to create multiple blocks. Please guide me. Thank you very much.

# Answer
Thank you very much Shawn.

It was the `@Block` annotation. I was using same id for both the blocks.

```
/**
  * @Block(
  *   id = "show_state",
  *   admin_label = @Translation("Show State"),
  *   category = @Translation("POP")
  * )
  */

```
> 2 votes

---
Tags: 8
---


title: Contextual links for a custom module

text:
# Question
Title: Contextual links for a custom module
I want to add in a contextual link to a block.

The block shows up in different pages, not just a specific page.

Here is my current setup

```
$block['content'] =array(
    '#markup' => _get_markup(),
    '#attached' => array(
        'css' => array(
            drupal_get_path('module', 'module_name') . '/css/main.css',
        ),
        'js' => array(
            drupal_get_path('module', 'module_name') . '/js/main.js'
        ),
    ),
    '#contextual_links' => array(
        'add content' => array('add/content/', array('content')),
    ),
);

```

Based on the documentation, this should work for drupal 7 but it does not for me.

# Answer
> 0 votes
Here is the solution that I ended up using. By no means, this is the definite answer to my question. Although the code below accomplishes what is being asked I would *HIGHLY* discourage anyone from using it unless you have to.

```
function hook_preprocess_links(&$variables) {
    if($variables['links']['block-configure']['href'] === 'admin/structure/block/manage/BLOCKNAME/configure'){
        $variables['links']['custom_name'] = array(
            'title' => 'TITLE',
            'href' => 'path/to/node'
        );
    }
}

```

# Answer
> 0 votes
To be able to add your custom contextual link, you first need to check the Contextual links module is enabled. Even though you define everything correctly, it would not show, if it is disabled. Also, you need to set context to MENU\_CONTEXT\_INLINE in your menu items.

```
/**
 * Implements hook_block_view().
 */
function example_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_custom_block':
      $block['subject'] = t('Example Block');
      $block['content'] = array(
      '#markup' => _get_markup(),
      '#contextual_links' => array(
          'add content' => array('add', array('node')),
      ));
      break;
    default:
      break;
  }

  return $block;
}

/**
 * Implements hook_menu().
 */
function example_menu() {
    $items['add/%/content'] = array(
        'title' => 'Add Content',
        'type' => MENU_LOCAL_ACTION,
        'context' => MENU_CONTEXT_INLINE,
        'page callback' => 'contextual_node_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );

    // To use local task menu items, there must be a parent page.
    $items['add'] = array(
        'title' => 'Contextual Link Page',
        'page callback' => 'contextual_node_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

```

### Additional resources

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


# Question
Title: Whats the proper way to preprocess field collection items to add first and last class names?
How to add `'first'` and `'last'` class names in addtion to `'odd'`/ `'even'` for field collection items in preprocess functions?

# Answer
> 22 votes
You would normally do this in MYTHEME\_preprocess\_field\_collection\_item(), but field collection items don't have their own preprocess. Fortunately, they're entities, so you can use entity preprocess to create your own field collection preprocess function:

```
/**
 * Implements template_preprocess_entity().
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = 'MYTHEME_preprocess_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Field Collection-specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_field_collection_item(&$variables) {
  $variables['classes_array'][] = 'your-class-here';
  // Plus whatever other preprocessing you want to do.
}

```

# Answer
> 2 votes
In **Drupal 8** the preprocess function exists without having to add one:

```
/**
 * Implements hook_preprocess_field_collection_item().
 */
function mymodule_preprocess_field_collection_item(array &$vars, $hook) {
  //dpm($vars);
}

```

---
Tags: theming, entities
---


# Question
Title: I need to prevent the translation of admin + toobar interface
Hello I am using Internationalization module. I want to keep the admin and the toolbar in English despite the language variable, despite the node translation operation. Is it possible?

# Answer
> 4 votes
You can use the Administration Language module:

> This module lets the administrator see all administration pages in her preferred language.
>
> You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).
>
> You can use the standard Languages page to choose the language of the admin pages.

# Answer
> 0 votes
Hi I have been doing alot of research to change the admin menu language to English this was what worked for me

First install the module "Admin Languages" https://www.drupal.org/project/admin\_language

Second go to \[site-domain\]/admin/config/regional/language/admin\_language and make sure you select the radio button 'Use administration language on every page except the listed pages' and make sure nothing is added in the below text box that would stop the user interface getting translated in the entire site

\*when you configure it like this the default language is what will apply all over you can change that too by going here \[site-domain\]/admin/config/regional/language

---
Tags: i18n-l10n
---


# Question
Title: How to check in Rules the value of a field collection field contained in a user account?
I want to give a specific user a price override on specific products. In doing so, I added field collection on the people account setting. This field collection has to two fields: product sku and price.

I also created a rule with this codes:

```
{ "rules_price_override" : {
"LABEL" : "price override",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
"ON" : { "commerce_product_calculate_sell_price" : [] },
"IF" : [
  { "user_has_role" : {
      "account" : [ "site:current-user" ],
      "roles" : { "value" : { "2" : "2" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
  { "entity_has_field" : {
      "entity" : [ "site:current-user:field-price-override:0" ],
      "field" : "field_product_sku"
    }
  },
  { "data_is" : {
      "data" : [ "site:current-user:field-price-override:0:field-product-sku" ],
      "value" : [ "commerce-line-item:commerce-product:sku" ]
    }
  }
],
"DO" : [
  { "commerce_line_item_unit_price_amount" : {
      "commerce_line_item" : [ "commerce_line_item" ],
      "amount" : [ "site:current-user:field-price-override:0:field-regular-price:amount" ],
      "component_name" : "base_price",
      "round_mode" : "1"
    }
  }
]
}
}

```

But it only good for the first field collection value.

What will be the best way to make it loop, so that it can change its index as site:current-user:field-price-override:0 - end

# Answer
I'm about sure that the machine name of your field collection field is `site:current-user:field-price-override` (your question doesn't state that explicitly), for which you do not have a "Entity has field" Rules Condition yet (you have `site:current-user:field-price-override:0` instead).

Try adding a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field. Not sure why you have/need that `site:current-user:field-price-override:0` Rules Condition, but you might not need that anymore.

You can then add a Rules Action which is simply a Rules "loop", and which iterates over each of the field collection items. And you will be able to use any of the typical tokens (in the replacement patterns).

For way more details about this, refer to "How to iterate over all field collection items in an eMail body using Rules?" (which also includes a rule in export format you may want to experiment with, if you only adapt some machine names of the used fields).
> 0 votes

---
Tags: 7, rules, entities
---


title: Drupal Database or MySQL Databse

text:
# Question
Title: Drupal Database or MySQL Databse
I want to create a dynamic website. Where does Drupal store its data? Is a MySQL database required to store the data? If Drupal has its own database, does it have any limitation? I am pretty new to Drupal.

Any help would be appreciated.

# Answer
As of Drupal 7, MySQL, PostgreSQL, and SQLite data types are supported in Drupal core.

Any web hosting company will offer at least one database server.

Basically:

1. you will copy the drupal files to your server via an FTP client
2. you will create a database from your web hosting company admin panel
3. you will go to www.yourwebsite.com/install.php and while installing Drupal you will provide the database credentials
4. done

You can find more info about creating your database here:

https://www.drupal.org/docs/7/installing-drupal-7/step-2-create-the-database
> 0 votes

---
Tags: database
---


# Question
Title: How can I show/hide a block on specific taxonomy URLs depending on term depth?
I need to show blocks on different url's.

```
Block1
Should be displayed on:
branches/taxonomytermlevel1
But not on
branches/taxonomytermlevel1/taxonomytermlevel2

Block2
Should be displayed on
branches/taxonomytermlevel1/taxonomytermlevel2
But not on
branches/taxonomytermlevel1

```

The terms /taxonomytermlevel1/taxonomytermlevel2 are variables (elements in some taxonomy list)

What is the most easiest way to do this? I think a php script in the block display visibility setting would be the trick and so I tried some code there but I did not succeed.

Some code I have now is e.g.:

```
<?php
if (empty(arg(3))) {
  return TRUE;
}else {
  return FALSE;
}
?>

```

Any suggestions?

# Answer
> 0 votes
There is another way to answer your question, ***without PHP in the block settings***: you can use the Rules block visibility module for this. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.
>
> Need to show a block only for users registered more than a month ago?
>
> Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
>
> What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***" (so that the appropriate menu block is shown on the appropriate pages).

For an illustration of how to use this module, refer to my answer to "How to show blocks by url, when nodes have multiple paths?". It includes some Rules Components (in Rules export format), which you should replace by the your variations to make it match your specific question.

So with 2 (similar) rules, 1 for each of both blocks, you should be able to get this to work.

To actually "*determine the path structure in rules*" (as in your extra comment below this answer), you might want to use a Rules Condition using a regular expression. Similar to the Rules Condition in the rule I included in my answer to "How to automatically skip intermediate redirects?".

Using regular expressions opens up many more situations (on top of the Rules block visibility module) where this solution can work. If you're not familiar with Regular Expressions (not obvious ...), then maybe you also want to look at my answer to "How to suppress a core Drupal warning or error message set with drupal\_set\_message for site users?".

### Bonus:

This approach ***does NOT require the PHP filter to be enabled*** either (which you should try to avoid whenever possible) ...

# Answer
> 0 votes
Arguments are not URL parts. In your case arg(3) will always be empty, because the internal Drupal path for taxonomy terms will be `taxonomy/term/[tid]`, for any term level.

## Solution #1. Based on taxonomy terms.

Your PHP code should get all the parents and calculate the amount of them.

For Block #1

```
if (arg(0) == 'taxonomy' && arg(1) == 'term' && !empty(arg(2))) {
  $tid = intval(arg(2));
  $parents = taxonomy_get_parents_all($tid);
  return (count($parents) == 1);
}

```

For Block #2

```
if (arg(0) == 'taxonomy' && arg(1) == 'term' && !empty(arg(2))) {
  $tid = intval(arg(2));
  $parents = taxonomy_get_parents_all($tid);
  return (count($parents) == 2);
}

```

The reason why we use count($parents) as 1 and 2 is that the function `taxonomy_get_parents_all()` returns all the parents and the term itself. So for the A-B-C-D hierarchy you will be given:

```
array(
  0 => D (term object),
  1 => C (term object),
  2 => B (term object),
  3 => A (term object)
);

```

Also this would only work if your terms have only 1 parent. In working with a taxonomy in which a term can have multiple parents, you will have to gather all the instances where the count is 1 and return an array of those terms.

## Solution #2. Based on the URLs.

Only if all your terms have aliases and all the aliases follow the hierarchy level. I.e. for your example both URLS are correct `branches/taxonomytermlevel` and `branches/taxonomytermlevel1/taxonomytermlevel2`.

For Block #1

```
$path = drupal_lookup_path('alias', current_path());
$exploded_path = explode($path);
$path_count = count($exploded_path);
return (count($path_count) == 2);

```

For Block #2

```
$path = drupal_lookup_path('alias', current_path());
$exploded_path = explode($path);
$path_count = count($exploded_path);
return (count($path_count) == 2);

```

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


# Question
Title: How to notify users from within a module
I'm building a custom module for a project and would like to display a notification/warning to the user once something happens. For instance, my module would trigger a Mailchimp action. Once I get the Ok from Mailchimp, I'd like to show a message to user, something like using Devel's `dvm` or `dpm` function.

How can I accomplish this (preferably without additional modules)?

Thanks in advance.

PS: I could use Devel, but I'd rather disable it in production env.

# Answer
> 4 votes
`drupal_set_message()` is what you're looking for.

Sample usage:

```
drupal_set_message('Mailchimp action is successfully executed.');

```

---
Tags: 7
---


# Question
Title: Why bootstrap sub-theme with sass starterkit is not working?
I am trying Bootstrap 7.x-3.6 theme.

But sub-theme for some reason is not working. I did follow the same procedure as described on the Documentation page for Drupal 7.

I am describing here, what I did,

**1.** Installed fresh drupal 7.50 on localhost.
**2.** Down loaded Bootsrtap 7.x-3.6 and enabled but not make is default.
**3.** **Sub-theme:** I did copy **sass** folder from the starterkits. Paste in /theme folder and rename with `mysubtheme`. Rename the file-name `sass.starterkit` with `mysubtheme.info`. And inside that changed the `'name'`.

>

**Final image of /theme folder**

>

**4.** **Downloding Bootstrap:** Downloaded bootstrap file from here as decribed in following image. I did select `Sass` option. Pasted to `/mysubtheme` folder, rename with `bootsrtap`.*(even to check, I did try all three options one by one, but same result)*

>

**5.** Downloaded Jquery update module also and enabled, default version was 1.50.

**Now,** Till this stage the site shows content but not a basic theme formatting. Comparative image below.

>

What could be the reason or I am missing something.

# Answer
Thanks to @JeffBurnz @MarkCornoy and @FreeRadical for their inputs.

The following setting needs to be disable in mysubtheme.info(*sass.starterkit* A original file). And may be @FreeRadical want to point out same thing by asking `"Have you removed the CDN?"` in the his comment.

> ; Disable the CDN provider so compiled source files can be used.
>
> settings\[bootstrap\_cdn\] = ''

After commenting out `settings[bootstrap_cdn] = ''` it does take the base theme setting.

Any more suggestion appreciated. For now, this solution works.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Adding javascript to module and access drupalSettings without jQuery
I am trying to create a Drupal 8 version of the Mautic Drupal module. Currently I have just ported the Drupal 7 version as is, and the script for Mautic forms along with the tracking pixel is printed in a block. Mautic now uses a tracking script and I want to update the module to use it. The tracking script looks like this (notice the Mautic base url required):

## js/mautic\_drupal\_tracking\_code.js

```
(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
    w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
        m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
})(window,document,'script', + drupalSettings.mautic_drupal.mautic_drupal_tracking_code.base_url + '/mtc.js','mt');

mt('send', 'pageview');

```

The script is showing on the page, but as I am trying to avoid jQuery, I can not find out how to access the `drupalSettings` variable.

My module code is updated and not in sync with the github repo. Here are a description of the files:

## mautic\_drupal.libraries.yml

```
mautic_drupal_tracking_code:
  version: VERSION
  js:
    js/mautic_drupal_tracking_code.js: {}
  dependencies:
    - core/drupalSettings

```

## mautic\_drupal.module

```
/**
 * Implements hook_page_attachments_alter().
 *
 * @param array $page
 */
function mautic_drupal_page_attachments_alter(array &$page) {
  $config = \Drupal::service('config.factory')->get('mautic_drupal.settings');
  $mautic_url = trim($config->get('base_url'), ' \t\n\r\0\x0B/');

  if ($mautic_url != '') {
    $page['#attached']['drupalSettings']['mautic_drupal']['mautic_drupal_tracking_code']['base_url'] = $mautic_url;
    $page['#attached']['library'][] = 'mautic_drupal/mautic_drupal_tracking_code';
  }
}

```

On the site, the script is showing, and the base url setting is set. But alas, I can not access the settings in my javascript, I can only find examples of how to do that in jQuery scripts.

Is this possible to do in pure javascript?

# Answer
> 1 votes
You can try to set a weight on the js file:

```
  js:
    js/mautic_drupal_tracking_code.js: { weight: -18 }

```

There is a core issue, that the dependencies don't get the correct priority. The weight is a workaround for this:

Replace custom weights with dependencies in library declarations

If you can't get `drupalSettingsLoader.js` running in the correct order, you can for testing purpose put the code to load the json array at the top of your custom js:

```
(function () {

  'use strict';

  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  window.drupalSettings = {};

  if (settingsElement !== null) {
    window.drupalSettings = JSON.parse(settingsElement.textContent);
  }
})();

```

---
Tags: 8, javascript
---


# Question
Title: How do you include a translatable string in an update hook
In D7 you had to use get\_t() in order to include translatable strings in an update hook. Is there a similar procedure for D8?

# Answer
No. Just call t().

get\_t() was actually for early install and things like that, update functions AFAIK didn't need it (calling t() there is however often pointless, as it is highly unlikely that there is a translation for it already when you run the updates.)

t() calls a service now, and it will use the correct one depending on the situtation automatically.
> 1 votes

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


# Question
Title: How to convert objects into array using serialization API?
I'm trying to convert entity objects into array but it's not working. Can you please help me spotting the mistake. I need to use \`serializer.normalizer.content\_entity' service. The code I have written is:

```
class ComplexMergeResolver implements ConflictResolverInterface {

  protected $serializer;

  protected function setUp() {
    $this->serializer = $this->container->get('serializer.normalizer.content_entity');
  }

  /**
   * {@inheritdoc}
   */
  public function applies() {
   return TRUE;
  }

  /**
   * @param RevisionableInterface $revision1
   * @param RevisionableInterface $revision2
   * @param RevisionableInterface $revision3
   *
   * @return array
   */
  public function merge(RevisionableInterface $revision1, RevisionableInterface $revision2, RevisionableInterface $revision3) {
    $r1_array = $this->serializer->normalize($revision1, 'array');
    $r2_array = $this->serializer->normalize($revision2, 'array');
    $r3_array = $this->serializer->normalize($revision3, 'array');
    $merge = new ThreeWayMerge();
    $result = $merge->performMerge($r1_array, $r2_array, $r3_array);
    return $result;
  }
}

```

`r1_array` is returned empty, which means `normalize` method is not being called properly. Any help would do great. Thanks in advance.

# Answer
I tried `serializer.normalizer.content_entity` but got no success in normalizing the (node) revision entity, or even node entity for that matter. It always resulted in the following error:

> PHP Fatal error: Call to a member function normalize() on a non-object in core/modules/serialization/src/Normalizer/ContentEntityNormalizer.php on line 28

For this I had to enable the serialization module. I also tried with the `ContentEntityNormalizer` provided by the "hal" module from core. Result same error:

> PHP Fatal error: Call to a member function normalize() on a non-object in core/modules/hal/src/Normalizer/ContentEntityNormalizer.php on line 95

I had success with directly using the `serializer` service from the serialization module. The working code for serializing a node revision is given below. It was verified on `/devel/php`

```
$revision = node_revision_load(4);
$container = \Drupal::getContainer();
$normalizer = $container->get('serializer');
$normalized_array = $serializer->normalize($revision);
dsm($normalized_array);

```

Or combine line 2 and 3 above to get the serializer directly as

```
$serializer = \Drupal::service('serializer');

```

In your `setup()` function, you need the following change:

```
$this->serializer = $this->container->get('serializer');

```

P.S: I am still trying to figure out why `serializer.normalizer.content_entity` is not working and throwing the errors.
> 3 votes

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


# Question
Title: How to perform a redirect after completing a Quiz?
I am using Quiz module. How can we redirect user to thankyou/someother page after clicking Finish button?

# Answer
> 1 votes
# If using Quiz 7.x-5.x

Assuming you're using the 7.x-5.x-rc3 version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.

To do so, have a look at the delivered rule, which looks like so:

```
{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and replace both Rules Actions with a basic "redirect" (a typical Rules Action) that fits your needs.

# If using Quiz 7.x-4.x

For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

> ... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.
>
> Patch works for me.

---
Tags: 7, redirection, quiz
---


title: Add class to taxonomy term in view

text:
# Question
Title: Add class to taxonomy term in view
I got a view listing nodes of the content type "Job". Every node is tagged with different "Jobtypes" that are listed too. Now I want to style every taxonomy different (colors, icons, etc.) so it would be nice, every taxonomy would have his own class. At the moment I don't see a way to do this. Some ideas? Thank you!

# Answer
1. Relationship: Choose "Content: Taxonomy terms on node" & "Jobtypes"
2. Field: Add "term id"(Exclude from display) with relationship
3. Field: Add Jobtypes Field and "Rewrite the output of this field" with token

such as:

```
<div class="jobtypes-[tid]">[field_jobtypes]</div>

```

will get each term with unique css class with its term id.
> 3 votes

# Answer
It seems the Field Formatter CSS Class module is what you're looking for.

> Adds a formatter for text/list/taxonomy fields to render as CSS classes on nodes.
>
> The Field formatter CSS class module allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.
> 1 votes

# Answer
In the view add the taxonomy as a field and exclude it from display. Install views\_php module. This module adds a field to tje view such that it's value is a php code and it uses the values of the current row as well. You can simply check for the current value of the taxonomy in the php field of the view then for every value of the taxonomy term output the approprite icon.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Why doesn't my text filter strip out the tags I don't want?
I thought I understood text filters, but it appears I don't.

I am using a filter on my node's "body" field that is supposed to restrict tags. I have entered the allowed HTML tags as

`<em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <br>`

Yet in my WYSIWYG editor I can switch to source view and save text that includes (or worse, ) tags.

Why aren't these tags stripped out when the node is saved?

# Answer
> 1 votes
Okay, I've found my own answer. The problem *was* with my understanding of how text filters work. Text is saved into the database with no changes, and filters are only applied when the text is output.

When using Entity Metadata Wrappers, as I am, when you get $wrapper-\>body-\>value(), it gives you an array with several elements. One is the "value", which is the raw, unfiltered text. Another is the "safe\_value", which has had filters applied.

So in my case I needed to use the "safe\_value" when displaying the text. Makes sense once you understand it!

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


# Question
Title: Prevent users from including their username in their password
I'm aware of the Password Policy module that has a number of features for forcing the user to constrain their passwords to certain criteria, but this module does not contain an option to prevent users from including arbitrary strings in their passwords (such as their own username).

Ex. User bob receives a validation error if they try to change their password to anything that includes the string "bob", such as "889bobisthebest99".

Does anyone know how to code custom functionality to achieve this result for Drupal 7.5 or a module that already does what I'm looking for?

# Answer
> 0 votes
I found that the Password Policy module actually does have an option to prevent the user from including their username in their password. The broader issue about how to restrict arbitrary strings from a user's password still stands though.

# Answer
> 0 votes
The Password Strength module for Drupal 7 offers the closest functionality to what you desire. Full disclosure, I'm the author of the module!

In particular, it utilizes the Zxcvbn-PHP library for discovering patterns in passwords. So, for your example the Zxcvbn-PHP library would detect "bob" and "best" as simple dictionary words in the password and the Password Strength module would report that as a validation error to the user (depending on module settings). Read more about the Zxcvbn-PHP library at https://github.com/bjeavons/zxcvbn-php.

You may be able to configure or hook into the module to further accomplish your goals.

---
Tags: forms, users, hooks, security
---


# Question
Title: Best practice for moving content from production server to dev server
I have used GIT to build my Drupal 7 site (following these guidelines). In order to move changed content downstream before updating the site – in order not to overwrite new content with old content – I would like to find out what the best practice is for that. I was thinking about using the d2d migration module, but maybe there are more established and proven methods?

How do the professionals do this?

# Answer
Modifying an existing project without loosing data is a common need.

**Use Features**

One of the best practice I know, is to use the Features module to deliver all the modifications you have made on the production server. Features allow you to make custom modules containing content type structures, views definitions, and a lot more.

You'll probably also need to use the Strongarm module to be able to retrieve the settings variables of some part (modules configuration for instance).

Those modules really help to deploy modifications on a production site, even using git. You'll find easily some good tutorials about using Features.

The only important part to know is when you start using Features, it's difficult to stop using it. Because it will create and implement custom module containing all the specifications of your website (content types, fields, views, pages, ...). If you disable it / them, everything disappear.

**Export modifications**

If the modifications on your project are not to complicate (mainly content types structures and views), you can use the export / import possibilities offer by some modules (views for instance).

You can also use Bundle Copy module for the node content types export and import part.

**Hard way**

After, there is a hard way I use sometimes. It is working only if you did not change the fields settings of your existing content types, and if you just add some (fields and content types).

You can copy in your development server database the content tables of your production server. You have to well know all your content types, and specifically the fields used in them (specially the machine names of the fields).

=\> **You will lose all the new and modified nodes of your dev server**. Then do not hesitate to make a backup of your database first.

If you are in the case, you can copy from the production server all the content tables :

* node : the base node table with all the content informations
* node\_revision : if you want to get back the revisions informations
* for each one of your content type fields :
    + the data table : field\_data\_\[field\_name\] (ie : field\_data\_body)
    + the revision table : field\_revision\_\[field\_name\] (ie : field\_revision\_body)
* url\_alias : The custom path of your content (if needed)
* taxonomy tables : if you need to, but it can be tricky
* user tables : users and users\_roles (if needed)
> 1 votes

# Answer
Since D7 keeps its configuration in sql, when you sql-sync from production to dev (as described below), any configuration changes made to dev will be overwritten. (This has been fixed in Drupal 8, where configuration is stored separate from the content.)

It is sometimes recommended that one use **Features** to push database configuration changes made on dev to files outside of the sql database, which then can be file-synced to production and then re-imported into the database. Unfortunately, it is not trivial to retrofit an already existing site to use **Features** for configuration, and not all modules support **Features**. While some people report they have success with this method, I have not been able to make it work for my sites - but YMMV.

Instead, the way I do this is to keep a fairly detailed *diary* of all configuration changes and additions that I make to the dev site. *After* the sql-sync, I use this diary as a *script* and manually add these configuration changes back to dev.

Since you're running the same code base on both servers, there is no need to use **d2d migration** or any other module to migrate the sql database - standard shell tools will do.

Given that the database holding Drupal is named "`drupal7`":

I first clear all caches (to reduce the size of the dump) and then do a full dump of the "`drupal7`" DB on my production server:

```
drush cc all
mysqldump -u root -p drupal7 > productionYYMMDD.sql

```

I then move the dump file (using `scp`) from production to dev and insert the full dump on the dev server:

```
mysql -u root -p drupal7 < productionYYMMDD.sql

```

After manually adding the configuration changes (using the diary as a script), dev is now ready to be deployed.

Git isn't relevant here, as it is used for syncing code, not content.
> 0 votes

# Answer
Thanks for all your suggestions!

In case anyone else looks for an alternative solution I decided to post this answer to my own question. When the production site needs to be updated with changed theming, new functions, custom modules, new code etc, I do the following for the time being:

1. Using Putty I login at the remote production server and export all nodes from each content type using the Node Export module with Drush (\>drush ne-export --type=mycontent\_type --file=transfer/mycontent\_type.txt).
2. After exporting all nodes from each content type I use FileZilla to transfer the transfer folder with all (8) export files to the dev site.
3. On the dev site I use Drush to import all nodes of each content type. These three steps takes about 10-15 minutes with around one thousand nodes and 8 content types.
4. The production site and the dev site now has the exact same content. If needed I also transfer images from the production sites/default/files to the dev side, which makes it easier to see that everything looks identical.
5. On the dev site I now use Migrate & Backup to backup the database. On my production branch I add, commit and push my local changes to my GitHub repo.
6. Then I login at my staging site with Putty and pull my production branch from Github.
7. On the staging site I restore the database backup from step 5 with Backup & Migrate.
8. If everything looks good I put the production site in Maintenance mode and repeat step 6 and 7 there.

This way I will have a fresh copy of the live content on the dev side (and I can easily move content downstream at any time).

As for the answers provided I will certainly explore the Features module and the other possibilities suggested. Thanks again. And please let me know if you spot a flaw in my current method.

Maybe I should mention that there are only a few people that are permitted to add new content or make changes on the live site. That means that I can see to that no new content changes are made during the update procedure.
> 0 votes

---
Tags: 7, importing-exporting, migrations
---


# Question
Title: How do I show a submenu when hovering over a menu item?
I have a Drupal 7 site. I need to create menu and sub-menu. I am using the Mega Menu module for this.

This is my menu structure.

Sub-menu not showing up when hovering over a menu item.

# Answer
> 1 votes
Mega Menu module will create a Block in Blocks section(admin/structure/block).

Enable that block in a particular region and see it in action.

---
Tags: 7, navigation
---


# Question
Title: How to create an Orbit slide show based on the zurb foundation?
I stubbornly tried to create an Orbit slide show based on zurb foundation 6 framework.

I followed all the steps on the instruction page:Orbit Slide Show.

I added everything needed for this type of slide show and included below CSS and Java Script classes in theme library:

* motion-ui.css
* foundation.css
* foundation.js
* jquery.js

The template code I used is here: Orbit SlideShow Problem

But unfortunately all images display vertically below each other (one image below another) and the `Previous` / `Next` button does not work properly, see below image:

I would be happy to hear what the problem is, share your experiences and guide me to know what is the right way to load that slideshow?

# Answer
After many days searching for cause of this problem in throughout of the web resources, forums and reading variety of article, I fond that this issue for this that I don't keep the Priority of foundation Files Structure in my library, According to the Zurb Foundation documentation in this page: Installing JavaScript

> It's important that you Make sure "Foundation.js" (or Foundation.min.js) files loads after "jQuery.js" (or jquery.min.js).
> 2 votes

# Answer
As an aside, there is a module that provides this with an 8.x branch in development:

https://www.drupal.org/project/field\_orbit

As a maintainer of the 7.x branch, it works great.
> 2 votes

---
Tags: 8, javascript
---


# Question
Title: How to make a block only appear for a certain content type?
I have a content type and what I want to do is show a block on the right hand side only if the user is viewing that content type using a custom module. Any general pointers as to where I should start looking?

# Answer
This can be done in a few ways.

If your content type always has a unique URL (such as /news) you can set the block to only show when on a page matching that URL.

Or this can be managed in a variety of ways using different plugins that allow for the manipulation of displaying content types and their corresponding views/blocks.

Are you currently using any plugins like that or have any themes installed?
> 1 votes

---
Tags: blocks
---


title: Find entity id in database

text:
# Question
Title: Find entity id in database
I am currently moving a website from Drupal. The information I need to transfer is divided to many DB tables and connected through entity\_id (That is my understanding, I have no experience in Drupal).

E.g. I have 2 MySQL tables:
`users` — contains `uid`s, passwords and emails
`field_revision_field_user_profile_phone` — contains phone numbers and `entity_id`s

I believe there should be a table that matches `uid`s and `entity_id`s, that will let me build a MySQL query to join them, but I can't find it.

How do I join those tables?

# Answer
> 2 votes
In the database that contains `entity_id` (`field_revision_field_user_profile_phone` in this case) there is a column named `entity_type`. That would be a name of the table which contains both `uid` and `entity_id`.

# Answer
> 2 votes
**For the second question how to join tables:**

You can use Drupal `db_select` or `db_query` in querying the database and joining tables.

This will list all users name, mail, and password.

Example:

**Using db\_select**

```
$query = db_select('users', 'u');
$query->join('field_revision_field_user_profile_phone', 'ei', 'ei.entity_id = u.uid');
$query->fields('ei', array('field_user_profile_phone_value'));
$query->fields('u', array('name', 'mail', 'pass'));

$results = $query->execute()->fetchAll();
foreach($results as $result) {
  // ...
}

```

**Using db\_query**

```
SELECT ei.field_user_profile_phone_value AS field_account_employee_id_value,
       u.name AS name,
       u.mail AS mail,
       u.pass AS pass
FROM users u
INNER JOIN field_revision_field_user_profile_phone ei ON ei.entity_id = u.uid

```

**Additional Resources:**

Documentation of `db_select` function.

Documentation of `db_query` function

---
Tags: 7, database, entities
---


title: Ranking/polling field or webform module

text:
# Question
Title: Ranking/polling field or webform module
I am trying to find a field (ideally, for use with Entity Forms), or a webform module that allows me to poll users.

I have found several modules like "Fivestar" and others that do basic polling, but I want to be able to do relative/comparative ranking. Essentially I want to be able to give users a list of options (say A, B, C), and allow them to rank in order (1, 2, 3) by their opinions. Ideally this could be done via a draggable table.

For what it is worth, it appears to be on the roadmap for the pollfield module (https://drupal.org/project/pollfield), but that module doesn't appear to be supported.

Any suggestions or leads would be greatly appreciated.

# Answer
> 2 votes
Rather than use a field for polling, I would recommend using a polling entity created by a module specific to polls. There is a core poll module.

There are also many contributed modules, the choice would depend on your use case: Advanced Poll, Poll Improved, Poll Extras -- and Poll Blocks provide a block for every core poll.

Then add some theming to make the selections draggable. I have created front-end doodads that populate a hidden element on the page - even an entire node body - so you could register the selections that way if you cannot theme the actual poll items.

You may need to use panels/views/context or template file to add the poll to your page.

My favorite place to search for Drupal contributted modules is http://drupalmodules.com/search/node/poll

# Answer
> 0 votes
If you are open to using a webform instead of an entity form, there's a module for that! Check out https://www.drupal.org/project/webform\_draggable\_list

---
Tags: webforms, entities, polls
---


# Question
Title: How to delete old obsolete terms after node's term field has been updated?
Because the old version of the term is left in the vocabulary and not deleted or updated with the new term.

So what I mean is that vocabulary should contain only terms that exist on at least one node.

I need this because I'm using certain vocabulary on Views as exposed filter and old terms leftovers messes it up.

# Answer
> 0 votes
A better description of what you're looking for is "orphaned terms". There exists a module that addresses that use case, called Delete Orphaned Terms.

> This is a utility module for deleting "orphaned" taxonomy terms. By default, terms with zero nodes associated with them are considered orphans, though administrators can specify the number of nodes associated with a term in order for it to be considered an orphan.

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


# Question
Title: How to re position the breadcrumb on the product detail page?
I am a bit confused, I was wondering how do you re position the breadcrumb to the top of the page. Please see image example below. When I see the default layout of Drupal Commerce Kickstart, the breadcrumb is located on the top of the product. I even replaced the css with the default css and there was no changes.

# Answer
> 0 votes
I figured this issue out, I had to look into the Block configuration and adjust the region.

---
Tags: commerce
---