# Question
Title: Print module doesn't work with Panelizer module. Why?
I need to make **print pdf** module work on the panelizer node. But on page printpdf/node/nid, I see only the node title and panelizer field is not shown. How to fix it?

# Answer
The Print module uses `hook_preprocess_node` which is not used with panels\_everywhere/panelizer. In a similar issue (with panels everywhere) I used a patch `565856-panel_support_print-39.patch`.

Background discussion and the patch you can find here: https://www.drupal.org/node/565856

Hope this will help.
> 0 votes

---
Tags: panels
---


# Question
Title: Group node from OG membership doesn't work
I want to create some views to display Group information on Group content pages. E.g. Display contact info from the group in a block/pane in the sidebar.

I did this before, by using the default OG Content view and add the relations.

1. I add the relationship OG membership: Group Node from OG membership, and sets its relation to (OG membership from node)
2. Set the contextual filter to provide a default value (Current OG group from context) and keep relation set to the default OG membership from Node.
3. Add fields and set their relation to Group node from OG Membership.

This isn't working though, it gives no results when viewing on Groupcontent-pages. It gives only results when viewing the Grouppage itself. I do not know why this is not working the way it should. As I recall I never had this problem before.

I used Organic Groups 7.x-2.7 with Panopoly 7.x-1.30. I have this on 2 separate installs (one on Acquia site, and one in my VM). The VM has only Panopoly and OG (and dependencys) installed as extra so it's almost vanilla.

I have enabled OG Context of course.

How can I solve this? Without these views it's a pain for the user to see in which groupcontext they are browsing.

EDIT: I installed a vanilla drupal (Not Panopoly). Installed OG + dependencys. Then I created an empty view and added the following: 1. Relationship: OG membership: OG membership from Node group (required) 2. Contextual: (OG membership from node group) OG membership: Og membership ID and Current OG group from context

This works! However, this doesn't work in Panopoly... Is this the new way to work with OG and Groupinfo on groupcontent pages?

The SQL-querys views does are exactly the same. Though on Panopoly there are no results. On Vanilla Drupal there is. How can I debug this?

# Answer
Solved it. The panel needed the relationship. This can be added on the contexts-page of the panel. The relation I added was: Node from Node (on Node: Groups audience \[og\_group\_ref\])

When this is added it can be chosen instead of "This node" when Views panes are added to a page-layout.

This works with the default OG Content-view with the relation OG membership: Group Node from OG membership added to it. (on groups without content this gives No content in this group however.)
> 0 votes

---
Tags: views, organic-groups
---


# Question
Title: PDOException on Article page : Base table or view not found
In my Drupal site, when I tried to save an article page I'm getting the following error:

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'novitawe\_icpasld.field\_revision\_field\_tags' doesn't exist: DELETE FROM {field\_revision\_field\_tags} WHERE (entity\_type = :db\_condition\_placeholder\_0) AND (entity\_id = :db\_condition\_placeholder\_1) AND (revision\_id = :db\_condition\_placeholder\_2) AND (language IN (:db\_condition\_placeholder\_3)) ; Array ( \[:db\_condition\_placeholder\_0\] =\> node \[:db\_condition\_placeholder\_1\] =\> 138 \[:db\_condition\_placeholder\_2\] =\> 138 \[:db\_condition\_placeholder\_3\] =\> und ) in field\_sql\_storage\_field\_storage\_write() (line 382 of /home7/novitawe/public\_html/icpasld/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module)

Could anyone please let me know how can I solve this issue without affecting any of my DB because this site is live. .

# Answer
As per @Triskelion comment:

When you created the 'tags' field, two tables (`field_data_field_tags` and `field_revision_field_tags`) were created to hold the information. If the first table is present but the second is not, use a statement like `CREATE TABLE field_revision_field_tags AS SELECT * FROM field_data_field_tags;` to replace the missing table. If both are missing, then you should restore your database from your latest backup.

If the error is showing, the field has already been created and the database is corrupt. If he tries to recreate the field before trying to recover, he might lose all existing information. Better to begin with the restoration attempt, then move to more drastic measures if restoration is not possible.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Saving custom field value leads to mysql error
I created a custom field as in field\_example described, using **text\_format** as type and it shows up a multi line editor without any problems.

But I'm facing a mysql error when trying to save a node:

