title: Autopost from Drupal to Pinterest?

text:
# Question
Title: Autopost from Drupal to Pinterest?
Is there a way to autopost images that are inside nodes from Drupal to Pinterest?

# Answer
> 1 votes
You could set something like this up, by using Rules+Mime Mail+IFTTT.

1. Set up a recipe in IFTTT that
2. Configure Rules to send an email on an appropriate event, e.g. node updated/created
    * You need to use the Mime Mail to get the option to add attachments to your outgoing email
    * Check out this video for further information: Learn Drupal - Send email with attachments via Rules
    * You may need to configure your Drupal instance to use SMTP authentication on yor outgoing server to make it work with IFTTT. The PHPMailer module will probably help you with this.

Hope this helps, good luck!

---
Tags: nodes, media
---


# Question
Title: Serving the CSS and JavaScript files of the Bootstrap theme locally
I have installed bootstrap theme on drupal 8 and instead of using CDN provider, I'd like to load my bootstrap files locally for offline intranet usage.

Does anyone knows where should I put my bootstrap css & js files to in order to achieve this? Are there any instructions I can follow to achieve this?

Thanks

# Answer
You need Bootstrap Library module.

Quote:

> 1. Download Boostrap files on /libraries/bootstrap (you\`ll have to create "libraries" folder in Dr8 install directory).
> 2. Then go to example.com/admin/config/development/bootstrap\_library -configure on which pages you want to load the libraries (by default everything but admin/\*).
> 3. Configure on which themes you want to load the libraries.
> 4. Drink some champagne coffee.
> 1 votes

---
Tags: 8, theming
---


title: How to format the display of a node?

text:
# Question
Title: How to format the display of a node?
I have contributors who have a vast range of skills and experience, who will have permission to post on my site. I want them their content to be displayed in the same way.

I want the user to be able to upload a single image and write some text in WYSIWYG and for it to publish with the picture at a pre-formatted width (let's say 40%) and for the text to wrap around it, like you would expect on a web page.

I imagine that I might not be able to create this as a content type and will have to use a webform, but I am still not convinced.

# Answer
> 1 votes
> Yes, that is how I envisage the end result, but I am looking for a solution to allow the node author to drop the picture into an input field and let Drupal deal with the float.

All you have to do is create a template file for your content type. Then add a class or an id for your image field. (copy the node.tpl.php file and paste, rename the copy to node--\[your content type name\].tpl.php such as node--articles.tpl.php) Then add this line, you will also need to print all the other fields you want to see.

Example `<div id="floated"><?php print render($content['field_image_example']); ?></div>`

So when someone view's the page, your image will automatically be wrapped inside floated.

(above answer assumes you're using Drupal 7)

### Template file

```
<div id="example">
  <div id="floated"><?php print render($content['field_image_example']); ?></div>
  <?php print render($content['body']); ?>
</div>

```

### CSS

```
#example{
    width: 400px;
    background: yellow;
}
#floated img{
    float: left;
    width: 150px;
    background: red;
}

```

---

If you want an easier solution, less advanced knowledge needed, then use Panels which will let you add a class to your image.

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Panels Tutorials

# Answer
> 0 votes
This sounds like a perfect fit for the Display Suite module. Quote from its project page:

> Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
>
> Watch a screencast to see it all in action!

And I don't see any reason why you can't use a content type for this.

---
Tags: 7, nodes
---


# Question
Title: How to print a message when a Pane is empty?
I've rewritten the node pages on my website with a Panel page (using *node\_edit*) and added the node's comments as a Pane. When no comments have been published yet, the Pane is hidden. However, I'd like to still display the Pane's title and a sentence underneath that says something like: *Be the first to react.*

I already have a template `panels-pane--node-comments.tpl.php` and added some lines under `if(!$content}{print t('Be the first to react.');}`, but as the Pane isn't displayed, the template isn't activated. What should I do?

I know that I could create a View that shows all the node's comments and set a value when there aren't any, but maybe that's overkill?

# Answer
> 4 votes
Create a new pane with that text and set a visibility rule on it - there should be an existing rule that you can use. If not a ctools rule plugin is pretty simple to write and you can have that rule plugin check to see if comment count is 0.

# Answer
> 0 votes
Add another pane (text area holds the string) to be displayed if the comment count equals 0.

---
Tags: 7, panels, comments
---


# Question
Title: Headless Drupal for managing multilanguage resources for Web/Android/IOS apps?
A company has content in 10 languages and 3 channels (web, ios, android). It creates a lot of overhead related to translation (external translation company has to be managed, translations sent etc.). Currently there's a dedicated tool to manage translation resources (basically a spreadsheet of strings with key name and values in up to 10 translations) and sometimes global variables (eg. user name) interpolated within. Potentially hundreds of them.

I'm considering using Drupal 8 as a single place to manage both rich content (articles) and low level UI strings. Additionally it would exposed a REST API for these clients. I'm not too concerned with the typical articles, but I want to make sure that working with these low level internationalised strings will be convenient in Drupal.

Some specific requirements are listed below:

1) structure strings hierarchically to allow easy identification of relevant app section by translators:

channel1 (eg ios) |--section 1 (eg. screen or step) |---key 1 (eg. en:confirm fr: confirmer de: ... ) |---key 2

2) allow mass exporting of keys via API within whole section or full channel using single request for performance (in some cases such a bundle would be converted to static resources specific for given platform). Graphql would be great here, any ideas on how to do it generically with REST API (to be able to fetch data hierarchically, either on leaf nodes or more aggregated on higher nodes).

3) Allow editors to search by key or by value in any language.

4) integrate with translation agencies APIs

5) Allow storing multiple versions / workflow states at the same time (published / new keys just added to specific app and waiting for translation / translation awaiting approval). Ideally tag specific versions to mirror various parallel development branches and allow fetching the individual key/ the whole set via API for specific branch for preview purposes.

6) Efficiently edit multiple keys at once in a single screen grid-like manner, rather than having to click x times to switch from one to another. Switching between language values should be really convenient.

I'd really love to know your opinions around how would you model this kind of content, eg/. each key separate entity? or section = entity and key = field? use taxonomy for categorisation? What if I want to store additional data about section, eg. Screenshot - with taxonomy it wouldn't be versioned. Wouldn't using CMS that stores content items in a tree out of the box make more sense?

Also it would be fantastic to get some ideas around whether any additional modules would be useful here (I'm thinking about Drupal 8) and what kind of Admin UI would you expose to manage it (built-in? custom?).

Also there's a key question lurking behind - do you think using Drupal for this is a good idea at all?

Thanks for any suggestions!

# Answer
> 1 votes
**Use** **.po** files that drupal uses for translations and sets it under **sites/default/files/translations**.

**Build** a custom module that manage the .po files status as yo need above and move it to **sites/default/files/translations** folder if approved, assume you have created another folders to hold not approved files.

**Fetching** any content from drupal will be automatically translated to the language you set by changing the path prefix for example (/en, /fr, /de if you used that method for detection).

**Editing** the translation strings in single click yo have to read the file and display it in a form for each record as a text field and rewrite the file after submit.

Hope that helps

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


# Question
Title: How do I use the value of a JavaScript variable in a module?
I need to use the value of a JavaScript variable in a module.
For example, I am getting a `city = 'delhi'` in a JavaScript file, and I need to use this value in a module showing a form.

# Answer
> 0 votes
You could send that value to a callback function in your .module file using AJAX, an example to do that stuff in forms see that tutorial Ajaxify form fields

And you could send any value to js variable see sending-a-javascript-variable-to-drupal

---
Tags: 7, javascript
---


# Question
Title: How to force the display of an empty field in panels for an editable field?
I can't seem to force an empty field to display so that it can be edited with editable fields. I installed the Empty fields module which adds an option in the pane settings but still no luck.

Has anyone had success with this?

Edit: *Form content* with added submit buttons work, but *Page Content* is far more user friendly.

# Answer
> 1 votes
In your `/sites/all/theme/YourTheme/template.php` file, you could try using

```
function YourThemeName_preprocess_content_field(&$variables) {

    if (!isset($variables['field_name']) {
    $variables['field_name'] = ' ';
  }
}

```

but I don't know if the empty `' '` will show.

---
Tags: entities, panels
---


# Question
Title: How to create a chart from simple data without using the Views aggregation feature?
I am trying to create a chart from really simple data. I am using the highcharts library and the Visualization API module and Views. It seems like the only type of graphs that I see examples of on the Internet involve aggregation. For example, someone wants to find the number of taxonomy terms used in the nodes of a particular content type and they use a pie chart to show the percentage (https://www.youtube.com/watch?v=ot2cFQVgzfA&spfreload=1).

The type of data I am trying to visualize is something like this.

```
  Year   Products
+------+----------+
| 2015 +    78    +
+------+----------+
| 2014 +    74    +
+------+----------+
| 2013 +   123    +
+------+----------+
| 2012 +   106    +
+------+----------+
| 2011 +    59    +
+------+----------+
|  ... +    ...   +

```

I want my x-axis to be Year and my y-axis to be Sales. My content type has each of these fields. In views I am only including the years field and the sales field, which are both integers.

If I view the data as an HTML Grid I see this at the bottom of the views page:

```
Title
Test

Content
2015
78

2014
74

2013
123

2012
106

2011
59

```

So it looks like view is showing both fields. But when I use Visualization (Highcharts) - Line Chart instead of HTML Grid I get:

The query produced by views is:

```
SELECT TOP(10) node.[nid] AS [nid], node.[created] AS [node_created], 'node' AS field_data_field_year_node_entity_type, 'node' AS field_data_field_products_node_entity_type
FROM
{node} node
WHERE ( (( ([node].[status] = '1') AND ([node].[type] IN  ('year')) )) )
ORDER BY node_created DESC

```

This makes me think views cannot do a JOIN to get the results from both the node and the product field tables. Instead it is using node as a text value, not an integer, so the chart shows values of zero. Interestingly in views the HTML Chart format can get the values, just not the Visualization format.

How can I create a simple chart based on two columns of data using Highcharts and Visualization?

Here is the export of my actual view (some field names are different than my example):

```
$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Test';
$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'] = 'Test';
$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'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'field_year' => 'field_year',
  'field_agricultural_related_produ' => 'field_agricultural_related_produ',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'field_year' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_agricultural_related_produ' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Year */
$handler->display->display_options['fields']['field_year']['id'] = 'field_year';
$handler->display->display_options['fields']['field_year']['table'] = 'field_data_field_year';
$handler->display->display_options['fields']['field_year']['field'] = 'field_year';
$handler->display->display_options['fields']['field_year']['label'] = '';
$handler->display->display_options['fields']['field_year']['element_type'] = '0';
$handler->display->display_options['fields']['field_year']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_year']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_year']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_year']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
  'date_conditional_display_field' => '',
  'date_conditional_display_pre_text' => '',
  'date_conditional_display_post_text' => '',
  'linked_field' => array(
    'linked' => 0,
    'destination' => '',
    'advanced' => array(
      'title' => '',
      'target' => '',
      'class' => '',
      'rel' => '',
      'text' => '',
    ),
  ),
);
$handler->display->display_options['fields']['field_year']['field_api_classes'] = TRUE;
/* Field: Content: Products */
$handler->display->display_options['fields']['field_agricultural_related_produ']['id'] = 'field_agricultural_related_produ';
$handler->display->display_options['fields']['field_agricultural_related_produ']['table'] = 'field_data_field_agricultural_related_produ';
$handler->display->display_options['fields']['field_agricultural_related_produ']['field'] = 'field_agricultural_related_produ';
$handler->display->display_options['fields']['field_agricultural_related_produ']['label'] = '';
$handler->display->display_options['fields']['field_agricultural_related_produ']['element_type'] = '0';
$handler->display->display_options['fields']['field_agricultural_related_produ']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_agricultural_related_produ']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_agricultural_related_produ']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_agricultural_related_produ']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
  'date_conditional_display_field' => '',
  'date_conditional_display_pre_text' => '',
  'date_conditional_display_post_text' => '',
  'linked_field' => array(
    'linked' => 0,
    'destination' => '',
    'advanced' => array(
      'title' => '',
      'target' => '',
      'class' => '',
      'rel' => '',
      'text' => '',
    ),
  ),
);
$handler->display->display_options['fields']['field_agricultural_related_produ']['field_api_classes'] = TRUE;
/* 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';
/* 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(
  'year' => 'year',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'testvisualization';

```

# Answer
> 3 votes
# Part 1: From the Charts documentation

The tabular data for which you're trying to create a chart looks pretty similar to the tabular data of this variation (with it's corresponding ***area chart*** below it):

The above screenprint is from Preview 4: Area chart created with the views UI, which was created using the Charts module.

Preview 3 of that same community documentation page has another sample which shows a pie chart (created with either Google Charts or HighCharts as charting engine, which looks like so:

So if you're willing to consider using the Charts module it should be pretty forward to get this to work. If needed refer to its Community documentation for (way) more details.

If you still can't get it to work, then try the "***bonus tip***" mentioned in Steps to create charts using the views UI (= first create a tabular version of the data you want to chart, to make sure that the input for creating the chart is actually correct). That may help to refine your view before actually creating the chart.

# Part 2: Online Charts demonstration

### Example 1

Have a look at Single chart, not attached to a table, and without aggregation. Here is a quote from it:

> The chart below (created using the "charts" module) shows all nodes of content type "Article", which has 2 fields with these "machine names" (+ values):
>
> * "`field_optionlist`" (with some select list values, such as the "year")
> * "`field_free_format_text`" (assumed to contain some numeric values)

I trust you agree it looks pretty close (identical?) to the chart you're trying to create. And in this case it does not (repeat: **not**) use any views aggregation facilities.

Here is the exported view that is used to create this (example 1) chart:

```
$view = new view();
$view->name = 'visualization_no_aggregation_ex1;
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Visualization no aggregation example1';
$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'] = 'Single chart, not attached to a table, and without aggregation';
$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'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'body';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'body' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'body' => '#2f7ed8',
  'field_free_format_text' => '#233a99',
);
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'The chart below (created using the "charts" module) shows all nodes of content type "Article", which has 2 fields with these "machine names" (+ values):

- "field_optionlist" (with some select list values, such as the "year")
- "field_free_format_text" (assumed to contain some numeric values)';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
/* Field: Content: Free Format Text */
$handler->display->display_options['fields']['field_free_format_text']['id'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['table'] = 'field_data_field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['field'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['label'] = 'Products';
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* 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';
/* 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',
);
/* Filter criterion: Content: OptionList (field_optionlist) */
$handler->display->display_options['filters']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['filters']['field_optionlist_value']['field'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['value'] = array(
  13 => '13',
  14 => '14',
  15 => '15',
);

/* Display: Chart */
$handler = $view->new_display('page', 'Chart', 'page');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'column';
$handler->display->display_options['style_options']['xaxis_title'] = 'Year';
$handler->display->display_options['style_options']['yaxis_title'] = 'Nr of Products';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_free_format_text' => '#7b0d49',
  'field_optionlist' => '#8bbc21',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['path'] = 'single_chart_with_no_aggregation_not_attached_to_table';

```

### Example 2

But wait, there is more ... i.e. another example. Actually a slightly enhanced version of the previous one. Have a look at Table with attached charts, and without aggregation. It's similar to the previous example, but on the same page it also includes that tabular view of the data in the chart, and it actually includes 2 variations of such chart (a line chart and a column chart).

Here is the exported view that is used to create this (example 2) chart:

```
$view = new view();
$view->name = 'visualization_no_aggregation_ex2';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Visualization no aggregation ex2';
$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'] = 'Table with attached charts, and without aggregation';
$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'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'body';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'body' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'body' => '#2f7ed8',
  'field_free_format_text' => '#233a99',
);
/* Footer: Global: Text area */
$handler->display->display_options['footer']['area']['id'] = 'area';
$handler->display->display_options['footer']['area']['table'] = 'views';
$handler->display->display_options['footer']['area']['field'] = 'area';
$handler->display->display_options['footer']['area']['content'] = 'The above table shows all nodes of content type "Article", which has 2 fields with these "machine" names (and their values):
- field_optionlist (with some select list values, such as the "year")
- field_free_format_text (assumed to contain some numeric values)';
$handler->display->display_options['footer']['area']['format'] = 'filtered_html';
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Field: Content: Free Format Text */
$handler->display->display_options['fields']['field_free_format_text']['id'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['table'] = 'field_data_field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['field'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['label'] = 'Products';
/* Sort criterion: Content: OptionList (field_optionlist) */
$handler->display->display_options['sorts']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['sorts']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['sorts']['field_optionlist_value']['field'] = 'field_optionlist_value';
/* 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',
);
/* Filter criterion: Content: Free Format Text (field_free_format_text) */
$handler->display->display_options['filters']['field_free_format_text_value']['id'] = 'field_free_format_text_value';
$handler->display->display_options['filters']['field_free_format_text_value']['table'] = 'field_data_field_free_format_text';
$handler->display->display_options['filters']['field_free_format_text_value']['field'] = 'field_free_format_text_value';
$handler->display->display_options['filters']['field_free_format_text_value']['operator'] = 'not empty';

/* Display: Table */
$handler = $view->new_display('page', 'Table', 'page');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 'field_optionlist',
);
$handler->display->display_options['style_options']['default'] = 'field_optionlist';
$handler->display->display_options['style_options']['info'] = array(
  'field_free_format_text' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_optionlist' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['header'] = FALSE;
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'The table below shows all nodes of content type "Article", which has 2 fields with these "machine names" (+ values):

- "field_optionlist" (with some select list values, such as the "year")
- "field_free_format_text" (assumed to contain some numeric values)';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
$handler->display->display_options['defaults']['footer'] = FALSE;
$handler->display->display_options['path'] = 'table_with_attached_charts_and_no_aggregation';

/* Display: Line Chart */
$handler = $view->new_display('attachment', 'Line Chart', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_optionlist' => '#008040',
  'field_free_format_text' => '#ff8000',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['header'] = FALSE;
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'Below is a <strong>chart</strong> about the very same data (as in the table above), in the format of the "<strong>line chart</strong>", and which is "<strong>attached</strong>" to the tabular view above.';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
$handler->display->display_options['defaults']['footer'] = FALSE;
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';

/* Display: Column Chart */
$handler = $view->new_display('attachment', 'Column Chart', 'attachment_2');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'column';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_optionlist' => '#2f7ed8',
  'field_free_format_text' => '#233a99',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['header'] = FALSE;
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'Below is a <strong>yet another chart</strong> about the very same data (as in the table above), in the format of the "<strong>column chart</strong>", and which is "<strong>attached</strong>" (also) to the tabular view above.';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
$handler->display->display_options['defaults']['footer'] = FALSE;
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';

```

**For both examples above** (the exported views): these are the changes you need to make before you'll be able to successfully import those views in your environment:

1. Adapt the machine names of the 2 field names to match your field names (which I saw in your exported view), ie:

* change `field_optionlist` to `field_year`.
    * change `field_free_format_text` to `field_agricultural_related_produ`.
2. Adapt the content type's machine name from `article` to `year` (that's your machine name I saw in your exported view).
3. Pretty sure you do want to delete (remove) the line with `/* Filter criterion: Content: OptionList (field_optionlist) */`, and 8 lines following that line containing values like 13, 14 and 15 (I added that extra filter to limit my results to only 3 relevant "articles").

Disclosure: I'm a co-maintainer of the Charts module.

---
Tags: 7, views, entities, charts
---


title: Store template in module

text:
# Question
Title: Store template in module
I want to store a template for my content-type in a module. This module provides the content-type (via features). My template *"node--my-content-type.html.twig"* should be in this module, too. Not in the Themes templates/ folder.

I know there are some related questions yet. I think I got the first step already; Drupal is recognizing my template and is outputing its contents.

In Drupal 7 the approach was made with something like this:

```
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
  'node__my_content_type_machine_name' => array(
      'render element' => 'elements',
      'template' => 'templates/node--my-content-typee-machine-name',
    )
  );
}

```

Drupal 8 recognizes the template when I change this a bit.

```
'template' => 'node--my-content-type-machine-name'

```

So far so good. But now I am trying to render a field in my template and here I am failing.

```
{{ content.field_body }} ==> This is doing **nothing**

```

In my theme´s template-folder this is working fine. Any ideas?

# Answer
> 3 votes
You are missing the base hook definition. See how system\_theme() does it for block templates. So, add `'base hook' => 'node'` and it should work.

---
Tags: 8, theming
---


# Question
Title: Why is Views Nivo Slideshow block only displaying to logged in users?
I'm using the Views Nivo Slider module to create a slideshow for a couple of different sites I'm creating. The slideshow works perfectly if a user is logged in, but the block doesn't display at all when not logged in (the HTML for the block isn't even there). I thought it might be a permissions issue, so I tried giving anonymous users every permission possible, and still no luck. Any idea what might be causing this? Could it be something in my view?

# Answer
> 0 votes
I have some problems with blocks before and I always check the following, it has solved my problems so far.

* Check your block permission.
* Verify the block is assigned to a valid region setting in your template.
* Rebuild the node permissions in admin/reports/status. Before doing this, backup your database and clear the cache.
* Verify the access permission used from the view is *view published content*.

When I am working with views, I make sure the theme developer module is not enabled. I disable it, and then I clear the cache.

# Answer
> 0 votes
Check the advanced settings, and try to disable views sql rewriting.

---
Tags: views, javascript
---


# Question
Title: Term name converted to term id filter removed?
I am currently working on a view that should show all items from a content type with the given taxonomy term **name** (not id) in the url.

While this was easy to achieve in D7 (by following the answer on this question: Views contextual filters taxonomy name), I can't seem to find the validator filter now.

# Answer
> 0 votes
The predefined view "taxonomy term" might have the answer. It will always show results based on the TID. I believe that if you just add an alias to your URL, it will work just fine. You can use the module pathauto to automatically create an alias.

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


# Question
Title: D6 to D7 upgrade error Invalid datetime format Incorrect integer value
After upgrading a D6 to D7 site. I get this error when trying to save an existing page on the site that has uploaded image files, and the page will not save. If I remove the uploaded files, the error goes away and I can save the page.

> PDOException: SQLSTATE\[22007\]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'field\_upload\_inline\_image\_width' at row 1: INSERT INTO {field\_data\_field\_upload\_inline\_image} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_upload\_inline\_image\_fid, field\_upload\_inline\_image\_alt, field\_upload\_inline\_image\_title, field\_upload\_inline\_image\_width, field\_upload\_inline\_image\_height) 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\] =\> 37 \[:db\_insert\_placeholder\_2\] =\> 25955 \[:db\_insert\_placeholder\_3\] =\> page \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> 24 \[:db\_insert\_placeholder\_7\] =\> NNSA Headquarters \[:db\_insert\_placeholder\_8\] =\> \[:db\_insert\_placeholder\_9\] =\> \[:db\_insert\_placeholder\_10\] =\> ) in field\_sql\_storage\_field\_storage\_write() (line 514 of /var/www/html/upgrade2a/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

This is my table structure field\_upload\_inline\_image, do i need to alter the Type or Null column?

```
entity_type (Primary) varchar(128)  No The entity type this data is attached to
bundle varchar(128) No The field instance bundle to which this row belongs, used when deleting a field instance
deleted (Primary) tinyint(4)    No 0 A boolean indicating whether this data item has been deleted
entity_id (Primary) int(10) No The entity id this data is attached to
revision_id int(10) Yes NULL The entity revision id this data is attached to, or NULL if the entity type is not versioned
language (Primary) varchar(32)  No The language for this data item.
delta (Primary) int(10) No The sequence number for this data item, used for multi-value fields
field_upload_inline_image_fid int(10)   Yes NULL The file_managed.fid being referenced in this field.
field_upload_inline_image_alt varchar(512)  Yes NULL Alternative image text, for the image’s ’alt’ attribute.
field_upload_inline_image_title varchar(1024)   Yes NULL Image title text, for the image’s ’title’ attribute.
field_upload_inline_image_width int(10) Yes NULL The width of the image in pixels.
field_upload_inline_image_height int(10)    Yes NULL

```

I'm using Media 7.x-1.5 Bundled with File entity 7.x-1.5. I am not using UUID module. maybe I need to then I will need the file\_managed table is missing the uuid column

# Answer
> 2 votes
I should have posted the answer here instead, it may help someone. This is fixed. I had missing images in the /sites/default/files/ folder. This was a upgraded d6 to d7 site with 4000 nodes and many images. I did not have the latest images in my files folder. So saving a node with uploaded cck field images threw this error.

---
Tags: 7, database, upgrading
---


# Question
Title: URL Link to Calendar Month view from Existing View
I have a page with some global header text. The page lists some events in a tabular format. I'd like to add a link (url) to my calendar within the text. I've tried to code a "\<a href\>" tag with what I thought was an appropriate url, but, I get the following:

> Warning: Creating default object from empty value in calendar\_plugin\_row-\>pre\_render() (line 312 of /home3/hartfos4/public\_html/mysitename/sites/all/modules/calendar/includes/calendar\_plugin\_row.inc).

followed by:

> 'calendar\_plugin\_style: A date argument is required when using the calendar style, but it is missing or is not using the default date.' in calendar\_plugin\_style-\>render() (line 238 of /home3/hartfos4/public\_html/mysitename/sites/all/modules/calendar/includes/calendar\_plugin\_style.inc).

Is there any way to compose a url to link to the calendar month?

# Answer
I was able to resolve this. I was trying to redirect to a second calendar from the global header text of another calendar. I took a closer look at the second calendar and noticed that it did not have a default date in the **contextual filter**. It may have gotten deleted after the fact. I deleted the second calendar view and recreated it according to required specifications. I then edited the first calendar's global header text to use "\<a href=\>" and it successfully redirected to the second calendar.
> 0 votes

---
Tags: uri, datetime
---


# Question
Title: How to hide breadcumbs on the front page?
I would like to disable breadcrumbs on my home page and I don't know of any easy way to do this so I was going to just display:none the breadcrumbs class.

Suggestions welcome, thank you!

# Answer
Assuming you are using D7. There are a number ways to achieve it. I am providing three methods here.

**Contributed module**. The easiest one is to use "Disable Breadcrumbs" module.

**Theme Overide**. If you think it is overkill, don't want to use that module, you can also implement the preprocess html hook to remove breadcrumb like this:

```
/**
 * Implements template_preprocess_html()
 */
function THEMENAME_preprocess_html(&$variables) {
  if ($variables['is_front']) {
    // kill breadcrumb, set to empty array
    drupal_set_breadcrumb(array());
  }
}

```

**Custom Module.** You can also done this in your custom module by implementing hook\_page\_alter

```
/**
 * Implements hook_page_alter().
 */
function MODULENAME_page_alter(&$page) {
  if (in_array('front', $page['#theme_wrappers'])) {
    // kill breadcrumb, set to empty array
    drupal_set_breadcrumb(array());
  }
}

```
> 13 votes

# Answer
You add a page-front.tpl.php to your theme (duplicating page.tpl.php) and than remove codes that prints breadcrumbrs. Or, in page.tpl.php, add some "if conditions" to display breadcrumbs everywehre except homepage.
> 6 votes

# Answer
Well you can target front-page elements specifically by using the .front css class, which is added to the body by almost all Drupal themes. If you have the element in a block, you can also control its visibility by setting it visible to everything but the `<front>` token.

I'm sure there's a programmatic way to solve this question better, however, with this solution you won't have to delve in the code.
> 3 votes

# Answer
The good way to do it: themes/YOURTHEME/template.php

```
function YOURTHEME_breadcrumb($variables){
    if(drupal_is_front_page()){
        return false;
    }
}

```
> 0 votes

# Answer
I used for fix the problem the hook\_page\_alter.

In my case, i hould disable breadcrumb for specific page according path

```
function mymodule_home_page_alter(&$page) {
  if(current_path() == "my_url_path"){
    drupal_set_breadcrumb(array());
  }
}

```
> 0 votes

# Answer
I usually hide it with CSS.

```
.breadcrumb {
    display: none;
}

```

Works great for me.
> 0 votes

---
Tags: theming
---


# Question
Title: How can I create a custom form settings to my custom field formatter?
I need to add form settings to my custom display format, can you provide me with an example?

To be clear I just want to add some fields to the format settings form.

# Answer
> 3 votes
Whenever you need to figure out how something works, look at examples that already do what you want. In your case, that's the ImageFormatter plugin.

Specifically, you are looking for the methods `defaultSettings()`, `settingsForm()` and `settingsSummary()`. Implement them, define the form for you settings, specificy default settings and for improved user experience, implement the summary method to give users a short summary of the current settings.

That's all, in viewElements(); you can then access your settings with getSetting().

---
Tags: entities, 8
---


# Question
Title: Render a content type bundle in a custom module template
How do I render/display an existing content type form in a custom twig template for a custom module in drupal 8?

I've tried using getform() function, but I dont think that is the correct function.

I have set a preprocessor variable in my custom module and can see the variable on my custom page via the twig syntax {{dump()}}. Just for simplicity, I would like to know, which class function will allow me to simply render the content type 'article' form , once I can see the article form, i can change it to my custom made form.

# Answer
I'm not sure what you're exactly asking, but there are various modules that allow you to display entity forms in a block, for example Entityform block (Disclaimer, maintained by me).

Either use that, you can use form modes and/or form alters to then customize the form, or just look at the code to see how to do it.

One thing that this module doesn't support yet is editing existing entities, I'd love to add support for that using the plugin context system.
> 0 votes

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


# Question
Title: How can I handle files in a cloud when when the site is configured as multi-site?
I want to run Drupal from a cloud and I am trying to figure out the design of the file system for multi-site setup.

In the cloud, there are multiple servers hidden under the load balancer which serve content from a single database (a service that handles replication on its own) and using central storage for user or Drupal data.

I solved the problem for user data, mostly images attached to nodes or uploaded via fields, but I'm stuck on how to handle files like compiled Twig templates, configuration files, services file, and similar files.

Once a new server instance is created, it will fetch the code from a Git repository. The user data is handled via a stream wrapper (and CDN); no action is needed.

How should I handle the system files?

The more static files like the settings.php and services.yml files could be potentially stored in some "remote" storage and fetched from there, or they could be dynamically generated based on data stored in a special database.
What about the other files (template and configuration files, for example)?
Would something like a fast cache be a good design?

A Redis database could hold the current files; each instance could either fetch them manually or serve them directly. Once an instance flushes the cache, this would be immediately "synchronized" to all the instances, in second scenario. For first scenario, there could be timestamp value for latest change that each instance would check on each page load to re-fetch the files when necessary.

# Answer
This is why platform as a service solutions like platform.sh, getpantheon and others are so popular. They provide solutions to problems like this.

If you don't want to use them, then you can still learn from them. In this case, the answer is environment variables. You commit a settings.php file that reads the configuration from environment variables, e.g. which database server/solr/redis/... to connect to, configuration overrides and so on.

platform.sh also automatically generates a settings.local.php that some configuration built in, but they move more and more towards just documenting how to do it yourself as that's more flexible. See their example setups and specifically, settings.php of the 8.x-composer approach.

How to actually get those environment in place yourself is a non-drupal related question that you'll have better chances for good answers elsewhere. It also depends a lot on how you actually instrument those cloud servers.

So far, I've haven't had the need for customized services.yml files, all I do sometimes (beside having a services.local.yml, just like settings.local.php), is to dynamically load additional files, e.g. with the redis configuration. If you need that, you can either generate those files or you can implement a site specific service provider that generates the service/parameter definitions dynamically.

For twig, while they are generated PHP files, unless you do something really weird, they are based only on the static .html.twig files that you are deploying. So, you do not need to share them between your servers, you just need a deployment step that deletes the files on all servers when you deploy new code. Or, you could write a script that pre-generates them, then you less of a performance hit when re-deploying. Haven't seen a script yet for Drupal that does that, there might already be a question about that here.

The container is in cache, by default in the database, with a bit of configuration you can also have it in Redis or Memcache, see https://github.com/md-systems/redis/issues/12.

I'm not aware of any other files that need to be maintained like this. (other than public or other stream wrappers, which you apparently have already solved).
> 4 votes

---
Tags: 8, files
---


# Question
Title: $form_state['values'] partial empty, while $form_state['input'] is filled
I would like extend an existing (altered) form. For this case, I created a new form with the Form API:

```
function my_new_form($form, &$form_state) {
  ...
}

```

In the next step, I get the existing form, which one I would like to extend:

```
function my_new_form($form, &$form_state) {
  $form = drupal_get_form('my_form');
}

```

Now, I extended the form with fields like this :

```
function my_new_form($form, &$form_state) {
  $form = drupal_get_form('my_form');

  $form['foo'] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('foo bar'),
  );

  // and so on..

  return $form;
}