> messagePDOException: SQLSTATE\[21S01\]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {field\_data\_field\_test3} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_test3\_additional\_info) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6\_value, :db\_insert\_placeholder\_6\_format); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 12 \[:db\_insert\_placeholder\_2\] =\> 12 \[:db\_insert\_placeholder\_3\] =\> article \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\_value\] =\> test \[:db\_insert\_placeholder\_6\_format\] =\> filtered\_html ) in field\_sql\_storage\_field\_storage\_write() (line 451 of /var/www/demo/site/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

I have the following files: si\_media.install:

```
<?php

/**
 * Implements hook_field_schema().
 */
function si_media_field_schema($field) {
  $columns = array(
    'additional_info' => array(
      'type' => 'text',
      'not null' => FALSE
    ),
  );
  $indexes = array(
    //'additional_info' => array('additional_info'),
  );
  return array(
    'columns' => $columns,
    'indexes' => $indexes,
  );
}

```

and si\_media.module:

```
<?php
/**
 * Implements hook_field_info().
 */
function si_media_field_info() {
  return array(
    // We name our field as the associative name of the array.
    'si_media_additional_info' => array(
      'label' => t('Additional Informations'),
      'description' => t('Adds more informations to a media field.'),
      'default_widget' => 'si_media_text',
      'default_formatter' => 'si_media_simple_text',
    ),
  );
}

/**
 * Implements hook_field_validate().
 */
function si_media_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if (!empty($item['additional_info'])) {
      /*if (! preg_match('@^#[0-9a-f]{6}$@', $item['additional_info'])) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'si_media_invalid',
          'message' => t('Color must be in the HTML format #abcdef.'),
        );
      }*/
    }
  }
}

/**
 * Implements hook_field_is_empty().
 */
function si_media_field_is_empty($item, $field) {
  return empty($item['additional_info']);
}

/**
 * Implements hook_field_formatter_info().
 */
function si_media_field_formatter_info() {
  return array(
    // This formatter just displays the hex value in the color indicated.
    'si_media_simple_text' => array(
      'label' => t('Default output'),
      'field types' => array('si_media_additional_info'),
    ),
  );
}

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

  switch ($display['type']) {
    // This formatter simply outputs the field as text and with a color.
    case 'si_media_simple_text':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          // We create a render array to produce the desired markup,
          // "<p style="color: #hexcolor">The color code ... #hexcolor</p>".
          // See theme_html_tag().
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#attributes' => array(
            'style' => 'color: ' . $item['additional_info'],
          ),
          '#value' => t('The color code in this field is @code', array('@code' => $item['additional_info'])),
        );
      }
      break;
  }

  return $element;
}

/**
 * Implements hook_field_widget_info().
 */
function si_media_field_widget_info() {
  return array(
    'si_media_text' => array(
      'label' => t('Text area (multiple rows)'),
      'field types' => array('si_media_additional_info'),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function si_media_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['additional_info']) ? $items[$delta]['additional_info'] : '';

  $widget = $element;
  $widget['#delta'] = $delta;

  switch ($instance['widget']['type']) {
    case 'si_media_text':
      $widget += array(
        '#type' => 'text_format',
        '#default_value' => $value,
      );
      break;
  }

  $element['additional_info'] = $widget;
  return $element;
}

/**
 * Implements hook_field_widget_error().
 */
function si_media_field_widget_error($element, $error, $form, &$form_state) {
  switch ($error['error']) {
    case 'si_media_invalid':
      form_error($element, $error['message']);
      break;
  }
}

```

I don't get it, why there is this error coming.

# Answer
> 1 votes
The error message tells you that there is a mismatch between the insert value list (7 items) and the number of values you're trying to insert (8 items).

The error message comes from a core module, that somehow is fed garbage. I am unable to see from the code snippets posted where this garbage actually comes from.

# Answer
> 0 votes
The error usually happens when you're trying to pass array for the field value when Drupal expects the string (as per `'type' => 'text'`).

So I would check if the `$value`:

```
'#default_value' => $value,

```

is really in string format (as per `$items[$delta]['additional_info']` assignment) or you need to specify exact element further down in the array.

Related:

---
Tags: 7, entities
---


# Question
Title: How to include the AddThis sharing buttons on the home page of a site?
I'm using the AddThis module to expose sharing features for nodes to users.

Is there a way to include these buttons on the ***home page*** of a Drupal 7 site?

For nodes it's easy enough to add this as a field for each content type and have it show for each content type-based node. But I'm unsure how to add this for the home page.

# Answer
> 1 votes
Find the block that comes with the AddThis module and make it available (expose this block) only on the `<front>`.

---
Tags: 7, theming
---


# Question
Title: PDOException when populating file field programaticalily?
I'm creating a drupal commerce product programatically and trying to populate it with a file using the following code:

```
$new_product = commerce_product_new($product_type);

$new_product->created = $new_product->changed = time();

$new_product->field_pdf[LANGUAGE_NONE][0] = $extras['file'];

commerce_product_save($new_product);

```

This is the value of `$extras['file']`;

Keys: `fid`, `uri`, `filename`, `filemime`, `uid`, `status`, `timestamp`, filesize Values: `135`, `public://pdfs/test2_106.pdf`, `test2.pdf`, `application/pdf`, `0`, `1`, `1356742160`, `3908`

My problem is I get this error:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'field_pdf_display' cannot be null: INSERT INTO {field_data_field_pdf} (entity_type, entity_id, revision_id, bundle, delta, language, field_pdf_fid, field_pdf_display, field_pdf_description) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => commerce_product [:db_insert_placeholder_1] => 113 [:db_insert_placeholder_2] => 115 [:db_insert_placeholder_3] => policy [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 128 [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => ) in field_sql_storage_field_storage_write() (line 448 of /var/www/clients/client1/web10/web/modules/field/modules/field_sql_storage/field_sql_storage.module).

```

I have absolutely no idea what the problem might be. Can anyone point me in the right direction?

# Answer
A file field item is not the same thing as a file object/array. You need to set the keys as defined in `file_field_schema`, which means fid, display and description.
> 3 votes

# Answer
Try adding:

```
$extras['file']['display'] = 1;

```

before you add it to the field as @Clive suggested in the comment.
> 0 votes

---
Tags: 7, commerce
---


title: Adding JavaScript just to one node

text:
# Question
Title: Adding JavaScript just to one node
I have added `scripts[] = js/add_property.js` to my `.info` file which works perfectly.

That loads the JavaScript for every page though, so how do you do it so that it only loads for the `.tpl` that it is used in?

# Answer
> 3 votes
If you want to add the Javascript to a single node, you might also implement `hook_node_view`:

```
<?php
function my_module_node_view($node, $viewmode, $langcode)
{
  if ($node->nid == MY_NODE_ID) {
    $node->content['#attached']['js'][] = array
    (
      'type' => 'file',
      'data' => drupal_get_path('module', 'my_module') . 'js/add_property.js',
    );
  }
}
?>

```

(Solution adapted from https://www.drupal.org/node/1993228).

# Answer
> 1 votes
Within your theme's template.php, you could use theme\_preprocess\_node() to distinguish between the types of nodes you like to add your JS to. For the desired type, you can use drupal\_add\_js():

```
/**
 * Implements theme_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->bundle == 'mytype') {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/js/my-js-file.js');
  }
}

```

# Answer
> 0 votes
drupal\_add\_js

> Adds a JavaScript file, setting, or inline code to the page.

# Answer
> 0 votes
If you want to add js to a specific node JS injector works well

https://www.drupal.org/project/js\_injector

Now I'm not sure how to set it to work on different templates....

---
Tags: javascript
---


title: How can I render UTF-8 characters?

text:
# Question
Title: How can I render UTF-8 characters?
In nodes, the *'* character is rendered like . Instead of Poland characters, a question mark is shown. In breadcrumbs, *'* is rendered as '.

I tried the following code, but nothing works.

```
<?php print stripslashes(render($content));?>

```

```
<?php print html_entity_decode($term->description, ENT_QUOTES, 'UTF-8');?>

```

How can I make my page work with all special characters?

# Answer
There are several possible reasons for that behavior. The most likely one is that your database encoding does not support these characters.

You should use a UTF8 encoding as standard character set (collation).
> 0 votes

---
Tags: nodes, breadcrumbs
---


# Question
Title: Passing Promo Code to Drupal Commerce via URL
I'm using Drupal 7 and Drupal Commerce Module. I'd like to be able to provide customized links with promo codes in them (promo codes would be a key/value pair in a format like www.url.com/?promo=specialK or some such thing). So Group A, for example, would get their link and click on it and it would bring them to our Registration/Product page form.

This would be the same form for every group with different discounts applied to the product price depending on the promo code attached to the URL.

If the promo is expired I'd like Drupal to just give the user a page that says something like 'Your promo is expired. Sorry. blah blah blah.' However, if the promo is NOT expired it would just apply the discount to the price and let them fill out the rest of the form and submit their payment information, etc \> the normal drupal commerce procedure with the discount applied.

I'm thinking of approaching this with Drupal Coupon module to enable the discounting functionality, but I don't know if it's possible to use a URL to pass that promo code automatically to Commerce. Does anyone know?

# Answer
> 3 votes
There are a number of ways you could do this. Probably the best way is to use a custom module, define a menu path with a token, and do it all in PHP. But I live mostly in the GUI world. You could also do this using Rules.

I have done something similar in a 10 minute youtube video that describes how to use rules to construct a url that passes in information and does things (like adding a product to a cart, or in your case you could use it to add a discount/apply a coupon).

Video: Using Rules to create a url to add a product to cart

**Step by Step**

1. Download Rules URL Arguments
2. Create a rule that fires on the event "Drupal is initializing"
3. Add a "Text Comparison" condition. Compare the `site:current-page:path` token against your first parameter "promo" for a url like "test.com/promo?coupon=123"
4. Add all of the actions you need to react to the rest of the parameters. In the video you'll see how to get at those parameters in the url.

---
Tags: commerce
---


title: Drush-error when using field-create

text:
# Question
Title: Drush-error when using field-create
Trying to make a field with Drush, i get the following error

First, the version

```
root@homer:/usr/share/nginx/html/8/sites/default# drush version
 Drush Version   :  8.0.1

```

Try to make a field 'voorvoegsel' (dutch) with field-create in Content-type contact

```
root@homer:/usr/share/nginx/html/8/sites/default# drush field-create contact voorvoegsel,text
PHP Fatal error:  Call to undefined function field_info_field() in phar:///usr/local/bin/drush/commands/core/field.drush.inc on line 175
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function field_info_field() in phar:///usr/local/bin/drush/commands/core/field.drush.inc, line 175

```

Googling gives me no clue, so i post this here. Can't find a (good) solution.

# Answer
> 4 votes
Drush doesn't support field commands for Drupal 8 yet. The error message is caused by the fact that Drupal 8 no longer has a function field\_info\_field() - see Drupal change record at https://www.drupal.org/node/2260037

Drush issue at https://github.com/drush-ops/drush/issues/230

---
Tags: drush
---


# Question
Title: PDOException error - Google AdWords Conversion module
My Drupal site is having a serious issue. Whenever I try to add content, such as a Basic Page, I receive this error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_adwords\_conversion\_id' in 'field list': INSERT INTO {field\_data\_field\_adwords} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_adwords\_conversion\_id, field\_adwords\_conversion\_language, field\_adwords\_conversion\_format, field\_adwords\_conversion\_color, field\_adwords\_conversion\_label) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 45 \[:db\_insert\_placeholder\_2\] =\> 45 \[:db\_insert\_placeholder\_3\] =\> page \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> 992249945 \[:db\_insert\_placeholder\_7\] =\> en \[:db\_insert\_placeholder\_8\] =\> 3 \[:db\_insert\_placeholder\_9\] =\> FFFFFF \[:db\_insert\_placeholder\_10\] =\> ) in field\_sql\_storage\_field\_storage\_write() (line 451 of

I know things don't just happen without a reason, but I'm not sure how it happened. Looking at my change notes, I did make a change on 01/27/2014: "Removed 'AdWords' from Webforms to work-around an error." Vague, I know. But this seems to be related to the "Google AdWords Conversion" module I am using (v7.x-2.0-beta). I went to their site and no one else appears to be having this issue.

I tried to tinker with the field definitions, but every time I do I end up with a SQL error.

Unfortunately, I cannot remove the AdWords Conversion module from the admin panel; it is grayed out because it's in use. I tried removing it manually (from the file system), and that rendered the site inaccessible; I had to restore from back-up.

I could, in theory, restore to my 01/27 back-up... but I've made many cosmetic changes since then, somehow without noticing this critical SQL error. So my preference would be to fix this rather than back-out to 3 weeks ago.

I'm running Drupal v7.26. I'm at a loss on how to fix this. Does anyone have any suggestions?

Thank you very much!

# Answer
OK I would take this approach. First off you need to look at the **system** table within your Drupal DB. Since you can't for whatever reason disable the module from the UI you'll need to disable it from here. You can do this by navigating to the row representing the module, and setting the **status** column to **0**. Once you've done this clear your cache.

The error message you're getting is due to a database schema inconsistancy, so what I would try do is navigate to the **Modules -\> Uninstall (/admin/modules/uninstall)** and see if I can now uninstall the module. Depending on how the module is written, this should invoke **hook\_uninstall** and undo any database scheme alterations made when the module was initially installed.

Hopefully this will get rid of the nasty PDOException you're running into when editing your webform.
> 2 votes

# Answer
The error:

> Column not found: 1054 Unknown column 'X' in 'field list': INSERT INTO {field\_data\_field\_X} ... in field\_sql\_storage\_field\_storage\_write()

means that you're trying to save field data, but there is no column to store it.

Probably your Drupal structure has been corrupted or it's bug of the module.

This is normally defined in `hook_field_schema` of your module which deals with that type of field (usually in `.install` file).

So the solution could be to:

* recreate a field instance (remove the old one, create a new one),
* reinstall the module (disable, uninstall and install again),
* create such column manually in SQL or using below sample code:

```
$column_name = _field_sql_storage_columnname('field_adwords', 'conversion_id');
db_add_field('field_data_field_adwords', $column_name, 'conversion_id');
db_add_index('field_data_field_adwords', $column_name, array($column_name));

```
* recreate all the schema fields as per Update field schema
> 0 votes

---
Tags: 7, database
---


# Question
Title: Adding a temporary column to a db_select query
I'd like to add a temporary column with a fixed value to a database query. Eg a column called 'type' with a value of 'thing' for every result. I have tried using the `addExpression` and `addField` functions to do this but I'm not getting the right result.

Is this possible using `db_select`? I've tried the following:

```
$query = db_select('people', 'p')
   ->fields('p', array('id', 'date'));
$query->addField(':val AS type', array(':val'=>'thing'));

```

However this is executing the following query:

```
SELECT p.id AS id, p.date AS date
FROM
people p

```

I suppose I'm trying to get drupal to do:

```
SELECT p.id AS id, p.date AS date, 'thing' as type
FROM
people p

```

# Answer
You just need to use an expression, e.g.

```
$query = db_select('people', 'p')
  ->fields('p', array('id', 'date'));

$query->addExpression(':val', 'type', array(':val' => 'thing'));

```

Gives:

```
SELECT p.id AS id, p.date AS date, :val AS type
FROM
{people} p

```

The replacement for `:val` will be injected when you execute the query.
> 4 votes

---
Tags: 7, database
---


# Question
Title: How do I show product attribute fields in a view?
I'm having difficulty with what seems straight forward and have tried many Drupal Commerce extra modules. Can anyone advise on showing product attributes in a add-to-cart form?

I have product types: \- "product" and \- "boat checkout"

And "boat checkout" products: \- 1/2 day \- full day

And node types: \- basic page \- boat \- boat reservation

I'm not able to get boat product attributes showing in the add form nor in the checkout view, despite attribute settings on Despite visibility on /admin/commerce/products/types/boat-checkout/fields. I'd prefer using a view to keep the site simple (and not creating 2 nodes to display 2 products).

Separately, can product attributes be saved/ shown on orders?? Very hard letting users change or view attributes.

# Answer
Answer borrowed from my answer over here.

Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display\_suite or panels to get more advanced control over what your products look like when rendered.
> 0 votes

---
Tags: commerce
---


# Question
Title: Error migrating a Drupal 8 site from beta15 to final
I have a site in development that is currently running Drupal 8 beta 15. As it is on shared hosting without shell access, I'm planning on moving it to a VPS. Updating Drupal 8 via FTP is just far too annoying.

But when I tried to move the site to a new server I encountered a problem. The new server is running Ubuntu 14.04 with PHP 7 on it.

I installed the final Drupal 8 on the server, and then copied the sites, themes and modules folder from my beta site and restored the beta database on the new server.

But now I get the following error when trying to access the site:

> PHP message: Uncaught PHP Exception InvalidArgumentException: "$max\_age must be an integer" at /var/www/html/drupal/core/lib/Drupal/Core/Cache/CacheableMetadata.php line 81"

I tried `drush cr`, but that didn't do anything. I also can't execute an updatedb, I get the following error then:

> Error: Call to undefined function drupal\_get\_installed\_schema\_version() in /var/www/html/drupal/core/includes/install.inc on line 80 Error: Call to undefined function drupal\_get\_installed\_schema\_version() in drupal\_load\_updates() (line 80 of /var/www/html/drupal/core/includes/install.inc).

Any ideas on how to fix this particular error? Or alternatively, a better way to migrate my beta site that doesn't rely on shell access on the server?

# Answer
> 3 votes
This particular error comes, when your `services.yml` file is outdated. It contains the default cache max-age:

The relevant portion looks like this.

```
parameters:
  renderer.config:
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []

```

This was added after beta 15, which is why you are seeing that error. Since some portions depend on the default max-age being defined, it will gives error when it isn't.

When updating your site, pre 8.0.0 you need to verify that your `services.yml` contains the required info.

# Answer
> 0 votes
I just had this problem (with 8.0.x HEAD) it was solved by doing a drush updb.

---
Tags: 8, migrations
---


# Question
Title: Need to create a link to call a function in a module
Want to create a link "Click Here To..." that will call a function in a module.

What is the best way to achieve that?

Thanks!

# Answer
There is more than one way to skin a drupal. What is "best" depends heavily on the situation, but here are a few options. Is this drupal 8 or drupal 7?

Use rules instead of functions, and the Rules Link module.

Use a hook\_menu to make a menu\_local\_tasks (a.k.a. tab) and style it how you want.

Look at the print module for inspiration and use a hook\_node\_view to add to the node's normal link set, where print adds it's print links.

As I have said on the irc many times, give more context information to get a better answer.
> 1 votes

---
Tags: hooks
---


# Question
Title: How to set default value of select list field on add node form?
I am trying to set the default value of a select list field on a node add form. The field name attribute in the HTML of the form is:

```
field_state[und]

```

The ID of the add form is:

```
local-affiliate-node-form

```

I created a little module to try to do this. It just has this code in it:

```
function MODULENAME_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'local-affiliate-node-form'){
        $form['field_state']['und']['#value'] = 17;
    }
}

```

I enabled the module and cleared cache but it doesn't appear to work. I also tried these lines inside the IF statement:

```
$form['field_state']['und']['value'] = 17;
$form['field_state']['und']['value']['#value'] = 17;
$form['field_state']['und']['#default_value'] = 17;

```

In case you're wondering, I can't use the Drupal interface to set the default value because eventually that "17" will be dynamic, so it will change depending on what the user clicks and I will use a string in the URL in place of a static number.

Thanks for any help!

# Answer
> 2 votes
If you need "code" way you need set default value like this.

```
$form['field_name']['und']['#default_value'][0] = "1"

```

"1" - its number of element which you want set default.

I use that when i need set programaticaly default value for field which use term reference.

---
Tags: nodes, forms
---


title: Combine several field as a new field

text:
# Question
Title: Combine several field as a new field
say my custom content type has 3 different fields: max, min, mean. What I want to achieve is group them into a new field say statistics so the new statistics field will have all the values in fields max, min, mean.

In terms of display, I now have several walk around solutions.

1. in node--examplecontent.html.twig template:

`statistics:{{ node.field_max }}/{{ node.field_min }}/{{
node.field_min }}`

but the problems with this is that "statistics" is hard code so it can't benefit from the translation module if I want to build a multi-lang site.
2. or I could define a dummy field "statistics", and hide it in the form display so user wont need to enter the value of "statistics" when create new content of the content type. then in node--examplecontent.html.twig template:

`{{ node.field_statistics.fieldDefinition.label }}:{{ node.field_max
}}/{{ node.field_min }}/{{ node.field_min }}`

this will allow me to translate to label of field statistics to have it dispaly as a different language.

I wonder if there are some better ways to achieve it, thank you.

# Answer
I think there are several ways to go about this, but with your current field setup and familiarity with template you can use the `trans` functionality in Twig (see https://www.drupal.org/node/2047135).

```
{% trans %}
  statistics: {{ node.field_max }}/{{ node.field_min }}/{{
node.field_min }}
{% endtrans %}

```

Other ways of doing things:

* hook\_entity\_extra\_field\_info()
* Display data via views (see nizz0k's answer)
* Translate in PHP in the template preprocess function
* Create a new field type that stores, min, max, and computes statistics via a Typed Data method.
* Similarly to the above, add a typed data data type plugin to calculate statistics.
> 4 votes

# Answer
If you're doing this is views, you can rewrite the output of the fields into a single dummy field. Simply put the fields you want to combine above the dummy field and exclude them from the display, then use tokens to write your fields into your dummy field to display them all.
> 0 votes

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


# Question
Title: How can I get the sub-navigation to show up in the sidebar on child pages
Drupal newb here :) So I may not have the Drupal lingo correct in my explanation...

I have a menu block called "Sub Navigation". Here are my configurations:

(I've inherited this site so I'm not sure if this is a default block or not etc)

So, the navigation shows up just fine in the sidebar of parent pages, but it does not on *any* child page. (The admissions parent page has a context configuration, is why it is omitted here).

Am I missing a configuration here?

Thanks for any help!

# Answer
> 1 votes
I got some help with this, and what it needed was for this checkbox to be selected:

---
Tags: 7, blocks
---


# Question
Title: htaccess non www to www redirect is not working properly
I have a site here at http://www.tlsasalestraining.com/browse-all-training-solutions its redirect non www(http://tlsasalestraining.com/browse-all-training-solutions) is taking it to homepage. Attach is my .htaccess. I have tried mulitple codes from internet but nothing is working

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

Redirect 301 /index.html http://www.tlsasalestraining.com/

# Redirect all users to access the site WITH the 'www.' prefix

 RewriteCond %{HTTP_HOST} .
 RewriteCond %{HTTP_HOST} !^www\. [NC]
 RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

# Answer
> 2 votes
Your problem is more than likely that you are placing the rewrite rules after the catch-all rule. Try restoring the stock .htaccess, and uncommenting lines 92-94, so that it reads

```
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

---
Tags: 7, .htaccess
---


title: XML sitemap rebuild links on cron run

text:
# Question
Title: XML sitemap rebuild links on cron run
I've installed XML Sitemap. I can manually rebuild the link in **/admin/config/search/xmlsitemap/rebuild**. Is there any way to automatically rebuild the links (e.g. when cron runs XML sitemap would rebuild the links) ?

# Answer
you need to set frequency of sitemap you can change it on daily,weekly,monthly basis

How add frequency in sitemap
> 0 votes

# Answer
Hello you can do it by another way by adding to your cron server your settings.
> -1 votes

---
Tags: 7, cron, xml-sitemap
---


title: Add font to bootstrap sub-theme

text:
# Question
Title: Add font to bootstrap sub-theme
I use drupal 8, and Bootstrap theme.

I created a sub-theme.

I would like added one font that I downloaded, to use it in my sub-theme.

I read contradictory things to realize it. For example that it was enough to create a folder "font" in its sub-theme, and add the font in it, then add it in `mytheme.libraries.yml`, or that it was necessary to place this font in the folder `vendor/` . I am a little lost.

How can it be done?

# Answer
> 1 votes
I followed this guide on Google Fonts to get it to work with my downloaded font. In your case that would be editing your info file to declare that you have fonts assets:

```
name: Subboot
description: Bootstrap Subtheme
type: theme
base theme: bootstrap
core: 8.x
libraries:
  - subboot/fonts

```

then edit the libraries.yml in your subtheme, ex. subboot.libraries.yml to add in the following:

```
fonts:
  css:
    theme:
      //your.domain.com/path/to/font {}

```

---
Tags: 8, theming
---


# Question
Title: Organic Groups - How to disable "Groups" Tab
I enabled OG and now I have a tab that lists all "public" groups if you're not registered, and it'll show the groups you belong to if registered. What's the best way to get rid of the groups tab for Anonymous users? It can be visible to authenticated users.

# Answer
> 1 votes
The quickest way I can think of doing it would be to use the Tab Tamer module. I've used it to do the exact same thing on a Drupal 6 site and it worked really well.

# Answer
> 3 votes
I had a similar problem with OG Extras installed, the view and members tab would show even when a site visitor wasn't logged in, I wanted it hidden for non registered users or non-admin users.

To stop it showing I edited the view 'OG Extras group members (User)' made sure I had the Page, not the block of the view selected and changed 'Access:' for the 'tab menu' to Role | administrator, this means that when logged in as an administrator I can see the desired tabs but when logged out the tabs are hidden.

# Answer
> 0 votes
Also if you created the menu links by the modules views, you can restrict access to the menu link and the viewed page from the views module.

# Answer
> 0 votes
OG Invite People provides an "invite" for existing users as well as new users. In 2.x it has an option to disable the OG group tab. Usual use case is to make your own "manage members" tab beneath via views or panels.

---
Tags: users, organic-groups
---


title: PluginNotFoundException - MailChimp

text:
# Question
Title: PluginNotFoundException - MailChimp
Earlier today I tried to install the MailChimp plugin for Drupal 8. I couldn't get it working properly so I decided I would just go ahead and uninstall it.

However, when I navigate to `/admin/modules/uninstall` I get the following error:

> The website encountered an unexpected error. Please try again later.
>
> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "filter\_mailchimp\_campaign" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 57 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
>
> Drupal\Core\Plugin\DefaultPluginManager-\>getDefinition('filter\_mailchimp\_campaign') Drupal\filter\FilterPluginCollection-\>initializePlugin('filter\_mailchimp\_campaign') Drupal\Component\Plugin\LazyPluginCollection-\>get('filter\_mailchimp\_campaign') Drupal\filter\FilterPluginCollection-\>get('filter\_mailchimp\_campaign') Drupal\filter\FilterPluginCollection-\>sortHelper('filter\_align', 'filter\_mailchimp\_campaign') uasort(Array, Array) Drupal\Core\Plugin\DefaultLazyPluginCollection-\>sort() Drupal\filter\FilterPluginCollection-\>sort() Drupal\filter\Entity\FilterFormat-\>filters() Drupal\filter\FilterUninstallValidator-\>validate('filter') Drupal\Core\Extension\ModuleInstaller-\>validateUninstall(Array) Drupal\Core\ProxyClass\Extension\ModuleInstaller-\>validateUninstall(Array) Drupal\system\Form\ModulesUninstallForm-\>buildForm(Array, Object) call\_user\_func\_array(Array, Array) Drupal\Core\Form\FormBuilder-\>retrieveForm('system\_modules\_uninstall', Object) Drupal\Core\Form\FormBuilder-\>buildForm(Object, Object) Drupal\Core\Controller\FormController-\>getContentResult(Object, Object) call\_user\_func\_array(Array, Array) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() call\_user\_func\_array(Object, Array) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) Stack\StackedHttpKernel-\>handle(Object, 1, 1) Drupal\Core\DrupalKernel-\>handle(Object)

Likewise, when I try and go to edit any pages content, I get the same error. This is preventing me from doing anything. I went ahead and uninstalled the plugin manually be removing all of the mailchimp files from the modules directory over FTP but I am still getting this error.

Any ideas on what I need to do to fix this? It's driving me crazy!

Thanks

# Answer
I was able to fix this. I had to go into the database and manually delete the entry `filter.mailchimp_campaing` from the `config` table.
> 0 votes

---
Tags: 8, emails
---


# Question
Title: How to export 'Content-Type' data into JSON?
I'm using Drupal 7 and I've created a content type as 'CONTENT\_TABLE', which includes multiple fields (COLUMNS) as such: CONTENT\_ID, CONTENT\_NAME, LARGE\_THUMBNAIL, ZIP\_FILE...

I want to export the data (each row of the table) into a JSON. I need to use this JSON as an input for another website.

I have tried to look for Node export module, but I'm not sure how to export the data into JSON which can be used as is.

Expected JSON:

```
{
   "ContentItems": [
      {
         "CONTENT_ID": "123",
         "CONTENT_NAME": "ABC",
         "LARGE_THUMBNAIL": "C:/LargeThumbnail/ABC.jpg",
         "ZIP_FILE": "C:/LargeThumbnail/ABC.zip"
      },
      {
         "CONTENT_ID": "234",
         "CONTENT_NAME": "PQR",
         "LARGE_THUMBNAIL": "C:/LargeThumbnail/PQR.jpg",
         "ZIP_FILE": "C:/LargeThumbnail/PQR.zip"
      }
   ]
}

```

# Answer
You could make a view of your nodes then use

Views Datasource

> Views Datasource is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML.

For how to use, see the accepted answer to this Views JSON output
> 2 votes

# Answer
You could use the Forena module (disclosure: I'm a co-maintainer of it) as your 1-stop-solution (using only 1 contributed module) to:

* Build your custom query to fetch the data, whereas these data can be retrieved directly from your Drupal database. Obviously, in this case it's be an SQL to retrieve your `CONTENT_ID`, `CONTENT_NAME`, `LARGE_THUMBNAIL`, `ZIP_FILE` ...
* Format the look and feel of your results (the report) using xHTML (and/or charts if you'd like).
* Download the results in any of the typical formats, such as PDF, XLS, CSV, XML, JSON, etc. For any report that you create (using Forena), just add `.csv` as an extension to the report (output) URL. That contains the CSV equivalent of that report (similar for the other formats).

### Example

As a sample, consider the sample report located at `/reports/sample.states` in your own site (one of the samples shipped with Forena) or in the Simple Table of States in the demo site. Change the URL to `/reports/sample.states.csv` (= just add `.csv` to it) to get the same report in `.csv` format. By adding such `.csv` to the URL, the result is like so ...

Same technique applies for other supported extensions (export formats), such as:

Remark: when building a report, you can also specify for which of these Document Types an hyperlink should be made available in the report.

### Direct access to data blocks

All data blocks are also accessible directly via their url, provided you have permission to access that block. Here are a few samples of that (from the demo site), for the sample report located at `/reports/sample.states`:

### More info

### Getting started

* To actually install/configure Forena, make sure to look at the various steps in the **Setup Guide** that comes with it, which you can find at `/reports/help.setup` in your own site also after you enabled Forena (similar to what you can see in the demo site). Missing (forgotten) "permissions" and/or "text formats" configurations (if you don't follow the Setup Guide) or the most common showstoppers if you"re new to Forena ...
* If you run into "PDO driver support for sqlite not installed", then head over to comment nr 7 in issue #1061436. Here is a summary of it: you only need that for using the "sample database" (the one you can also see in the demo site), which is delivered in SQLite format. So you can use Forena without that support, eg to access your own Drupal database (in MySql fmt). And/or you might want to look at the "drupal admin samples" instead ...
> 4 votes

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


title: Automatic tagging (based on other tags)

text:
# Question
Title: Automatic tagging (based on other tags)
I have the following taxonomies:

* Countries
* Cities

When I create a new node Im allowing to enter "Cities" as a field of that node. Given that I have a "mapping" in place, how can I automatically assign the "Country" to that node as well (the user doesn\`t have to do it, it happens in the background)?

Example: I "tag" a node with "New York" - and that node is atomatically tagged with "United States" behind the scenes. When listing "United States" in a view, the node tagged "New York" would appear amond all other nodes tagged with US cities.

Also, where would the mapping of "New York -\> United States" be defined?

Thanks for your help!

# Answer
> 1 votes
Here is the module to do it:

Hierarchical Term Reference Autocomplete

I think it's preview image shows exactly what you want

---
Tags: taxonomy-terms
---


# Question
Title: Converting a helper class into an Entity
I am working on a Drupal 8 module, and a separate module of examples, on how to use the first module. In my example module, I have a function in my controller that looks like this:

```
public function basicUsage() {
  // Basic line chart.
  $series[] = [
    'data' => [[0, 3], [4, 8], [8, 5], [9, 13]],
  ];
  $params = [
    "data" => $series,
    "theme" => "flot_examples_basic_usage",
  ];
  $flot = new FlotD8($params);
  $output[] = $flot->outputPlot();
  return $output;
}

```

I would like to use the standard entity notation if possible to simplify things, and make it look like this:

```
public function basicUsage() {
  // Basic line chart.
  $series[] = [
    'data' => [[0, 3], [4, 8], [8, 5], [9, 13]],
  ];
  $output["flot_d8"] = [  //maybe name needs to be FlotD8?
    "#data" => $series,
    "#theme" => "flot_examples_basic_usage",
  ];

  return $output;
}

```

Here is the code for my class. What do I need to do or change to give it the behavior I'm looking for? Is it just a matter of extending a certain Core Entity class? I do not need any schema or database functionality.

```
<?php
namespace Drupal\flot_d8\Entity;
class FlotD8 {
  protected $id;
  protected $theme;
  protected $data;
  protected $options;

  function __construct($params){
    $this->id = isset($params['id']) ? $params['id'] : 'placeholder';
    $this->theme = isset($params['theme']) ? $params['theme'] : 'flot_d8_my_template';
    $this->data = $params['data'];
    $this->options = isset($params['options']) ? $params['options'] : NULL;
  }

  /*
   * Create the theme output.
   */
  function outputPlot (){
    $drupalsettings['flot_d8'][$this->id] = ['data' => $this->data, 'options' => $this->options];
    $output = [
      '#attached' => [
        'drupalSettings' => $drupalsettings,
      ],
      '#theme' => $this->theme,
      '#options' => $this->options,
      '#data' => $this->data,
    ];
    return $output;
  }
}

```

# Answer
Why exactly do you want to use an entity?

Entities are about CRUD. Saving, loading and deleting data in the database or somewhere else.

From looking at your code, that doesn't really seem to be what you're after, you just have an API to display some data. That's not what entities are about at all.

You could make a service of your class but that doesn't really seem to match either.

I guess the only thing that would make sense is to define it as a render element. See RenderElement and Render API overview.

So you'd define your class with @RenderElement in an Element namespace, see Link for an example. You give it a name in the annotation, like yourmodule\_plot and in your render array, reference it as #type =\> 'yourmodule\_plot' and pass the data to it like that.

A render element class basically consists of a getInfo() method that defines some default properties. In your case, that would be #theme, #attached and so on. if you need to dynamically process your data, you can add a #pre\_render callback like shown in the Link example that can then process the merged array of your defaults + data you specify in the controller.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Migrating disqus comments from non drupal site to drupal 7 site
I have installed an set up Disqus (add shortname and public key). How can i show/migrate my old comments to my new drupal site.

# Answer
Disqus offers variety of migration tools depending on your needs - https://help.disqus.com/customer/en/portal/articles/286778-migration-tools. I performed migration of comment threads from static website to Drupal 7 recently. Main change to the pages with comments was new clean URLs, so in my case all I needed to do is to use URL mapper tool. It is very straight forward and comment threads were migrated in minutes.
> 2 votes

---
Tags: 7, migrations, comments
---


title: Centering block view

text:
# Question
Title: Centering block view
Hello Drupal community!

I have a questions about displaying content with views. Is it possible to center the content within the block, in-browser?

Right now I have two entities next to each other, both left-aligned. I am trying to get them both centered in the block, and centered on the page.

Any ideas?

# Answer
> 1 votes
You need to right click and inspect the elements and find the div **class** or **id** that belongs to those blocks or fields.

Then with CSS you can center them. See CENTERING THINGS. So just add the css to your theme's style.css file, located in `/sites/all/themes/yourtheme/` folder.

Then remember to flush the cache to see the changes.

---

**If you want to do it within Views using REWRITE RESULTS**

put `<center>[title]</center>`

---
Tags: views, blocks
---


# Question
Title: Why Conditional Fields Validating the Hidden Fields?
I have preset sizes like small, medium and large and an option to provide custom size. If some one selects custom option from a select list the measurements fields appears through conditional fields and if some one select small medium or large the measurements fields hides.

The problem is when I am submitting a form by selecting Small, Medium or Large option from select list it gives error that measurements fields are required.

I have tried to add additional condition to make the fields optional if the select list has the values small, medium or large but still getting the same error.

# Answer
> 0 votes
Check that your measurements field isn't set as required in the field settings in content types. You could also provide a default of 0 I guess.

---
Tags: forms
---


# Question
Title: How to make a view specific to only 1 node, not all nodes
I am building a register event calendar so people can sign up for future events. I have the calendar and the registration for events already completed. Now all I want to do is create a view that will display all the current registered users for the event, but here is the problem i'm running into.

In drupal views it is listing ALL the register users for ALL events. So instead of viewing only a group for one specific event, its adding every single person that has ever clicked the register button.

What steps do I have to go through to say "no, only list register users for THIS event"?

My content type is "Date" for setting a event and my registration is set to "Meetings". I'm not quite sure how to tell views to organize each event separately, rather than together.

# Answer
> 0 votes
At Taxonomy add one vocabulary and name as "Event". At content type add fields for particular info and "Event". User will fill up the particular as well as event type. At views filter by Event category. This is an example and I not really what is your structure. Hope it help

---
Tags: views, users
---


# Question
Title: How to use Rules to redirect a user based on URL argument?
I'm using Drupal 7 and the Drupal Commerce module. I'm now able to capture an argument passed by URL using Rules (thanks to this helpful thread). However, I'd now like to be able to redirect the user to one page if the argument equals one thing and send them to a different page if it equals ANYTHING else. Anyone know how to do that?

I tried using 'Page Redirect' as an action in Rules, after the action of capturing the argument in the URL (Action \> Provide URL argument value), but there's no option in the Page Redirect action to send users somewhere based on the argument value.

So for example, I have users coming to the site with urls like so:

```
membership-renewal/?ID=promo1

```

Currently Rules is recognizing that they are using that URL and it's reading 'promo1' value using `[ID:value]` replacement pattern...I can print it out to the screen so I know it's reading it.

But I don't know how to then use that value to inform a page redirect for example.

Anyone know?

# Answer
> 2 votes
Well, if you're planning on doing it solely via rules, you can create a new rule for each `if` in your logic and then just set them to be actions one after the other. Something like this:

```
Action:
  RULE:
    IF: <condition>
    REDIRECT: <here>
  RULE:
    IF: <condition>
    REDIRECT: <here>
  RULE:
    IF: <condition>
    REDIRECT: <here>

```

This would effectively work like an `if`-`elseif`-`else` statement (assuming that the redirection is using `drupal_goto()`.

But really, this sounds like a job for a custom action that takes the parameters and includes your own custom logic. It'd probably be a lot cleaner in the long-run.

# Answer
> 1 votes
To make the value of the URL argument available as new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.

---
Tags: 7, rules, redirection
---


# Question
Title: Custom "admin/people" view preventing user creation
I've created a new view for admin/people; as part of the view set up, I've included "Path: /admin/people."

However, this causes a "page not found" error when I go to "admin/people/create"; I'm guessing I'm not supposed to use the path setting here.

How else would I override the default user view?

# Answer
Set your path to admin/people/list, not admin/people

Set the menu item for the page to "Default Menu Tab"

Set Default tab options to "Parent menu item already exists"

Worked for me, and didn't interfere with other items under the admin/people pages. It even added the "add user" link that normally appears on the regular admin/people pages.
> 4 votes

# Answer
It seems like you would have two somewhat clean options.

* Alter the menu router that views defines so that it sets itself as a default tab and whatnot which is why I assume "create" is not working.
* Use `hook_menu_alter()` to hide the default "admin/people" menu item (not delete, just change it to a callback so it doesn't show in menu) then define your view as "admin/people2" and just deal with the URL. You can also use the menu module to disable the link (or `hook_menu_alter()` I suppose as well)

Additionally you can look into `hook_url_inbound_alter()` and `hook_url_outbound_alter()` to try and fake the "people/create" or "people" pages.
> 1 votes

# Answer
I ran into this issue and for some reason, turning off the default view and using my overridden view with the same path got the same access denied (which oddly worked for all the other admin views). I disabled and enabled both default and my new view a bunch of times. I also edited the path and saved it a couple times. and it suddenly worked at some point. Not sure why, but it did. Hopefully that helps anyone else who finds this question.
> 0 votes

---
Tags: views, users
---


title: Exposed Filters in Drupal 8

text:
# Question
Title: Exposed Filters in Drupal 8
I am not able to get exposed filters to work in Drupal 8. Here is a screenshot to help me while I explain some of the issues

I want to filter by the title of a content type. This title was renamed to "Name" as you can see me trying to put it in the value for the operator to compare. This value seems to be the default since when I try this, "Name" is in the field and not grabbing any nodes. Without anything inside the Value box, nothing is coming up for my queries when testing this filter.

So how do exposed filters work in Drupal 8? Nothing I have tried has gotten any results.

# Answer
> 1 votes
Exposed filters do work in 8.0.2, although there are limits of to how well you can format or alter them.

But you want to do should work fine. Looking at your uploaded image, though, suggests you don't quite have it configured right for what you want to do. I'd recommend that you leave "Value" blank, and choose "Contains" as the operator. Under "Advanced", check "Use AJAX". Once you "Apply" to the display, you'll see a preview at the bottom of the view edit window. If you start typing the name (i.e., title) of one of your nodes, you'll see that the list of nodes at the bottom of the window indeed updates as you type.

---
Tags: views, 8
---


# Question
Title: How to remove H tag from user register form in drupal for SEO purpose
I want to remove tag from user register form in drupal for SEO purpose.How can I achieve it in drupal way?

# Answer
> 0 votes
You can use hook\_form\_alter or hook\_form\_FORM\_ID\_alter to alter form field which you want to alter. The `$form_id` would be `user_register_form`.

```
function MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // do the altering you want here
  }
}

```

---
Tags: users, theming
---


# Question
Title: How to use Computed_field as a product of an existing one?
I would like to have a field (`field_result`) that would display a number that is the result of the product of an existing field (`field_1`) on the same content type (let's call it `book`) and a fixed number (let's say 3.5).

My idea was to use the Computed Field module in order to display the result. After reading its Community documentation I managed to do the following:

That's what I achieved so far:

1. I configured field\_result to accept only one value and save it on the database.
2. I set its value as follows:

`$field_1 = field_get_items($entity_type, $entity, 'field_1');
$entity_field[0]['value'] = $field_1[0]['value'] * 3.5;`
3. I set its `$display_output` as follows: `$display_output = $entity_field[0]['value']`

Unfortunately when I edit the node and save it I get the following notice:

> Notice: Undefined index: value in eval()

and the field displays 0.00 as a result.

What am I doing wrong?

# Answer
> 6 votes
A NOT commonly known/used solution that might help to prevent your problem from happening, is to use the (fairly new) Math Field module (for D7), instead of the Computed Field module (so change your mind about which module to use). Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Known issues**

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...

# Answer
> 4 votes
You are missing the function

example:

```
function computed_field_field_profit_compute(&$entity_field, $entity_type, $entity,
$field, $instance, $langcode, $items) {
 $entity_field[0]['value'] = $entity->field_price[LANGUAGE_NONE][0]['value'] - $entity->field_cost[LANGUAGE_NONE][0]['value'];
}

```

> The function name pattern that needs to be used is computed\_field\_{field\_name}\_compute.

For more info, I suggest you read Working with the Drupal Computed Field Module

**But... I highly suggest you look into the Math field module as suggested in the other answer, any time you can avoid enabling PHP Filter you should take it. Have a look at "What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc?" to understand why**

---
Tags: 7, entities
---


# Question
Title: URL aliases [node:language] repetition issue
I have an issue with URL aliases creation. I have set my configuration as following:

The default path pattern above is the only one configured. Yet, when I create my content type instances and translate them, I get the following:

```
http://mysite.localhost:8082/en/search-form
http://mysite.localhost:8082/fr/fr/recherche-de-mots
http://mysite.localhost:8082/ab/ab/dfghdf

```

EN is the default language, but why do I get double `/fr/fr` and `/ab/ab`? These are the links created in the language link available under node contents.

**REM:** *Generate automatic URL alias* is set on all node content translations.

**Update**

Of course, I would like to avoid repetitions (this is my real question):

```
http://mysite.localhost:8082/en/search-form
http://mysite.localhost:8082/fr/recherche-de-mots
http://mysite.localhost:8082/ab/dfghdf

```

# Answer
> 1 votes
That happens because Drupal is using the language prefix to generate the language URLs, and you are using the \[node:language\] token in the path pattern. As consequence, the language prefix appears twice.
In the first case, as English is the default language, the prefix doesn't appear twice because \[node:language\] is replaced from an empty string.

Just use \[node:title\], instead of \[node:language\]/\[node:title\] as path pattern.

The reason for allowing the use of \[node:language\] is that the other method to generate language URLs is through a domain for a specific language. Suppose you set http://exemple.com has domain for the French language; with your path pattern, the URL alias would be something like http://exemple.com/fr/recherche-de-mots, which is perfectly acceptable.

# Answer
> 0 votes
There's also the possibility to *rewrite the results* of your `path`-field, and select "**Use absolute link**" (not to be confused with the similar option under "rewrite as link").

It gave me the right result.

---
Tags: 7, uri, path-aliases
---


# Question
Title: How to share only a particular link in a node using social media,instead of complete node?
Using **user referral** module i was able to generate referral link. After this i enabled **social media** module in order to share the particular link to other people whom i would be referring.

While testing this,i came to know that instead of link,entire node is being shared.

Can anyone tell me an idea as how to share only the link,apart from getting the entire node being shared

# Answer
If you're open to using an alternative module (instead of the Social Media module), you can get this to work for at least **Facebook** and **Twitter** by using the Rules module instead, combined with these modules:

For (way) more details on that, refer to my answer to "How to post the node link in social networking if node is published?", which also explains what the options are (that I'm aware of) for **Google+**.
> 0 votes

---
Tags: nodes
---


# Question
Title: Theming views-exposed-form search block same like normal Drupal search block
On this page, top-right you see a custom `views-exposed-form` search block. How do i theme this, so it has the same classes and HTML structure as the one below (default Drupal search block)?

# Answer
You can try block attributes

You can edit class or ID. More readable and easy to maintain.
> 0 votes

---
Tags: search, theming
---


title: Webform Protected Downloads Module

text:
# Question
Title: Webform Protected Downloads Module
This module is able to send emails to subscribers. User has to click a download link (included in an email) and will be redirected to a download page. After that he/she need to click the link to open the file. Lastly, save the files to their computer.

Here is my question: Is there any way to click the download link from his/her email and download the files immediately?

More Info: I think Email Download Module is what I need, however it is only use for drupal 6.

# Answer
> 1 votes
I have never used that module before but by reading its home page I found this

> When a user submits a webform with protected files he will be sent an email with a link to the downloads page. **The link contains an individual hash code that will be checked upon page load to verify the access.** If verification fails access will be denied. **If it succeeds the user will see the default private upload file listing with all protected files that are attached to the webform.**

Now based on your question you want to add a link direct to the protected files by the module, bypassing (if that is possible) the access verification, to violate the module's functionality. Why you want to do that ? I think that this is not a good idea even if possible. Probably you are looking for another module or I am missing something.

---
Tags: 7
---


# Question
Title: Save Nodes with Field collection in a different database
I am trying to node\_save($node) in different database. Second DB is clone of first DB.

its the part of Archive old content data in different database

I am trying with following code

```
  $node = node_load($nid);
  db_set_active('archive_db');
  field_info_cache_clear();
  node_save($node);
  db_set_active();

```

But its not working. Is anything i am doing wrong ?

i want to use node\_save because in my node, number of fields, field\_collection, entity\_refrences are available.

# Answer
Try this, it was working for me:

```
$nid = '2841';
$item_ids = array();
$node = entity_load('node', array($nid), array(), true);
foreach ($node[$nid]->field_COLLECTION_NAME[LANGUAGE_NONE] as $key => $value) {
    $item_ids[] = $value['value'];
}

//load the field collections
$fc_item = entity_load('field_collection_item', $item_ids);

//change db
db_set_active('my_custom_db');

$clone = new stdClass();
$clone = clone $node[$nid];
unset($clone->nid);
unset($clone->vid);
$clone->is_new = true;

//save node so we can use the new nid to link the field collection
entity_save('node', $clone);
//gives you the nid of the new node created
dsm($clone->nid);

//save the field collections
foreach ($fc_item as $key => $value) {
    //unset values
    $value->is_new = true;
    $value->revision_id = NULL;
    $value->item_id = NULL;
    //link it to a node
    $value->setHostEntity('node', $clone);
    $value->save();
    dsm($value);
}

dsm(entity_load('node', array($clone->nid), array(), true));
//go back to the default DB
db_set_active();

```
> 3 votes

---
Tags: 7, database, performance
---


# Question
Title: Is using a TLS/SSL termination reverse proxy currently possible in Drupal 8
I use Nginx (port 443) which terminates TLS/SSL then forwards the request to Varnish (port 80) and on to Apache (port 8080). This worked really well for D7.

Am I correct in thinking that because of the following bug this set-up cannot work without 'Mixed Content' errors due to CSS and JS being written as absolute paths rather than relative paths?

References to CSS, JS, and similar files should be relative to server: less bytes, avoids mixed content warnings

I am looking for conformation of this question to ensure that it is not my server configuration at fault.

# Answer
> 0 votes
The patch you reference was applied to Drupal 8 last month. Drupal 8.0.3 was released 3 February and included the fix. If you're using this version (or later) you should be fine.

---

---
Tags: caching, proxies, 8, ssl
---


title: Recurring payments

text:
# Question
Title: Recurring payments
Looking for feedback from those who have experience or have done research on recurring payment options for Drupal 7. I'm familier with Ubercart UC Recurring for Drupal 6, but have not looked at Ubercart for D7.

My hope, since I'm rebuilding the site from the ground up in with D7, was to use Commerce. But so far, it doesn't appear that there is much support for recurring payments via the Commerce module.

Or... is there something besides Ubercart or Commerce that integrates well with Drupal 7?

# Answer
If what you want/need is an order (multiple products) to be recurring:

Commerce Recurring

If what you want/need is a product (often times a service like hosting or a software license or a paid subscription) to be recurring:

Commerce License Billing \+ Commerce License

Regardless of those two options, you should definitely use the following module to deal with people who have credit cards that expire (everyone!):

Commerce Dunning
> 1 votes

---
Tags: 7, ubercart, commerce
---


title: Comment form won't appear in my theme

text:
# Question
Title: Comment form won't appear in my theme
I can't get the comment form to appear in my theme. It does appear in Garland, but not in Bartik.

I have copied node.tpl.php and comment.tpl.php into my theme from Garland.

I have added text to the node.tpl.php template to ensure that it is in fact the relevant template for the node.

I checked the page source to see if perhaps the comment form is appearing, but is hidden by CSS.

I deleted ALL code from the template.php file in the theme.

I have cleared the cache and run cron after doing all of the above.

I've built more than 100 Drupal sites, so I'm not exactly new to the framework. And yet I can't get the comment form to appear in this theme.

Clearly I must be doing something wrong, but I can't think of what else to check.

Any ideas?

Remember, the comment box does appear in Garland, so this can't be a permissions issue and can't be due to settings in the node itself.

The Drupal version is 7.41.

Thank you.

# Answer
> 1 votes
The "Comments block" module was the cause of this. The module appears to be functioning as intended. I just hadn't encountered this contributed module before, and didn't realize the project made use of it.

Because the "Comments block" module is installed, the "Comment form" block must be added to a region (e.g. "Content") in the theme. This explains why the comment form was appearing in some themes but not in others.

---
Tags: 7, comments
---


# Question
Title: How to fetch manual flate rate token on replacement pattern
How to fetch manual flate rate token on replacement pattern

I added Flate Rate cost manually on orders, but I don't find this token on REPLACEMENT PATTERNS. How to fetch this token for my invoice?

here screenshot that I did

# Answer
> 1 votes
You would need to two things to make this happen:

1. How to programmatically create a custom token. And you'll definitely want to read the API docs on the relevant hook function.
2. How to get at the line item given an order.

Let's assume your token has an $order object inside the $data variable. The next step would be to use entity metadata wrappers to pull in all the information, including line items.

```
<?php
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $line_item = $line_item_wrapper->value();
}
?>

```

Your shipping line item is in there. `dpm($line_item);` to find it and then construct your token output.

---
Tags: commerce
---


# Question
Title: How to filter views rows whose nid is less than nid provided by url?
Drupal 7. In a node/edit form panel I have added a view that returns nodes. I whish to filter thoses nodes and keep only the nodes whose nid is less than the nid of the node beeing edited.

the url of the node/edit form is : /node/11541/edit?step=11538

the nid of the node being edited is : 11541

I wish the view to return only the nodes whose nid \< 11541

I use Views PHP

# Answer
You can implement the `hook_views_query_alter()` to alter your query and change the `=` operator by the `<` operator.

```
function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW_NAME') {
    /* Using the following line dmp($query)
     * (you need the devel module to use dpm) you will be able to search
     * where is condition to alter, you will see that in the
     * $query->where[0]['conditions'][0]['field'] you will have:
     * node.nid = :node_nid
     * so your solution will be replace the
     * = operator by the < operator
     * at this moment you can't do this from the Views UI
     */
    dpm($query);

    $query->where[0]['conditions'][0]['field'] = str_replace('=', '<', $query->where[0]['conditions'][0]['field']);
  }
}