```

In my Template, I display the form:

```
print drupal_render(drupal_get_form('my_new_form'));

```

This works correctly, but after submitting the form, the values from the form from which I extend in the `$form_state['values']` are empty. But in `$form_state['input']` they are existing.

Do you have any idea what I'm doing wrong?

# Answer
> 3 votes
The reason drupal\_get\_form() doesn't work in your code is that it contains the following code.

```
  $form_state = array();

  $args = func_get_args();
  // Remove $form_id from the arguments.
  array_shift($args);
  $form_state['build_info']['args'] = $args;

  return drupal_build_form($form_id, $form_state);

```

What the function passes to the form builder is a newly created `$form_state` array, not the one being passed to your form builder.

Using drupal\_build\_form() is not working because the function is retrieving the form from the cache. (See the comments before the code.)

```
  // If the incoming input contains a form_build_id, we'll check the cache for a
  // copy of the form in question. If it's there, we don't have to rebuild the
  // form to proceed. In addition, if there is stored form_state data from a
  // previous step, we'll retrieve it so it can be passed on to the form
  // processing code.
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  if ($check_cache) {
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  }

```

You can implement hook\_form\_alter(), hook\_form\_FORM\_ID\_alter(), or hook\_form\_BASE\_FORM\_ID\_alter() for a form that has been already altered.

About calling `drupal_get_form()` from a template file, see Be careful with drupal\_get\_form() in theme layer. As reported in that blog article, you would have problems with the validation error messages which will not appear.

# Answer
> 2 votes
I can't imagine calling `drupal_get_form()` form inside another form function will produce very good results. If you want to alter an existing form, even one you've declared yourself, you should use `hook_form_alter()` instead:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    $form['foo'] = array(
      '#type' => 'textfield',
      '#size' => 30,
      '#title' => t('foo bar'),
    );
  }
}

```

Doing it that way you should find all of the expected values in the `$form_state` array when the form is submitted/validated.

# Answer
> 0 votes
Usually all the game about population `$form_state['values']` from `$form_state['input']` is concluded with correct setting `$form['some_input']['#tree']` parameter, which affects form builder to fill the `$form['some_input']['#parents']`. So `$form['some_input']['#parents']` has the direct influence of correct populating `$form_state['input']` into `$form_state['values']` In most cases `#tree = FALSE` to all elements (no matter how deep they are nested) is enought for correct populating. Here you can read some about this https://www.drupal.org/node/48643 This "problem" is not clear to me totally, i still get results with experiments :)

For nested elements is better to set #tree = TRUE to thier direct parent only. For example `$from['users_list']['action_selected']['user_id1'] ...['user_idN']` here is `['action_selected']` must be #tree=true, and you will have in $form\_state\['values'\] grouped by \['action\_selected'\] as subarray of \['user\_idN'\] values, assuming that \['user\_idN'\] is HTML input field

---
Tags: 7, forms
---


# Question
Title: How do I check the access to every node?
I need a quick solution to restrict access to nodes based on the contents of field. I've built the skeleton of a module and managed to restrict access to a custom route. Now, the service that redirects to access check is this:

```
services:
  access_check.untitled_check:
    class: Drupal\untitled\Access\UntitledAccessCheck
    tags:
      - { name: access_check, applies_to: _access_untitled_check }

```