```

I test the code and in my environment it works as I want it to.

Here is my view for if you want test the code (in this case the view name is articulos):

```
$view = new view();
$view->name = 'articulos';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'articulos';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'articulos';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'articulos/%';
$translatables['articulos'] = array(
  t('Master'),
  t('articulos'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('All'),
  t('Page'),
);

```
> 5 votes

# Answer
You can use a contextual filter for your view:

* If you are using a page display, you will be able to retrieve the nid from the URL.
* If you are using a block display, you will need to do it a bit differently. See Contextual filter with a block view
> 2 votes

---
Tags: views
---


title: hook_node_insert() doesn't work

text:
# Question
Title: hook_node_insert() doesn't work
hook\_node\_insert() doesn't work after node insertion in Drupal 8. When I'm trying to get the node details in that hook, it's not working.

My code is the following one.

```
use Drupal\Core\Entity\EntityInterface;

function test_node_insert(EntityInterface $node) {
    dpm($node);
}

```

# Answer
How about hook\_entity\_insert

```
function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity){
  // do something
}

```

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook\_entity\_insert/8
> 4 votes

# Answer
I think you can use hook\_node\_presave(). This function work with new node and update node (hook\_node\_insert run for new node). And better you can use class **Drupal\node\NodeInterface;**

```
<?php
use Drupal\node\NodeInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for node entities.
 */