This only applies to routes with \_access\_untitled\_check in the requirements array.

How can I have **all nodes** checked? Can I add \_access\_untitled\_check to nodes' requirements array?

# Answer
> 3 votes
There are several ways to do *alter* or *hook* into node access. You can find out more by reading the Node Access Rights page on api.drupal.org.

Briefly node access works like this (paraphrasing from the aforementioned documentation page):

1. Users with 'bypass node access' are granted access.
2. Invoke implementations of hook\_node\_access
3. Invoke implementations of hook\_node\_grants

Finally,

> To see how to write a node access module of your own, see node\_access\_example.module.

# Answer
> 0 votes
This is the solution I found. No routes, no services, no controllers. Only `hook_node_access` as advised by @mradcliffe

```
function modulename_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $bundle = $node->bundle();
  $user = $account->id();
  $refs = $node->field_with_references->referencedEntities();

  $condition = ...

  return AccessResult::forbiddenIf( $condition );
}

```

---
Tags: 8
---


# Question
Title: What is the difference between 'Groups audience' and 'Groups content visibility' in Organic Groups Access?
I am trying to set up Organic Groups Access for an existing site where I want to add gated content. I was watching this tutorial about setting it up, and it briefly addressed it. They said that 'audience' is better for sites where you have a bunch of existing nodes. Can someone give me a more technical answer, indicating what exactly the difference is?

# Answer
Group audience = which group(s) content was posted to.

Group content visibility = who can see the posted content, only group members or all site users.

Do contact the author directly to ask them and/or let them know that the tutorial could be improved.
> 1 votes

---
Tags: organic-groups
---


title: Making File Field description required

text:
# Question
Title: Making File Field description required
My users always skip adding the "description" to the file field because they can. I tried implementing the code posted here:

How do I make Drupal File Description Field Required?

(and thank you) -- but I have a question. My users now do see a red asterisk suggesting that the description is required ... but if they do not enter a description, they may still click save and create the node ... with no description entered in the box. Any ideas on how to get this to really force the issue and require the description?

# Answer
> 0 votes
If you like you can add to the `hook_field_widget_form_alter` and then add a validation callback:

```
  $form['#validate'][] = 'my_validate_function';

```

Then create a `my_validate_function($form, &$form_state)` which contains a check on the values and calls a `form_set_error($name, $message)` if a value is wrong or missing.

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $context['form']['#validate'][] = 'my_validate_function';
  }
}

/**
 * Require description to be set.
 */
function my_validate_function($form, &$form_state) {
  if ($form_state['values']['description'] == '') {
    form_set_error('description', 'Description must not be empty.');
  }
}

```

This may need to be changed above:

```
$form_state['values']['description']

```

---
Tags: entities
---


# Question
Title: How to restore uploaded backup in Drupal 7 (public files or entire website) correctly?
When trying to restore public directory I see:

PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'temporary://cvetmagazin-2016-03-13T16-28-59.tar\__0.gz' for key 'uri': INSERT INTO {file\_managed} (uid, filename, uri, filemime, filesize, status, timestamp) 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); Array ( \[:db\_insert\_placeholder\_0\] =\> 1 \[:db\_insert\_placeholder\_1\] =\> cvetmagazin-2016-03-13T16-28-59.tar\_.gz \[:db\_insert\_placeholder\_2\] =\> temporary://cvetmagazin-2016-03-13T16-28-59.tar\__0.gz \[:db\_insert\_placeholder\_3\] =\> application/octet-stream \[:db\_insert\_placeholder\_4\] =\> 166375 \[:db\_insert\_placeholder\_5\] =\> 0 \[:db\_insert\_placeholder\_6\] =\> 1457901164 ) в функции drupal\_write\_record() (строка 7316 в файле /home/user/drupal\_fish/apps/drupal/htdocs/includes/common.inc).

However, Drupal accepts database dump without errors. How to fix that? Thanks.

# Answer
I think it's a concurrency issue when D7 makes a file object in db. try to use this modules Upload QC please let me know if it works with you.

also try to check the temp file name. and make sure tat the database is restored correctly.
> 0 votes

---
Tags: backups
---


# Question
Title: How to generate a stack trace upon errors
I am sysadmin trying to debug a Drupal site. In my server logs I can see Drupal making the same requests again and again to our Solr instance until PHP eventually runs out memory, and Apache returns a 500 error.

How can I configure Drupal to log a stack trace somewhere on the disk?

# Answer
You can use the Devel module, and select one of the "Krumo Backtrace" options it provides in its configuration page at admin/config/development/devel.

>

Make sure to visit admin/config/development/logging and select "Errors and Warnings" or "All Messages". If you have the Syslog module, or any other logging module enabled, you may need to disable it and enable the Dblog module.

>
> 19 votes

# Answer
in your drupal system in modules section under core modules their is syslog module to store log on the disk. hope it help what your looking for.
> 2 votes

# Answer
For Drupal 7 and 8, the module inspect is great for backtraces.

It can add them to files or the log in the Drupal database rather than showing them, which is useful in cases where Krumo backtrace, `ddebug_backtrace()` and other solutions that create direct on-screen output fail. That is the case for errors and exceptions happening before rendering output started.

The admin backend config area for inspect contains a nice quick reference for its usage in code.
> 2 votes

# Answer
The Trace module worked much better for my situation.

> This is a sysadmin & developer tool that adds extensive tracing facilities for Drupal hook invocations, database queries and PHP errors.
>
> Some features provided by version 1.0 this module:
>
> * Outputs trace messages to a file or the syslog (on Unix platforms).
> * Traces Drupal hook invocations with an optional filter and stack trace.
> * Traces PHP warnings and errors with an optional full stack trace.
> * Traces SQL database queries with optional filtering by query type.
> * Trace output includes microsecond-level timing information.
> * Stack traces include the function's passed arguments in PHP syntax.
> * Optional debug output includes PHP superglobals and HTTP headers.
> * Defines a hook allowing other modules to extend the trace output targets.
> 1 votes

---
Tags: debugging
---


title: How to order CKEditor plugins

text:
# Question
Title: How to order CKEditor plugins
I'm implementing CKEditor Drupal plugins using `CKEditorPluginContextualInterface` in D8.

I wander if there is a way in which I can control the order/weight of the plugins so that I could change which plugin code executes first.

# Answer
> 0 votes
Indeed, all you can do is specify the other CKEditor plugins your CKEditor plugin depends on. It is guaranteed that those are loaded first. But beyond that, there are no guarantees. Nor should there be.

So, just specify the CKEditor plugins your plugin depends on in `getDependencies()`. This ensures Drupal informs CKEditor about where those plugins live.

Then, it is up to the CKEditor plugin *itself* (i.e. the JavaScript code) to specify the necessary dependencies, CKEditor then ensures the depended plugins are loaded first.

---
Tags: 8, wysiwyg
---


# Question
Title: Service is being instantiated during installation with unknown entity type call
I have a module that defines two services. **Service A** has **service B** as dependency.

**Service B** has some dependencies, one of which is entity type manager.

In the constructor of the **service B** an entity storage is being called for entity type that is defined by this module as well

```
public function __construct(AccountProxy $user, EntityTypeManager $entity_manager, QueryFactory $entity_query) {
    $this->user = $user;
    $this->storage = $entity_manager->getStorage('entity_type_name');
    $this->query = $entity_query->get('entity_type_name');
  }

```

During installation I get error about unknown entity and the installation breaks. I have tried to backtrace the cause of this but so far it looks like everything is in order. The container is only parsing the service definitions and instantiates them when needed. What I think might be the issue is the order in which the entity definitions are processed and service definitions parsed.

I do not want to add any condition into **service B** constructor to check if installation is in progress. I think this should not be happening.

What would be a proper workaround?

# Answer
While it will require an additional call when you require it, you could just store a reference to the entity type manager only.

Especially for entity query, you must not do it like this anyway. A query object is not re-usable. You can't execute multiple queries from a single instance.

Additionally, you can simplify your dependencies if you call $storage-\>getQuery() instead of using the entity query for that (which does the same internally).
> 1 votes

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


# Question
Title: Should views search specific caching skip preprocess?
**Problem**

I have a view powered by the Search API, which uses the views inbuilt caching - "Search Specific" in order to provide better performance.

However I also run a number of theming alterations in:

`theme_preprocess_views_view_unformatted`

However this code appears to be skipped when the views caching kicks in. Is this by design or an I encountering a bug? If it's not, how have people gotten around this sort of thing before?

**Re-creation**

* Clear all caches Load page - *Code runs correctly*
* Refresh the page a number of times usually between 2 & 5
* Refresh the page - *Code is skipped*

I've been testing if the code is skipped by including:

```
function theme_preprocess_views_view(&$vars) {
  ...
  watchdog('test', 'This chunk of code has just run');
  ...
}

```

# Answer
I was misusing `theme_preprocess_views_view_unformatted`.

I'm running views caching, search specific (I think this may also apply to time specific) in order to cache the results of the view.

This caches the HTML of the view and means that the entire view creation, render and theming steps are skipped. When the view calls the search the correct HTML is returned.

However they do have to be run originally to build the cache. (For some reason it kicks in after a random number of refreshes? Perhaps there's simply a delay on creating the cache.)

I was using `watchdog` to log when the code runs and so obviously this only runs until the cache is created. This won't be an issue if everything you're doing in `theme_preprocess_views_view_unformatted` alters the HTML because that will be cached the first time it happens. However I was using it to add text to header based on the results of the view, which obviously didn't work.

This was possibly muddled by the fact that I run Varnish & Authcache on my live environment so I think this would cache the initial version (before the search cache is built) and thus stop me from re-creating the bug on my live version.

Make sure you're aware of all your caches and how they run!
> 0 votes

---
Tags: 7, views, caching, search
---


title: Views entity object sometimes missing

text:
# Question
Title: Views entity object sometimes missing
**Problem**

I'm trying to pull data from the entity objects on a views page that is rendered using Search API. I'm trying to pull the data from `hook_views_post_render`.

Views appears to sometimes load the entire entity in the path:

`$view->result[x]->_entity_properties['entity object']`

However it doesn't always. Sometimes the objects are just missing and I can't pull data from them. (They appear on flushing the cache and then disappear a couple normal browser refreshes after.)

Does anyone know why this happens? I was wondering if they were cached, but they don't appear in `$cache` or `$view` i.e.:

`hook_views_post_render ($view, $output, $cache)`

# Answer
This is because I have search specific caching enabled on the view. This is a Search API caching plugin for views which caches both the results of a query and the HTML (I think).

So when a query is repeated it returns the HTML and doesn't load the entity objects. Because that's the entire point of the cache! (In fact it skips the entire view generation, i.e. both hooks like `module_views_post_render` and `theme_preprocess_views_view`)
> 0 votes

---
Tags: 7, views, entities
---


title: write to code without prefix table name

text:
# Question
Title: write to code without prefix table name
I work on D7, My Sql database name is `dbdrupal7` and all table prefix with **abc** (abc\_block, abc\_node, ...), website work fine. I create a custom table without prefix **abc** (custom). I create a module and write to custom code.

```
$query = db_select('custom', 'c');

$query->fields('c');

$results = $query->execute();

```

...

...

Show "unexpected Error" when browse.

I not want to change table name **custom** to **abc\_custom** in database.

My question is how write correct code `db_select('custom', 'c');` without prefix.

# Answer
That behaviour is hard-coded with a `SelectQuery`; the prefix will apply to all tables, without exception, and there's no mechanism in place to override it. It happens in `SelectQuery::__toString()` if you're interested.

If you want to change that, you'll need to subclass `SelectQuery`, add a mechanism to let the class know which tables should/shouldn't be prefixed, and override the `__toString()` method to take that into account. Then you'll need your own version of `db_select()`, which uses your new custom version of the class.

All that's probably not worth the effort given that you can run an arbitrary SQL string with `db_query()`. For example, the following won't attempt to prefix `custom`:

```
db_query('SELECT * FROM custom c')

```
> 3 votes

# Answer
The "correct" way would be to treat the other tables as non-drupal databases, because they aren't (Otherwise they would be prefixed). You can see how to do this here:

How to connect to multiple databases within Drupal
> 0 votes

---
Tags: 7, database
---


# Question
Title: Implement Push Notification in my iOS App with a Drupal backend
I building an iOS App whose content is being brought from a Drupal site. It is being built in ionic/AngularJS.

I intend to implement "Push Notification" functionality in my app that whatever notification a user sends through my Drupal site is received on my app.

There is a particular module Push Notification, made specifically for this and has integration with Services, but I can't seem to figure out how I'll show the Push Notification on my app when it's sent from my Drupal site. Probably some small example?

Any help would be highly appreciated.

# Answer
> 1 votes
Three module you need to require to accomplish notification one is rules second is services and push notification modules.

On cofiguration of push notifications you need to configure APNS certificate for IOS by put on private folder and set path to configuration.

By services module you need call register and deregister push token services.

By rule module you can set action of send push notification to particular token.

# Answer
> 1 votes
Download and install the Push notification module in your Drupal site. configuration for Android:

1) Using Google Cloud Messaging set up your project in google developers console projects.

2) Enable google cloud messaging in your project(created on Google developers console).

3) And get your project's API Key from API manager.

4) Add that key in the configuration of push notification in Drupal site in Google Cloud Messaging API Key.

5) Then you can send push notifications from your Drupal site to your apps. `[configuration > Web services > Push Notifications > Send Push ]` (If you have done set up on the ionic app you can view push notifications on the mobile app directly.)

You can refer to this link

---
Tags: javascript
---


# Question
Title: How to create RSS feed for particular content type in drupal 8?
I have to create the RSS feed for particular content type and found some module and try to generate some RSS feed but I won't. If you have any idea or if anyone did this Please share with me.

# Answer
> 2 votes
Can create the views as well for generate the rss feed with following steps:

1. Enable `Serializer` and `RESTful Web Services` module, available in Drupal 8 core.
2. Create views for retrieving the contents of required content type.
3. Select the option **Provide a REST export**, present in the `REST export settings` (present at the bottom of views).
4. Configure the views as per the requirement.

Example:

---
Tags: views, feeds
---


# Question
Title: Using '#type"=>'container' to create a div wrapper around nested elements?
From my reading a render array can define a wrapper div by using the `'#type'=>'container'`. I am inserting a render array in the `page_alter` hook function in the `page_bottom` region. It appears that the container type does not work in this case. The code below does not wrap the two `#markup`elements with the div wrapper but instead outputs the `div` then the content at the same level.

```
$page['page_bottom']["notices"] = array(
  '#type' => 'container',
  '#attributes' => array(
    'id' => array('notices'),
  ),
);

$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#suffix' => "<div id='notices-placeholder'>",
  '#prefix' => '</div>',
);

$page['page_bottom']["notices"]['notices-tab'] = array(
  '#markup' => '<div class="notices-notification-tab">NOTICES  <span class="notices-count">10</span></div>',
);

```

What I want is the following.

```
<div id="notices">
    <div id="notices-placeholder"></div>
    <div  class="notices-notification-tab">NOTICES....</div>
</div>

```

What I get is the following.

```
<div id="notices"></div>
<div id="notices-placeholder"></div>
<div  class="notices-notification-tab">NOTICES....</div>

```

--- Added I did try `#children` earlier in the day and it didn't work as well. Before I left for the day I also tried with