function node_test_node_presave(NodeInterface $node) {
  kint($node);
}

```
> 0 votes

---
Tags: hooks, 8
---


# Question
Title: Assign to node all child terms if parent term selected
I started to develop my first website with drupal. So far so good, I like this system, but I have one problem: When creating new node, I want to assign all child terms if I select parent term.

Let's say, I have a vocabulary "Plants". In this vocabulary, there are terms with this kind of hierarchy:

```
Fruits
--- Apples
------- Green
------- Red
--- Pears
------- Green
------- Red
Berries
--- Wild berries
------- Red
------- Blue

```

Now, when I create a node, I'm using Simple hierarchical select to select terms of this vocabulary. I'm using Views to display nodes. Let's say I want to assign term "Apples" to a node. When I go to view the page and use Filter Criteria Content: Has taxonomy terms (with depth) (exposed) and choose "Apples", I can see my node.

That's OK. But I want my node to appear if I select Green or Red (under term Apples in terms tree). In other words, if I assign term "Apples" in node creation page, I want it to assign all of its child terms also to this node. I.e., if I assign Wild berries, I want terms Red and Blue (childs of Wild berries) to be assigned also. Because right now, by assigning term "Apples" and then filtering by "Apples" gives what I want, but if I filter by Fruits-\>Apples-\>Green, I get no results.

# Answer
You can use the Taxonomy Term Reference Tree Widget module

> This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

**How to use this module**

1. Enable the Term Reference Tree module.
2. Go to the Manage Fields tab of any fieldable entity (such as a content type, taxonomy term, or user.
3. Add a new field with a type of Term Reference.
4. In the widget select box, select Term reference tree.

Note that you can also change any Term Reference field to use the Term Reference Tree widget, by editing that field and selecting Term Reference Tree on that field's Widget Type tab.
> 3 votes

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


# Question
Title: Product category filter on the /products page
I've been looking for a while but I can not seem to find the correct way to tackle the following problem.

On my products page, where all the products are, I have the standard drupal commerce kickstart filters. One of those filters lets me filter the shown products depending on which category they belong to. Now, I have somewhat of a hierarchy

Term
-child Term
--"grandchild (child of child)

(see image below)

now I'd like to be able to show for example the "Kastanje" product when i click on "Vloeibaar". Show the child product when clicking on the parent.

So far, i have had no idea how to do this and have tried pretty much everything i can think of in the "configure facet display" option.

Anyone who has an idea on how to do this?

# Answer
You need to add a new filter to your view and remove the default category filter.

You should choose: **Content: Has taxonomy term ID (with depth)**

This filter / argument will also return content assigned to child terms of any given taxonomy term.
> 0 votes

# Answer
Complete solution is somewhat as @bmunslow said, though a tad different if you specifically want a hierarchy in your "shop" (/products page by default, where all your products are shown).
1) Go to admin/configuration/search API
2) Go to fields -\> Check the checkbox of Product category » All parent terms | field\_product\_category:parents\_all
3) Save the changes and then go back to facets (2 tabs away from "fields")
4) Click on the checkbox of the All Parent Terms and save
5) go to your blocks. Add the newly saved (enabled) block to your sidebar region, remove the standard one (for product category, leave the price one be if you want it).
6) Check: Expand hierachy checkbox
7) Optional: Go to the display and there "Treat parents items as individual facet items" and save.
> 0 votes

# Answer
And I'm adding a third answer here. This is copied from an earlier answer I posted on the drupalcommerce.org forum.

Here's the tutorial video: https://www.youtube.com/watch?v=y1jqu8JnLbU

**STEP BY STEP**

1. Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)
2. Create a Taxonomy View here: admin/structure/views/add

> You want to make sure that you choose "taxonomy" entities.

3. Add a contextual filter for "Taxonomy term: Parent term"

> Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

4. Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.
5. Save that view and create a new view here: admin/structure/views/add

> Make sure this view is a for "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).

6. Add a contextual filter for your taxonomy term, mine was called "Product Categories"

> Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

7. Add a "No results" item called a "View Area" and select "Page\_1" from your first view (this is the second page we created)
8. Save this view and go back to the first view.
9. Add a "No results" item called a "View Area" and select the second view that we just made.
10. Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/\[name\]" that way your catalog names are clickable :)
11. Profit!

---

**Bonus Answer!!**

As a follow up on the same forum post, they wanted to know how to do this with multiple vocabularies, instead of one vocabulary.

Bonus video: https://www.youtube.com/watch?v=ngl3v0-8XZI

**Bonus!! PRE-FLIGHT CHECKLIST**

Before you walkthrough the video and the step-by-step below, make sure you have three taxonomy vocabularies with three taxonomy terms each. Additionally, confirm your Product Display has a field per taxonomy field.

**Bonus!! STEP BY STEP**

1. Create a View: admin/structure/views/add

* Call it "Catalog" and leave the "page" selected
    * Show type "Taxonomy" for Level 1
    * Click "Continue"
2. Edit the field that shows for this taxonomy

* Rewrite the output and select "output this field as a link"
    * Choose the path to be "catalog/\[name\]" and select to convert spaces to dashes
3. Create a new view: admin/structure/views/add

* Call this view "Catalog - Products"
    * Change name to "Catalog" and url to "catalog"
    * Show "Content" of type "Product Display"
4. Edit the view by doing the following:

* Change the path to "catalog/%/%/%"
    * Add a contextual filter for all three Taxonomy Vocabulary Fields that you added in Preflight
    * Add a relationship for all three Taxonomy Vocabulary Fields that you added in Preflight
    * Call this display "Products"
5. Add a new page

* Change the path to "catalog/%/%"
    * Change the name of the display to "Level 3"
    * Remove the Level 3 contextual filter FOR THIS PAGE ONLY
    * Change the Content Format to "Fields" FOR THIS PAGE ONLY
    * Remove the title field and add a Taxonomy term name field
    * Change the relationship to be level 3 relationship
    * Modify the output of the taxonomy term name field to output a link to "catalog/%1/%2/\[name\]"
    * Check the "Convert spaces to dashes" checkbox
6. Add a page

* Path should be "catalog/%"
    * Change Display to be called "Level 2"
    * Remove Level 3 and Level 2 contextual filters FOR THIS PAGE ONLY
    * Change Display format to Fields FOR THIS PAGE ONLY
    * Modify the taxonomy term name relationship to be Level 2
    * Modify the output of the taxonomy term name field to output a link to "catalog/%1/\[name\]"
    * Check the "Convert spaces to dashes" checkbox
7. Profit!
> 0 votes

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


# Question
Title: Using the Big Pipe approach for listing pages that are driven by Solr Index
We are working on a website where we might end up having thousands/lakhs of nodes. So we are planning on using Apache Solr for the listing pages as well.

Having researched a little bit about Big Pipe I was curious if we can use the Big Pipe approach for listing pages that are driven by Solr Index and if Drupal 8 Search/Solr module already supports it.

# Answer
> 1 votes
What exactly do you want to achieve?

That you can scroll endlessly through your nodes and don't have to click on pager links?

That's not related to the big pipe stuff.

Instead, you'll need a views pager plugin for that, e.g. https://www.drupal.org/project/views\_infinite\_scroll. There is a Drupal 8 version but I haven't used it yet, so I don't know if it's stable.

---
Tags: 8, performance, search
---


# Question
Title: Version of Drupal is no longer supported [Using the latest 7.42 release]. After automatic update
I use Drupal with Commerce Kickstarter profile installed. After automatic update from Installatron in my Direct Panel i get an error of unsupported Drupal Core version:

There's no way to make update using Drush or Installatron from that state.

The only way to make it work, that I have found, is to revert to the backup before update. Can anyone help me to understand what's happening, and why Installatron updates to the 7.42 version (7.41 -\> 7.42) while Drupal Report state of 7.41 v. states that it is up-to-date?

# Answer
You updated Drupal core outside of updating the entire distribution. You're seeing this message because of the Distribution Update module and having upgraded outside of the distribution.

On that note, CK 2.32 uses Drupal 7.41. I will roll CK 2.33 with 7.42
> 3 votes

---
Tags: commerce, updating
---


# Question
Title: Is there any way to add the social medial buttons in a field?
I have made the field using field collection which is collection of 7 fields and the 8th field I would like to add as strip of social media buttons (like easy social module).

So when the entire content is displayed, below each set of field collections the social media button appears.

I searched and found that all social modules can be attached to content type which adds at the top of content or bottom. But is there a way where it can be added in-between the text or using CKeditor, the above issue can be solved?

# Answer
You can use the Link icon module.

> The Link icon module is a simple link field formatter to create icon classes based on a predefined set of link titles.

Or the Social field module

> The Social field module provides a field that allows you to collect links to social network profiles like facebook, twitter, googleplus, linkedin, etc. Links are shown as icons. Social field links are validated according to the patterns inserted in the module configuration.
> 4 votes

---
Tags: 7, entities
---


# Question
Title: How can I make content type appear as a table?
How can I make content type appear as a table each time I add content through it or its easier to make it in Views?

I am trying to make a website for students and each students will see some numbers and statistics only for him (absence, degrees, home works, etc). So how can I make a table in specific content type to fill the data instead of making a table for each student?

# Answer
> 2 votes
Use the Views module to show all your Students in a view and then with the help of the Views link area module create a link to Create Students.

> The Link Area module provides an "area plugin" for Views 3. It allows customized links to be placed in the header, footer, or empty text of any view.
>
> The obvious use case is to create a list of all nodes of type "foo" and then add a header link to the node/add/foo page. By making it a real link rather than just a blob of HTML in a header text area it gets all of the special handling and clean URL friendliness and base-path portability that any Drupal link gets.

# Answer
> 1 votes
# Option 1

Use the Views module to create a table (list) of all relevant data about your students. Then use the Editable Views module for inline editing. Some more details about this module (from its project page):

> Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.

Also, if you're going to display the **block view** on the user page of each student (ex: /user/10), you need to add (under Advanced) a **CONTEXTUAL FILTER** of **user: uid**. Then select default value. Type: User ID from URL.

# Option 2

Use the jEditable inline content editing module. Some more details about this module (from its project page):

> The jEditable module provides integration between Drupal's CCK module and the excellent jQuery plugin, jEditable. It is implemented as a CCK formatter, which makes inline editing possible through regular node displays, Panels, Views, or anywhere else you can place a CCK field.
>
> Currently supported features are "click to edit" functions for text fields, number fields, date fields, node reference fields and workflow transitions.
>
> So what is this good for? it provides a very quick and easy way to update the things they need to change without having to edit specific fields without having to switch to the full-blown node editor.
>
> It is with Views integration that jEditable really comes into its own. It allows users to edit many nodes at the same time, e.g. if the same field must be updated for many nodes.

Attention though if you'd go for this option 2: this module only has a DEV version fpr D7 (their is an official version for D6), and its last commit is from 3 years ago. So if I was to decide, I'd only go for option 2 if option 1 wouldn't fit.

---
Tags: views
---