```
$page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#suffix' => "<div id='notices-placeholder'>",
    '#markup'=>"Empty String", // added to see what it would do
    '#prefix' => '</div>',
);

```

This resulted in a completely out of sync html with the `#markup` tag being outside the `#prefix`/`#suffix`. I don't have the results on me now to post but if you try it you will see the results for your self.

# Answer
I was able to obtain what you wanted using the following code.

```
  $page['page_bottom']["notices"] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices'),
    ),
  );

  $page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => array('notices-placeholder'),
    ),
  );

  $page['page_bottom']["notices"]['notices-tab'] = array(
    '#markup' => '<div class="notices-notification-tab">NOTICES  <span class="notices-count">10</span></div>',
  );

```

The output I obtain using that code as implementation of `hook_page_alter()` is the following.

```
<div id="notices"><div id="notices-placeholder"></div><div class="notices-notification-tab">NOTICES  <span class="notices-count">10</span></div></div>

```

I tried using your code, and setting `$page['page_bottom']["notices"]['#tree']` to `TRUE`, or setting `$page['page_bottom']["notices"]['notices-placeholder']['#type']` to `'markup'`, but I always obtained the same result as you.

The only explanation I have is that, using your code, theme\_container() (the function defined as theme wrapper for the "container" element) doesn't get any value for `$element['#children']`. That would explain why the container HTML output doesn't contain any children element, as the code executed by `theme_container()` is the following one.

```
  $element = $variables['element'];

  // Special handling for form elements.
  if (isset($element['#array_parents'])) {
    // Assign an html ID.
    if (!isset($element['#attributes']['id'])) {
      $element['#attributes']['id'] = $element['#id'];
    }
    // Add the 'form-wrapper' class.
    $element['#attributes']['class'][] = 'form-wrapper';
  }

  return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';

```

### References
> 4 votes

# Answer
Change suffix and prefix

$page\['page\_bottom'\]\["notices"\]\['notices-placeholder'\] = array( '#prefix' =\> "", '#suffix' =\> '', );
> 1 votes

# Answer
you have to render the $page : return drupal\_render($page)
> -1 votes

---
Tags: theming
---


# Question
Title: Saving values using variable_set through an array
I have used `variable_set` to save one value. How can I save multiple values through an array using `variable_set`?

# Answer
> 11 votes
It's the same:

The `variable_set` function saves the variable to database serializing it. `variable_get` takes the variable from `$conf` where the variable is already unserialized.

Example:

```
$var1 = array(
 'key1' => 'value1',
 'key2' => 'value2'
);
variable_set('var1', $var1);
print_r variable_get('var1');

```

Output

```
Array
(
    [key1] => value1
    [key2] => value2
)

```

# Answer
> 1 votes
If you wand do it in the system form, you can use #tree param.

```
    $settigs = variable_get('default_settings', array(
      'setting_1' => NULL,
      'setting_2' => NULL,
    ));
    $form['default_settings'] = array(
      '#type' => 'fieldset',
      '#title' => t('Default settings'),
      '#weight' => 5,
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#tree' => TRUE
    );
    $form['default_settings']['setting_1'] = array(
      '#type' => 'textfield',
      '#title' => t('Setting 1'),
      '#default_value' => $settings['setting_1'],
      '#required' => TRUE
    );
    $form['default_settings']['setting_2'] = array(
      '#type' => 'textfield',
      '#title' => t('Setting 2'),
      '#default_value' => $settings['setting_2'],
      '#required' => TRUE
    );

```

# Answer
> 0 votes
I think best way to save array value in varible\_set(); is json. drupal\_json\_encode() and drupal\_json\_decode() function in drupal 7.

You can do something like this:-

```
$var_input = array(
 'key1' => 'value1',
 'key2' => 'value2'
);
$var_input = json_encode($var_input);  // convert to json

variable_set('var1', $var_input); // set in variable

$var_output = variable_get('var1'); // get from variable

$var_output = drupal_json_decode($var_output); // decode json

print_r($var_output);

```

Hope this help!

# Answer
> 0 votes
For `variable_set()` there isn't any difference between saving a persistent variable containing a string or an array, since it passes its `$value` parameter to `serialize()`.

```
db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

```

Eventually, what changes for you is what you do when the saved value comes from a form. To make it easier for you to save an array, you could use a form with the following structure.

```
  $options = variable_get('admin_theme', array());
  $form['admin_theme'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administration theme'),
    '#tree' => TRUE,
  );
  $form['admin_theme']['admin_theme'] = array(
    '#type' => 'select',
    '#options' => array(0 => t('Default theme')) + $theme_options,
    '#title' => t('Administration theme'),
    '#description' => t('Choose "Default theme" to always use the same theme as the rest of the site.'),
    '#default_value' => $options['admin_theme'],
  );
  $form['admin_theme']['node_admin_theme'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use the administration theme when editing or creating content'),
    '#default_value' => $options['node_admin_theme'],
  );

```

In the submission handler, you can then save the settings with `variable_set('admin_theme', $form_state['values'][admin_theme'])`.

---
Tags: configuration
---


# Question
Title: How to display the weekly view in manage availability in rooms_availability?
I installed the Rooms module, and enabled all dependencies. Now when I edit a bookable unit and when I click in "manage availability", I can edit availability per month.

But I do not want a monthly view, I want weekly view. And I want to select the availability per hours/days.

Is that possible? And is there any other way to do this? Or is there another change in the code?

# Answer
I'm not aware of a way to display a weekly view. But as per your "***... is there another change in the code ...***", it seems like it should be pretty forward to transform the 3 months view to a single month view via rooms\_three\_month\_calendar.tpl.php.

To actually do so, remove line 2 (with `class="month1"`) and line 4 (with `class="month3"`) from this part of that tpl file:

```
<div class="calendar-set clearfix">
  <div id='calendar' class="month1"></div>
  <div id='calendar1' class="month2"></div>
  <div id='calendar2' class="month3"></div>
</div>

```

After doing so, it should look like so:

```
<div class="calendar-set clearfix">
  <div id='calendar1' class="month2"></div>
</div>

```

Still not exactly a weekly view, but at least you already got rid of 2/3 of the days you don't want to see, right? And hence leaves 3 times as much space for the current month view.

**Note**: By not removing the backward / current / forward links in that tpl file, you should still be able to easily navigate to another month.
> 1 votes

---
Tags: 7, views, hooks
---


title: Taxonomy Sidebar view with Nodes

text:
# Question
Title: Taxonomy Sidebar view with Nodes
I'm building a sidebar for my taxonomy and node pages.

I've got it as

* Show (View Setup): Taxonomy Terms
* Unformatted List
* Show: Fields
* Relationship: Taxonomy term: Representative node

Fields:

* Taxonomy term: Name
* (Representative node) Content: Title

This works pretty well, each row starts with the taxonomy term name as a link and is followed by a node from that term. The trouble is, it'll only show the first node. How do I get it to display all nodes?

# Answer
> 1 votes
The Representative node relationship will show you a single representative node for your term, so that's not what you need in this case. Instead, try this:

**Relationship**: *Taxonomy term: Content with term*

Your results will now look like this:

Term A

Node 1

Term A

Node 2

Term B

Node 3 etc

Assuming this is not what you want, you can next add some grouping like this:

Under **Format: settings** set **Grouping field Nr. 1** to *Taxonomy term: Name*. Finally, in Fields, set the **Taxonomy term: Name** field to *Exclude from display*. Now you should have a list of node titles grouped by taxonomy term.

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


# Question
Title: fatal error when i want to disable apachesolr module
I see an error when i want disable apachesolr module. what should i do?

# Answer
> 2 votes
Updated:

Point from @kiamlaluno is correct, the apachesolr\_stats has apachesolr listed as a dependency. Therefore, in order to disable the apachesolr, you should first disable the apachesolr\_stats (and possibly other dependent modules).

I suspect that this issue comes from cached blocks, when I look at the trace you posted. Try to clear the cache and/or disable the apachesolr\_stats block before trying to disable the apachesolr module.

Original:

You should try to disable the apachesolr\_stats module first. If you are using drush, this would be the command:

```
drush dis -y apachesolr_stats

```

If you don't have drush, you can also use MySQL/PHPMyAdmin commands, here are some links with examples:

Disabling modules:
https://www.drupal.org/node/157632

Clearing cache:
How do I clear cache using an SQL query? \[if that answer works for you, you can upvote ;) \] https://www.drupal.org/documentation/clearing-rebuilding-cache

Good luck!

---
Tags: search
---


# Question
Title: How to display Meta tag description for Views genereated page
How to display meta tag description for Views generated page. Title is displaying by views but not description. Even I entered in Views description PFA.

Along with that I tried "Metatag Views Overview" module that gives an error when I created new meta tag.

# Answer
You need to enable the `metatag_views` module, that already comes with the Metatag bundle. Once you install it, you will see a new section on the page where you edit views, and you can update description there.

The section is called "Metatags", and there you can override the defaults for a specific view.
> 2 votes

---
Tags: 7, views, meta-tags
---


title: Add some html in a menu

text:
# Question
Title: Add some html in a menu
I try to add some html in "secondary nav".

A little bit like that :

```
    <ul>
      <li>
        <div>
          MY CUSTOM HTML
        </div>
      </li>
      <li><a>First link</a></li>
      <li><a>Second link</a></li>
    </ul>

```

(my menu is not a block).

Do you know how can it be done? By template suggestion or a function for example?

# Answer
> 2 votes
For menus that are printed by invoking `theme('links__YOUR_MENU')`, you can use the following code and place it in your theme's `template.php` file:

```
function YOUR_THEME_links__system_main_menu(&$variables) {
  // Copy here the code from theme_links() function and adjust it to your liking.
}

```

See the source for `theme_links()` here.

For menus in blocks, you can do that using `theme_menu_tree__YOUR_MENU()` override in your theme's `template.php` file. Here's example code that will work for the main menu:

```
function YOUR_THEME_menu_tree__main_menu(&$variables) {
  $your_custom_html  = '<li><div>your custom HTML</div></li>';
  return '<ul class="menu clearfix">' . $your_custom_html . $variables['tree'] . '</ul>';
}

```

This will add the content before menu links.

# Answer
> 1 votes
You can use Menu HTML module. It's the best way to allow the admin to add html to the menu item title.

---
Tags: 7, theming
---


# Question
Title: Shipping/Delivery Labels in Drupal Commerce
I've been searching for a way to print shipping/delivery labels for Drupal Commerce (drupal 7 kickstart). I'm amazed that there still seems to be no real solution to this but rather a series of hacks. I was sure this would be adequately covered or even be part of core! We could do this in Ubercart and yet it seems to have been overlooked in Drupal Commerce.

Anyway, we want to be able to print the labels to a label printer as we process each order from the admin screen. The closest 'solution' is this Print mailing address labels from a view. This isn't exactly ideal as we just need a button next to 'Shipping Address' which prints the label to the label printer.

Using the Themer Devel module it tells us we should be able to override commerce-order--backoffice.tpl.php where we were hoping to inject a print code and customise the print fields using the Print Module http://drupal.org/project/print but drupal refused to see our version of commerce-order--backoffice.tpl.php.

We just seem to be going around and around with this one trying idea after idea getting nowhere, very frustrating that this has been overlooked by Drupal Commerce.

Any ideas much appreciated. Chris

# Answer
> 1 votes
There are myriad number of ways that people want their shipping labels—some print them pre-cut sheets and other use label printers. Overall, every setup is a bit different.

Ultimately, your shipping label solution will be custom (although calling it hack is a bit much). You can use a view to create a single printable "page" (just use an argument to limit it to a single result) and then just use CSS to style it. If you're wanting to print a whole bunch of them, then leave out the argument and ensure that you're setting the proper page size and putting in your page-breaks properly.

---
Tags: commerce
---


# Question
Title: How do I create a custom field storage back end?
In Drupal the default field storage is in an SQL database. I am creating a custom field type and want it to have non-SQL storage.

In Drupal 7 there was the Field Storage API, which you could use to define your own storage back ends by implementing a module similar to the field\_sql\_storage module.

How does one do such a thing in Drupal 8?

To give an example usage, I am interested in implementing something similar to Drupal 7's hook\_field\_storage\_load() so I can have fields that load their data from files in the file system.

If it is too complex a thing to give a code example for, a point in the direction of the relevant API and/or default SQL implementation that I can reference should suffice.

# Answer
> 4 votes
Field types implement FieldStorageDefinitionInterface. In Drupal core, there is FieldStorageConfig and BaseFieldDefinition.

So if the desire is to change field storage to an arbitrary file store, then you should create an abstract class similar to BaseFieldDefinition, and have your Field Type classes extend it.

# Answer
> 2 votes
Fields don't control own storage anymore with Drupal 8. The entity is in charge. See http://www.drupal.org/project/external\_entities/ for an example.

---
Tags: entities, 8
---


# Question
Title: How to add css to specific blocks or view with CSS injector module?
**How to add css to specific blocks or view with CSS injector module?**

I can add css to specific pages, but what about blocks, views and all sorts of other nodes?

# Answer
I am try already this but i think it would be helpfull

Use php section to add css against any view or block and try this one

```
<?php
if ( $block->module == 'your_block_id/name'){
          //add some code here
}
?>

```

Or can do it by add a class in view or block
> 0 votes

# Answer
Using the CSS Injector module, there is not a way to only add CSS to **pages that include specific elements** such as Views, blocks, etc.

However, that's generally OK. If you're using Drupal's built-in CSS aggregation (and/or Advanced Aggregation), you're really just looking at couple hundred bytes per page, which *should* be cached by the browser, making those tweaks fairly negligible in terms of page load times.
> -1 votes

---
Tags: theming
---


# Question
Title: How to dynamically change the text of the Global: result summary based on exposed filter on Views?
There is a content type and it has a field called `field_type`. It's a select list and there is 5 options to select such as AAA, BBB, CCC, DDD, EEE.

I'm using the Views module to list the nodes of this content type. I added the field\_type as exposed filter for this views.

In the header of the views, I added the `Global: Result summary` to show result summary.

```
 "@total results found."

```

What I want to do is dynamically change the text based on the exposed filter. For example if the AAA is selected on the `field_type` exposed filter then the results summary should display:

```
 "@total AAA found."

```

**How can I do that?**

# Answer
> 2 votes
This can be done by implementing the hook\_views\_pre\_render and altering the view's header content. Here is a sample code:

```
/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(&$view) {
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
    $indicator = $view->exposed_input['my_filter'] == 1 ? t('AAA ') : t('BBB ');
    $view->header['result']->options['content'] = '<div class="my-class-results">@total <strong><em>' . $indicator . '</strong></em> found</div>';
  }
}

```

This works with any substitution: `@start, @end, @total, @name` etc

# Answer
> 1 votes
I took the liberty of writing a little module for accomplishing what you asked for, I found it an interesting problem. You can access it here:

https://www.drupal.org/sandbox/stefanos.petrakis/2666048

Hope this helps

---
Tags: 7, views
---


# Question
Title: How to show Comment Count in node template?
How can I show ***Comment Count*** in a specific place of the node template?
I want to show Comment Count's of a node (article) in the submitted area instead of in the node links area.
I do this already in Drupal 7 with this codes in node.tpl.php:

```
<?php if (module_exists('comment') && $node->comment) { print t('Comments'). ': ' .$node->comment_count;} ?>

```

or this code:

```
<a href="<?php print $node_url;?>#comments"><?php print t('Comments'). ': '. $comment_count; ?></a>

```

What is the equivalent code for Drupal 8?

# Answer
Use this code in your theme's `YOUR_THEME.theme` file:

```
function YOUR_THEME_preprocess_node(&$variables) {
  // Note: you'll probably want this only for certain content types.
  if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $variables['comment_count'] = $variables['node']->get('YOUR_COMMENT_FIELD')->comment_count;
  }
}

```

And then you can use it in your `node.html.twig` file like so:

```
{{ comment_count }}

```
> 8 votes

---
Tags: theming, 8, nodes, comments
---


# Question
Title: Show attribute widgets even if the Add to Cart form only represents one product
I'm having problem with display option, of Product variation field as "Add to Cart form":

With that option it should show variation switcher, **whenever there is one or more product variations**.

But it does not:

Simply looks like "Show attribute widgets even if the Add to Cart form only represents one product." option doesn't change anything.

The above display shows teasers on the front page (I have trying manipulating default view in Manage Display as well).

I have trying clearing cache, running cron and changing my customized *node--product--type.tpl.php* and *node--product--type--product--list.tpl.php* to oryginal ones and it does not help as well.

# Answer
> 1 votes
There are a few things you have to ensure you do right for this to work, as even in my little test environment to reproduce the error I screwed it up a couple different ways.

1. You must ensure the field you've added to your product type has checked the box to state that it should function as an attribute field on Add to Cart forms.
2. You must edit the field display settings using the form you've posted a screenshot of, but make sure you save the full form as the "Update" button on the expanded form doesn't actually save any changes to the database.
3. You must reproduce that for all relevant view modes.

With all of those things in mind, I was actually able to confirm the feature itself is working as advertised when properly configured:

---
Tags: commerce
---