# Question
Title: How to gets analyts and generate visual reports from sessions?
I'm looking for a technique or approach to get data from user session logs and convert it to a some sort of visual style (bars/charts/whatever).

We'd like to specifically have the users session "arcs" (`login->news->something->logout`) displayed in a way that makes it easier to analyze the way people use the site.

This is meant for our service as a usability analyser with the idea that we could make out and see the UX/UI problems that users experience, just from the statistics.

Google Analytics and Piwik are cool and have some of the same functionality but we're looking to go a bit further...

Any ideas on how to get started? Also if I missed an obvious way of doing this, feel free to point out!

# Answer
I don't know of any modules that build this functionality inside Drupal itself. However, there are several tools out there, for which there are Drupal modules, that allow you to visualize the *arc* that you speak of. Two of my favorites are:

**MixPanel:** Mixpanel can allow you to create funnels that will help you see how the user is progressing through your website. For example, how many logged in users clicked on a product, how many of those went on to the payment page, and how many of those actually ending up paying. Mixpanel also has a Drupal module for easy integration. Or you could easily integrate this using a custom Mixpanel module with minimal effort. This is how a funnel in MixPanel would look like:

<sub>(source: wordpress.com)</sub>

**Google Analytics:** It has a fantastic Visitors flow functionality that will allow you set flows, goals, and track against those too. Again, Google Analytics has a readymade Drupal module. Here's what a flow in GA would look like:
> 1 votes

# Answer
The Forena module can be used for such types of reporting. It comes with all sorts of Sample reports and solutions, such as the *Site administration reports*, which contain data about the actual Drupal site.

Here are some details about those reports:

* **Active Users** \- A variation of D7's admin/people, including hyperlinks to the Logs for User report.
* **Active Users Email** \- A demo of the ability to send email to all active users of a drupal site.
* **Logs for User** \- Most recent watchdog log entries for a user (specified as a report parameter).
* **Role Details** \- A table displaying all users for a Drupal role (specified as a report parameter), and the Drupal permissions granted to them, with for each user hyperlinks to either view or edit the user's profile.

Cloning these sample reports into custom variations is straight forward. E.g. tune the **active users** report with some report parameters to only report about user registered this week. Or as I did some time ago in this report (with drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the forena issue queue for more details about the above screenshot.

There is even AbitMORE: this module also supports charting of those data (a typical related requirement ...).

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

# Answer
module google analytic report with charts activated do the work

EDIT:

i don't know if i exactly reply to your needs but google analytics report module create a default view to display a summary charts and datas tabs from GA datas. These drupal attached views can be modified and extended with adding GA:session variables such as

```
Adsense metrics: AdSense Exits
The number of sessions that ended due to a user clicking on an AdSense ad.
API name: ga:adsenseExits.
Ecommerce calculated metrics: Ecommerce Conversion Rate
The average number of transactions for a session on your property.
Calculation: ga:transactions / ga:sessions.
API name: ga:transactionsPerSession.
Ecommerce dimensions: Sessions to Transaction
The number of sessions between users' purchases and the related campaigns that lead to the purchases.
API name: ga:sessionsToTransaction.
Event tracking calculated metrics: Events / Session with Event
The average number of events per session with event.
Calculation: ga:totalEvents / ga:sessionsWithEvent.
API name: ga:eventsPerSessionWithEvent.
Event tracking metrics: Sessions with Event
The total number of sessions with events.
API name: ga:sessionsWithEvent.
Goal conversions calculated metrics: Goal Conversion Rate
The percentage of sessions which resulted in a conversion to at least one of your goals.
Calculation: ga:goalCompletionsAll / ga:sessions.
API name: ga:goalConversionRateAll.
Goal conversions calculated metrics: Goal XX Conversion Rate
The percentage of sessions which resulted in a conversion to the requested goal number.
Calculation: ga:goalXXCompletions / ga:sessions.
API name: ga:goalXXConversionRate.
Goal conversions calculated metrics: Per Session Goal Value
The average goal value of a session on your property.
Calculation: ga:goalValueAll / ga:sessions.
API name: ga:goalValuePerSession.
Internal search calculated metrics: % Sessions with Search
The percentage of sessions with search.
Calculation: ga:searchSessions / ga:sessions.
API name: ga:percentSessionsWithSearch.
Internal search calculated metrics: Site Search Goal Conversion Rate
The percentage of search sessions (i.e., sessions that included at least one search) which resulted in a conversion to at least one of your goals.
Calculation: ga:goalCompletionsAll / ga:searchUniques.
API name: ga:searchGoalConversionRateAll.
Internal search calculated metrics: Site Search Goal XX Conversion Rate
The percentage of search sessions (i.e., sessions that included at least one search) which resulted in a conversion to the requested goal number.
Calculation: ga:goalXXCompletions / ga:searchUniques.
API name: ga:searchGoalXXConversionRate.
Internal search metrics: Sessions with Search
The total number of sessions that included an internal search
API name: ga:searchSessions.
Page tracking calculated metrics: Pages / Session
The average number of pages viewed during a session on your property. Repeated views of a single page are counted.
Calculation: ga:pageviews / ga:sessions.
API name: ga:pageviewsPerSession.
Page tracking dimensions: Page Depth
The number of pages visited by users during a session. The value is a histogram that counts pageviews across a range of possible values. In this calculation, all sessions will have at least one pageview, and some percentage of sessions will have more.
API name: ga:pageDepth.
Session calculated metrics: Avg. Session Duration
The average duration of user sessions represented in total seconds.
Calculation: ga:sessionDuration / ga:sessions.
API name: ga:avgSessionDuration.
Session calculated metrics: Bounce Rate
The percentage of single-page session (i.e., session in which the person left your property from the first page).
Calculation: ga:bounces / ga:sessions.
API name: ga:bounceRate.
Session metrics: Bounces
The total number of single page (or single engagement hit) sessions for your property.
API name: ga:bounces.
Session metrics: Session Duration
The total duration of user sessions represented in total seconds.
API name: ga:sessionDuration.
Session metrics: Sessions
Counts the total number of sessions.
API name: ga:sessions.
Social interactions metrics: Unique Social Actions
The number of sessions during which the specified social action(s) occurred at least once. This is based on the the unique combination of socialInteractionNetwork, socialInteractionAction, and socialInteractionTarget.
API name: ga:uniqueSocialInteractions.
Time dimensions: Hour
A two-digit hour of the day ranging from 00-23 in the timezone configured for the account. This value is also corrected for daylight savings time, adhering to all local rules for daylight savings time. If your timezone follows daylight savings time, there will be an apparent bump in the number of sessions during the change-over hour (e.g. between 1:00 and 2:00) for the day per year when that hour repeats. A corresponding hour with zero sessions will occur at the opposite changeover. (Google Analytics does not track user time more precisely than hours.)
API name: ga:hour.
Traffic sources dimensions: Social Source Referral
Indicates sessions that arrived to the property from a social source. The possible values are Yes or No where the first letter is capitalized.
API name: ga:hasSocialSourceReferral.
User calculated metrics: % New Sessions
The percentage of sessions by people who had never visited your property before.
Calculation: ga:newUsers / ga:sessions.
API name: ga:percentNewSessions.
User dimensions: Count of Sessions
The session index for a user to your property. Each session from a unique user will get its own incremental index starting from 1 for the first session. Subsequent sessions do not change previous session indicies. For example, if a certain user has 4 sessions to your website, sessionCount for that user will have 4 distinct values of 1 through 4.
API name: ga:sessionCount.

```
> 0 votes

---
Tags: users, sessions
---


# Question
Title: Where do views/panels get their source html code
I'm working on a few sites that use views/views-ui/panels to display content.

The entry points of the templates are located in the active theme directory for example 1 view with settings of `Format: Bootstrap Thumbnails` renders the file `views-bootstrap-thumbnail-plugin-style--title.tpl.php`

But inside here is only a loop which prints out `$rows` of large html strings.

This is the same for most sections which simply `print $variable`.

I've tried using xdebug and followed the stacktrace but get completely lost in the nested functions, and can't keep up with the large unorganised `$this` variable.

I've also tried root directory searches of strings from the HTML which only finds html in the cache.

**Where do views/panels get their source html that's inserted into `$row` `$content` etc.. ?**

# Answer
> 0 votes
It will depend on the contents of the panel or view display as to the actual content to be displayed. For example a panel/view might contain a node, in which case a specific display mode would be used dependant on the output settings. Using your example whichever module provides the `Format: Bootstrap Thumbnails` is likely to be the candidate which can either be further overridden with a different template, or with an appropriate hook\_theme.

---
Tags: 7, views, panels
---


# Question
Title: Populating 2 variables with user-entered form data and sending them to PayPal
**Problem**

Hi, when a user submits a payment form on my site I need to populate two variables $comment1 and $comment2 with the values of other information the user supplied but I'm unsure how to accomplish this in Drupal so that those variables get sent to PayPal.

**Example Scenario**

So, for example, a user enters their name in the checkout form and their organization in another field. When the user submits the form to paypal for payment processing we want the `$comment1` field to get their `$organization` value and for the `$comment2` field to get their `$fullname` value.

We want these to be sent to PayPal along with all the other information that gets sent to PayPal because the PayPal manager can read and utilize values in variables called `$comment1` and `$comment2`.

**Question**

My question is, what's the best way to accomplish this?

**Assumption**

I assume it involves hooking into and changing some code in a function in the contributed module somewhere. Any guidance is appreciated.

# Answer
> 1 votes
assuming you're using commerce\_paypal **WPS**, you'll need to hook

```
HOOK_commerce_paypal_wps_order_form_data_alter(&$data, $order){}

```

in a custom module. there you can extend the $data array like

```
$data['on3'] = 'your_property_name';
$data['os3'] = 'your_property_value';
$data['on4'] = 'your_other_property_name';
$data['os4'] = 'your_other_property_value';

```

or exchange data like

```
$data['organization'] = $data['fullname'];

```

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


# Question
Title: How to transform data from the Google Analytics Reports module into charts?
I'm using Google Analytics Reports to bring in Google Analytics data into Views, this works fine, but I'd like to display this data as a chart.

I've tried with two different charts modules: Charts and Google Chart Tools. Both require you to use `Aggregation` in views to group the data, but this isn't something the Google Analytics Reports module supports.

Can anyone recommend a way around this or a different approach?

# Answer
> 1 votes
You can use the API sub-module within the Google Analytics Reports module and use

DataViz module for the visual representation.

You could use http://blog.amazeelabs.com/en/comment/257249 for reference.

# Answer
> 1 votes
According to the Google Analytics Reports issue about "Use Aggregation", the 7.x-3.x version (for which only a beta2 is available at this moment) should support this now.

That's also what's written in comment #1 of it, ie:

> See chart examples in the latest 7.x-3.x version.

What isn't obvious to discover, is that these examples have a weak module dependency of the Charts module:

So if the Charts module isn't enabled yet, these example charts will show up as soon as you (download and) enable it.

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

---
Tags: views, google-analytics, charts
---


title: Social Feeds with Views Module

text:
# Question
Title: Social Feeds with Views Module
I've been searching high and low for a feeds module that will show Facebook and Twitter feeds with the Views Modules (Drupal 7.x). With Twitter using oauth, many Drupal 7 social feed modules haven't caught up to using oauth yet. The main reason I want to use views with the social parsers is because I want to use animation(like slide show) to show each social feed as it comes in.

I have found Social Parsers for Feeds that will work with views module but none that will work for Drupal 7.x

Does anyone have any suggestions that will allow social feed modules to be used in the views moudle?

# Answer
I guess you have some options:

You can use Activity Stream, the imported feeds become nodes so they can be re-created using views. You have a choice to enable only the modules you need. The Facebook add-on module also has a Drupal 7 release in the issue queue.

```
 Activity Stream builds a lifestream, a "River of You", by aggregating all your social activities in one place. Whether it's bookmarks on Del.icio.us, posts from Twitter or your blog, edits to wikis or enjoyed music and movies, anything you create can be gathered into one easy-to-read stream. Every item becomes a full Drupal node, allowing them to be searched, promoted, commented upon, and managed just like any other piece of content within Drupal.

```

Alternatively, you can use the TB Social Feed, the feed items become nodes so they can also be used with views.

```
This module we have developed for our responsive Premium Drupal theme TB Wall. We contribute this module to the community and hope you can re-use it in your projects and development.

**What does this module do?**

This module aggregates content from social media sites. The module will retrieve public RSS feeds or request the API and creates a node for each item. Your website visitors will be able to see your sharings directly on your website and drive those visitors to your social media account. This way you might increase facebook fans, twitter followers etc.

We currently support facebook, twitter, vimeo, youtube, instagram, Flickr. Anyone feel free to contribute to this module so we can add up other social media channels.

```

There is also Social Feed which has a Drupal 7 release in the issue queue, but it creates a block for the feed items rather than a node for each.

So i guess the first two options are what you need
> 1 votes

# Answer
The Social Content module imports social posts as nodes, which can then be displayed with views. We are successfully using this with Drupal 7.

From the project page:

> This enables content from social media websites to be imported as nodes.
>
> Content can be pulled from the following sites:
>
> Twitter Tweets can be pulled from user accounts and hashtags. OAuth module is required.
>
> Instagram Instagram posts can be pulled from user accounts and hashtags.
>
> Facebook Facebook posts can be pulled from Facebook pages.
>
> Tumblr Text, Photo and Video sources can be imported from Tumblr blogs.
>
> Pinterest Content from Pinterest boards can be imported.
>
> Youtube Youtube videos from channels can be imported.
>
> SoundCloud SoundCloud tracks can be imported.
>
> Linkedin Company updates can be imported.
>
> VK VK group / user wall posts imports.
>
> Flickr Photos from public photo streams can be imported.
>
> Picasa Web Albums Photos from photo streams and albums can be imported.
>
> These are all separated into individual modules within the project so you can just enable the ones that you want to use.
> 0 votes

---
Tags: views, feeds, javascript, authentication-authorization
---


title: How do I register a user?

text:
# Question
Title: How do I register a user?
I am using Drupal 7.17 and the Services module 7.3.2.

I set the Services module as in the following screenshots.

I followed the documentation on http://drupal.org/node/1447020.

With FireFox HttpRequester, I tried to register a new user.

I got a 500 error.

Do you have any idea?

# Answer
apparently , there is a field of that name ... and some node / entity which is trying to get saved automatically. Could you have Profile2 installed ? Did you try the report on admin/reports/fields ? If you dont find it there, try the database - finde the table that uses the column ie this way :

```
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'field_published_value'
AND TABLE_SCHEMA = 'yourdb'

```

i tried on a "default install" and didnt see it :)
> 1 votes

# Answer
I solved this problem by using resource which has name "entity\_user" (mabe it's nesessary activate module "eck").

I use this uri: http://mysyte/myendpoint/entity\_user I use POST method I use same json parameters as you.

It Works for me.
> 0 votes

---
Tags: 7, services
---


# Question
Title: Add epsacrop to programmatically added image field
I'm adding an image field to my theme form in order to setup a default image for the user. I'd like the user to be able to use EPSAcrop to crop the image he uploads here.

Is this possible, if so; How?

This is what I have now:

```
function MYTHEME_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {
  $form['header_images'] = array(
    '#title' => t('Header image'),
    '#type' => 'managed_file',
    '#description' => t('The default header image on every page. Unless a header image is selected in the node of the page.'),
    '#default_value' => variable_get('header_images', ''),
    '#upload_location' => 'public://header_images/',
    '#upload_validators' => array('file_validate_extensions' => array('png, jpg, gif')),
  );
}

```

# Answer
> 0 votes
I had the same problem. If you change managed\_file to media, you will have availability to manage EPSA cropping for the form image.

---
Tags: media
---


# Question
Title: What is the menaing of print t(); in following code?
I was referring the `html.tpl.php` to learn the theming guide for drupal 7, and found following code line in `html.tpl.php`,

```
<a href="<?php print $skip_link_target; ?>" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>

```

Can anybody let me know what is the `print t()` in `<?php print t('Skip to main content'); ?>`. Is it translation function or something else?

# Answer
Yes, it's Drupal's string translation function.

`t()`

> Translates a string to the current language or to a given language.
> 1 votes

# Answer
Yes, this is translation function https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/7 .
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Using module_invoke() and render() causes PHP warnings
From within a block, I've used the following PHP to add additional blocks inside it:

```
$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search);
print render($user_search);

```

When I do so, I get the following warnings:

> Warning: Invalid argument supplied for foreach() in element\_children() (line 6541 of /var/www/mysite.dev/public\_html/includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 5998 of /var/www/mysite.dev/public\_html/includes/common.inc). Warning: Illegal string offset '#children' in drupal\_render() (line 6008 of /var/www/mysite.dev/public\_html/includes/common.inc).

It appears that the problem is tied to the *render()* function as I can call *print\_r($content\_search)* and everything looks good, but I can't render the blocks without these warnings.

# Answer
Blocks aren't render arrays, they're made up of a `subject` and `content` key.

You'll probably have better luck referring to those explicitly:

```
$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search['content']);
print render($user_search['content']);

```
> 3 votes

# Answer
try it like this:

```

$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search['content']);
print render($user_search['content']);

```

or use another method:

```

$block = block_load($module, $delta);
$render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
$output = drupal_render($render_array);
print $output;

```
> 1 votes

---
Tags: blocks
---


# Question
Title: How do I display the absolute URL of the terms?
I have a view displaying a list of my taxonomy term (term name with link). How do I display the absolute URL of the terms?

This is the exported view I am using.

```
$view = new view();
$view->name = 'sitemap_taxonomie';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Sitemap taxonomy';
$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'] = 'Sitemap taxonomy';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['use_more_text'] = 'plus';
$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['exposed_form']['options']['submit_button'] = 'Appliquer';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'nothing' => 'nothing',
  'nothing_1' => 'nothing_1',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nothing' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nothing_1' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Champ: Terme de taxonomie : Nom */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'loc';
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
$handler->display->display_options['fields']['name']['convert_spaces'] = TRUE;
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing']['id'] = 'nothing';
$handler->display->display_options['fields']['nothing']['table'] = 'views';
$handler->display->display_options['fields']['nothing']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing']['label'] = 'changefreq';
$handler->display->display_options['fields']['nothing']['alter']['text'] = 'weekly';
/* Champ: Global : Texte personnalisé */
$handler->display->display_options['fields']['nothing_1']['id'] = 'nothing_1';
$handler->display->display_options['fields']['nothing_1']['table'] = 'views';
$handler->display->display_options['fields']['nothing_1']['field'] = 'nothing';
$handler->display->display_options['fields']['nothing_1']['label'] = 'priority';
$handler->display->display_options['fields']['nothing_1']['alter']['text'] = '0.8';
/* Critère de filtrage: Terme de taxonomie : Vocabulaire */
$handler->display->display_options['filters']['vid']['id'] = 'vid';
$handler->display->display_options['filters']['vid']['table'] = 'taxonomy_term_data';
$handler->display->display_options['filters']['vid']['field'] = 'vid';
$handler->display->display_options['filters']['vid']['value'] = array(
  3 => '3',
  4 => '4',
  2 => '2',
);

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

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'views_xml_style';
$handler->display->display_options['style_options']['root_element'] = 'urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
$handler->display->display_options['style_options']['top_child_object'] = 'url';
$handler->display->display_options['style_options']['plaintext_output'] = 1;
$handler->display->display_options['style_options']['header'] = '';
$handler->display->display_options['style_options']['using_views_api_mode'] = 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['path'] = 'sitemap-taxonomy.xml';
$translatables['sitemap_taxonomie'] = array(
  t('Master'),
  t('Sitemap taxonomy'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('loc'),
  t('changefreq'),
  t('weekly'),
  t('priority'),
  t('0.8'),
  t('Page'),
);

```

This is the output of the view.

# Answer
> 1 votes
You need to do the following in your View:

1. Add the following fields (if not there already), in the following order (rearrange if you must, TID must come before Name).
    * Taxonomy term: Term ID
    * Taxonomy term: Name

2. Configure the TID field: exclude it from display, change the "Thousands marker" to none.

3. Rewrite the Name as a link, using absolute paths and the tid.

Just tried this and it worked as you described:

# Answer
> 0 votes
Here is an alternative answer, following your comment

> I would have liked that the URL is displayed instead of the name in the statement of my views.

1. You need to install this contrib module =\> Views base url
2. Add 2 fields (if not there) in your View and exclude them from display (will use them for rewriting): Taxonomy vocabulary: Machine name Global: Base url
3. For the "Taxonomy term: Name": Select "Link this field to its taxonomy term page" and rewrite to this \[base\_url\]/\[machine\_name\]/\[name\]

Hope this is what you asked for! Here is the final result:

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


# Question
Title: Problem in rendering double-field in other node
I think I have a problem with keys and values of a list field in the rendering phase (on Drupal 7).

Let's me go in detail.

Model part:

* We defined a CCK "double field" for a "profile2", with multiple values allowed.
* This field is composed by a select and a text-field, but I'm interested only to the "select" part in this moment (its behavior seems to be the same of a simple list field).
* Then we defined values in the list as `K1|V1`, `K2|V2`, etc.

Render part:

* We defined a theme template for this field; there we verifies values by comparing the key: `$val = $item['first']` (to take it) and `if ($val=="K1") {...}`... and everithing works fine, because tamplate receives keys of the list (inside `first` key of the `#object` array of the renderable array).
* In a node page I have to show the same information and I would like to use the same template file (instead of replicate the code). So I tried to use `render( )` Drupal function, and it needs for a renderable array... but the only function I found to get it was `field_view_field( )`... and it doesn't work as I expect.

The **problem** is that this function doesn't return field keys (e.g. `K1`), but values (e.g. `V1`)... so templates is not able to work properly.

I know I can write differently my template (e.g. `if ($val=="K1" || $val=="V1")`, but I think this is can't be the right solution, because code should alway depend from keys (and not values, that may change over time).

So I'm wondering what is the Drupal way to achieve a renderable array in which there is the keys and not the values of a list element.

Thank you

# Answer
Try to change format for that field in 'Manage display' in back-office. 'key' option should be there. This option available for select list, but for "double field" try to set "unformatted list", style "simple", and text format "-none-".
> 1 votes

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


# Question
Title: Content REST view does not work because of moderation states
I've created a simple view using the `REST export` to export all published content in JSON format, but I get this error:

```
Symfony\Component\Routing\Exception\RouteNotFoundException:
    Route "entity.moderation_state.canonical" does not exist.
    in Drupal\Core\Routing\RouteProvider->getRouteByName()
    (line 191 of core/lib/Drupal/Core/Routing/RouteProvider.php).

Drupal\Core\Routing\UrlGenerator->getRoute('entity.moderation_state.canonical') (Line: 285)
Drupal\Core\Routing\UrlGenerator->generateFromRoute('entity.moderation_state.canonical', Array, Array, 1) (Line: 110)
Drupal\Core\Render\MetadataBubblingUrlGenerator->generateFromRoute('entity.moderation_state.canonical', Array, Array, ) (Line: 754)
Drupal\Core\Url->toString() (Line: 291)

```

Moderation states have indeed been added, but I have no idea why that's throwing this kind of error...

# Answer
> 0 votes
The route is not in core. Probably it is in a contrib or custom module. You have to search for a \*.routing.yml file, where it is defined and then look for an error in the yml file and then clear the cache.

You can get a complete list of all routes with drupal console:

```
drupal route:debug

```

---
Tags: nodes, 8, workbench
---


# Question
Title: Simplest way to add a custom icon to a Navbar menu item
The Navbar module comes with some pre-set icons for common uses. They're fixed to the menu item names.

If you want different icons, or, to add icons to custom menu items or menu items provided by 3rd party modules, what's the simplest way that makes these new icons appear on pages using both the admin and main themes?

There's an issue in the Navbar queue for 3rd party module maintainers wanting to support Navbar icons out of the box, but it's not intended for site builders.

The *ideal* answer would:

* Work in both main and admin theme contexts without duplication (so, not just adding CSS to theme)
* Not cause the icons to fall off if the wording of their menu item labels is changed - in many organisations CSS styling and site structure will be handled by different people and should be independent of each other (this currently happens to Navbar default icons)

# Answer
> 1 votes
You can try to create custom module and implement `hook_navbar()` \- for new items and `hook_navbar_alter()` \- for already created items. In this hooks you can set custom css classes for items and attach you custom css file.

check `/navbar/navbar.api.php` file.

---

Looks like links came from `navbar_menu_navigation_links()`, they already have css class `navbar-icon-<item_title>`. You create custom css file in you module and add in hook\_init(). Example of css styles you can get from navbar/css/navbar.icons.css or even copy it to your file and change if needed or add css for new items.

---
Tags: 7
---


# Question
Title: Which type to use for checkbox fields in hook_field_schema?
**Task:**

Create a custom field which contains a single checkbox by implementing `hook_field_schema` etc.

**Question:**

Which data type is (or should) be used to define the corresponding database column to save checkbox values?

**Sample code:**

```
function field_test_field_schema ($field)
{
    $columns = array();
    switch ($field['type']) {
        case 'test':
            $columns = array(
                    'value' => array(
                            'type' => '???',
                            'not null' => TRUE
                    ),
            );
            break;
    }
    return array('columns'=> $columns);
}

```

**Update:** `node_schema` uses `int` for boolean columns. e.g. :

```
'status' => array(
  'description' => 'Boolean indicating whether the node is published (visible to non-administrators).',
  'type' => 'int',
  'not null' => TRUE,
  'default' => 1,
)

```

# Answer
> 13 votes
A tiny `int` would be most appropriate in my opinion:

```
$columns = array(
  'value' => array(
    'type' => 'int',
    'not null' => TRUE,
    'size' => 'tiny',
    'default' => 0,
  ),
);

```

A 'standard' `int` would be overkill for a field that will only ever hold a `0` or `1` value.

See the Data types docs for an overview of the different types available to you.

# Answer
> 7 votes
There is no boolean in the Drupal schema API so you just use a tiny int. Below is an example of a checkbox for a member where checked is "blocked" and unchecked is "in good standing":

```
  'status' => array(
    'description' => '0 = in good standing; 1 = blocked',
    'type' => 'int',
    'size' => 'tiny',
    'not null' => TRUE,
    'default' => 0,
  ),

```

# Answer
> 0 votes
pgsql worked sample:

```
'has_original' => array(
  'pgsql_type' => 'boolean',
  'type' => 'int',
  'size' => 'tiny',
  'not null' => TRUE,
),

```

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


# Question
Title: Memory-saving cache-clearing strategies for large sites?
One of my Drupal 7 sites has thousands of fields, a bunch of content types, more than 25 views, and hundreds (soon to be thousands) of profile types. Because of this, I'm using a core patch that better caches entity field info (http://drupal.org/node/1040790), and the -dev version of Views which better caches views by display (instead of having one HUGE views cache row with all views data in it).

This has helped most pages on the site to load with 20-30MB of RAM used, rather than 160MB+ (instead of pulling up cache\_\* table rows for fields and views that were 10MB+, the patches help keep cache\_\* data much more efficient).

This introduces a problem, however, in that cache rebuilds take a *really long time*. Usually more than a minute or two. And during this time, Drupal simply won't load any pages (since the caches that it's trying to read from are not yet built, other requests have to wait).

During low-traffic cycles, this isn't a big deal; a hundred or so users will simply have to wait a minute before the page loads. But during high-traffic cycles, the Apache server starts going crazy, with 40+ CPU load, and the memory quickly fills up because all the worker threads sit waiting, and max out their memory, causing swapping. It's kind of a death spiral. A restart of httpd will clear things up, but it takes 5-10 minutes for things to get back to normal.

My goal is to make it so cache clears don't bring the site to its knees. For one, if I use admin\_menu's individual cache clearing functions (like "CSS and JS", then "Menu", then "Theme registry", etc.), things go smoothly until I hit the "Page and else" option. That's when views' cache is reset (a very CPU and database-intense operation with the number of views that need to be cached), and when the field info cache is reset (which is also CPU and database-intense on this site).

So... my questions/ideas:

* Using drush and/or other shell scripting, is it possible for me to clear caches in a more intelligent way than "blast all caches at once, and hope for a clean rebuild"?
* Can I block http requests while the cache clearing is happening so apache doesn't get clogged with a bunch of cache-stampeding requests?
* If I can clear caches outside of Drupal/normal httpd request, I could presumably set a higher PHP memory\_limit for the cache clear operation, and back off my universal memory\_limit (right now set to 256MB, in case any individual httpd thread needs to clear caches...).

Basically: Is there any intelligent and graceful way to clear all caches with Drupal besides simply clicking the button in the UI, or using `drush cc all`?

\[**Edit for clarification**: The main problem I have is *cache rebuilds*, which (a) take a while, and (b) block all other requests until the rebuilds are complete. I would like to find a way to make it so the rebuilds aren't quite as deadly during high-traffic times.\]

# Answer
> Is there any intelligent and graceful way to clear all caches with Drupal besides simply clicking the button in the UI, or using drush cc all?

The cache actions module does that. It depends on rule. For exampple, you can setup a rule to clear a specific view when a node of type "x" has been added or updated. Checkout the docs for more details.

Also take a look at the cache graceful module - haven't tried it yet but looks interesting.
> 10 votes

# Answer
The main problem is that you are using MySQL to store cache data - for high-load sites this is very ineffective solution.

I advice to use Memcache instead. This will dramatically increase performance of cache system and give you 2 great benefits:

1. Memcache is much faster for read and write operations that MySQL - all you cache operations (and full cache rebuild) will work faster.
2. Because cache data not stored in DB anymore - clearing cache will not block any other MySQL queries.

Here is example of Memcache configuration for Drupal 7.
> 2 votes

# Answer
> Using drush and/or other shell scripting, is it possible for me to clear caches in a more intelligent way than "blast all caches at once, and hope for a clean rebuild"?

If you don't want to blast all caches, use: `drush cc type_of_cache` to clear specific one, or define your own.

Alternatively clear all cache-like tables manually, e.g.

```
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "DELETE FROM %;" | $(drush sql-connect) -v

```

If you're using memcached (Bash syntax), try:

```
pgrep memcached && echo flush_all > /dev/tcp/127.0.0.1/11211

```

> Can I block http requests while the cache clearing is happening so apache doesn't get clogged with a bunch of cache-stampeding requests?

Enable maintenance mode (`drush -y vset maintenance_mode 1`) to prevent people accessing the site. Or configure front-end to redirect somewhere else (e.g. in Varnish, redirect in Apache or changing `.htaccess`).

> If I can clear caches outside of Drupal/normal httpd request, I could presumably set a higher PHP `memory_limit` for the cache clear operation, and back off my universal `memory_limit` (right now set to 256MB, in case any individual httpd thread needs to clear caches...).

Clearing cache doesn't take more memory, but the rebuilding the cache after clear will take more. You can always warm up the caches by running cron or opening any page, e.g.

```
time php -n -d memory_limit=-1 time $(which drush) cc registry
PHP_OPTIONS='-d memory_limit="2G"' drush cron
php -d memory_limit=1G ./scripts/drupal.sh http://localhost/

```

Specify `-n` to ignore `php.ini` processing which can additionally speed up the cache clearing process.
> 1 votes

# Answer
There's potentially a monetary cost involved, but you could use a caching server setup like Varnish. The upside is that Varnish will serve your site while your cache is clearing on the production server, without the user being the wiser.

The downside: depending on how many seconds/minutes of downtime of the production server vs your VCL timeout settings, Varnish may update during that time and you'll see a Varnish 503 error screen.

But this approach along with Redis or Memcache may help.
> 0 votes

---
Tags: 7, drush, caching, performance
---


# Question
Title: Is there a way to return "Drupal root" value that is faster than running drush status?
I'm trying to add something to my shell that shows the current Drupal root value so that we can use drush use more, but the only way I can see to return the current Drupal root value is to run drush status which is quite slow

# Answer
```
cd /path/to/drupalroot/sites/default
drush drupal-directory '%root'

```

On the old system I'm on right now, that clocks in at 3.5s, vs. 11.8s for `drush status`

If you are using site aliases, as tenken suggested, then you can do this:

```
drush sa --format=csv --fields=root

```
> 3 votes

# Answer
Sure. Instead of running `drush status` from a DocRoot of a Drupal site you can create a Drush Site Alias file.

The simplest example from that documentation file is:

```
 /*
 * Aliases are commonly used to define short names for
 * local or remote Drupal installations; however, an alias
 * is really nothing more than a collection of options.
 * A canonical alias named "dev" that points to a local
 * Drupal site named "dev.mydrupalsite.com" looks like this:
 *
 *   $aliases['dev'] = array(
 *     'root' => '/path/to/drupal',
 *     'uri' => 'dev.mydrupalsite.com',
 *   );
 */

```

You basically are hardcoding the filepaths. You can later use this known structure and data to lookup the site root paths when you need them.

If you want to automate building your site alias file you can look at this example tutorial (I am not the author) called Drush Pro Tips: Automatic Site Aliases by Rob at LastCallMedia. His example uses the following code to build an alias file across a structured project codebase:

```
$aliases = array();
$dir_handle = new DirectoryIterator('/var/www');
while($dir_handle->valid()) {
  if($dir_handle->isDir() && !$dir_handle->isDot()) {
    // Does this subdirectory contain a Drupal site?
    if(file_exists($dir_handle->getPathname() . '/sites/default/default.settings.php')) {
      $basename = $dir_handle->getBasename();
      $aliases[$basename] = array(
        'uri' => 'http://localhost/' . $basename,
        'root' => $dir_handle->getPathname()
      );
    }
  }
  $dir_handle->next();
}

```

Once you have a site alias file you can then use BASH commands to easily rip out the information from the alias array or show it to the screen. This approved answer from our own site on showing site alias information is an example of utilizing BASH to get at the alias information https://drupal.stackexchange.com/a/50563/3279

The final example shows how to show the site paths on the filesystem from the answer, you could further tweak his BASH commands into an alias that just returns the raw `PATH` for a given `@alias` if you wanted, the work is ~80% for you in his example:

```
    drush sa | xargs -I {}  sh -c "echo {}; drush {} st" | egrep "(@|path)"
@8080
 Site path                     :  sites/8080.webtest2
 File directory path           :  sites/8080.webtest2/files
 Private file directory path   :  /var/www/drupal_private_files
@commons_3_dev
 Site path              :  sites/default
 File directory path    :  sites/default/files
@none
@w2
 Site path              :  sites/default
 File directory path    :  sites/default/files

```
> 2 votes

# Answer
In Drupal 7 you can just print `DRUPAL_ROOT` constant, e.g.

```
drush ev "print DRUPAL_ROOT"

```

which obviously won't be faster than `drush dd %root`.

So to make it quicker, you need to use something else than Drush.

For example if your Drupal is under git repository, quicker solution for the script is to check top dir of your repository, e.g.

```
git rev-parse --show-toplevel 2> /dev/null

```

To look for the first folder containing `index.php`, try:

```
dirname $(find -L $PWD -name index.php -print -quit)

```

Basically `DRUPAL_ROOT` is where `index.php` exists which have those lines:

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

```
> 0 votes

---
Tags: drush
---


# Question
Title: What specific modules are included in Drupal Commerce Kickstart?
Drupal Commerce Kickstart is a project built on Drupal Commerce that bundles Drupal 7, Commerce and a host of additional modules with some preset settings to speed up Commerce-based development.

I'm trying to find out what specific modules are actually included in this bundle, but all I can find is uninformative advert pages like this.

There's nothing about what exactly is included in the Kickstart documention. The closest I can find elsewhere online is this list of modules *not* included.

Is there any simple list of the modules that are bundled in the Commerce Kickstart package?

# Answer
> 2 votes
Here's the actual makefile that builds the latest version of Commerce Kickstart.

http://cgit.drupalcode.org/commerce\_kickstart/tree/drupal-org.make

Within it, you can find every module that is built in. It includes the machine name of the project and the version number used.

For example, the entry "projects\[ctools\]\[version\] = 1.9" shows you the machine name ctools, which is the Chaos Tools module, and the version is 1.9. You can look up the modules on drupal.org by substituting the machine name into the following URL: http://drupal.org/project/MACHINENAME.

# Answer
> 0 votes
This is a list based on this page announcing the first release candidate for Commerce Kickstart 2 in 2012 of modules that were developed as part of Commerce Kickstart and subsequently released as independent modules.

It gives an overview of some of the non-standard modules most specific to Kickstart. Note it's not complete and may not be up to date, but might be a useful starting point for understanding what sort of things Kickstart adds to a typical Drupal site.

## Modules

## Themes

---
Tags: 7, commerce
---


# Question
Title: Add product thumbnail to user/%/purchased-files?
I've managed to add an extra field in the Purchased Files page, as well as hide the address limit, however I cannot figure out how to actually get the product thumbnail in there, like there is on the cart page. Below is what I'm working with so far, any ideas how to get the image associated with that file in the empty field?

# Answer
You need to change page callback for path `user/%/purchased-files` in `hook_menu_alter()` and your custom callback should be based on code of `uc_file_user_downloads()` function, you need to change it, add new column with product image. I guess you need to change query in that function to get more data from 'uc\_file\_products' table about the product id, and based on that you can get all product info etc
> 1 votes

---
Tags: ubercart
---


# Question
Title: Profile2: How to understand if user has not an associated profile?
I'm not able to understand what is the code I should use to verify if user has (or not) a profile (made by profile2 module) associated.

I use `profile2_load_by_user($uid, "my-profile-name")` and it always returns me a "Profile" object... also for users that has not that profile (for example users listed in `/admin/people/noprofile`).

I know I can test if some mandatory field is currently filled, but do you know what is the "formally correct" way to proceed?

Thanks

# Answer
> 1 votes
If you are doing `profile2_load_by_user` and profile object is showing, then its profile object has been created. If Profile object has not been created for a user, then its profile object will be empty, means its pid has still not been created.

You can check for the same, in your database, inside profile table.

# Answer
> 1 votes
Try to check what return

```

$profiles = profile2_load_multiple(FALSE, array('uid' => $uid));

or direct query
$result = db_select('profile', 'p')
      ->fields('p', array('type', 'pid'))
      ->condition('uid', $uid)
      ->execute()

```

---
Tags: 7, users
---


# Question
Title: No Drupal Site Found when clearing cache
I installed drush using composer following the instructions here: http://docs.drush.org/en/master/install/

When trying to run `drush cc all` I get this error:

> No Drupal site found, only 'drush' cache was cleared.\[warning\] 'all' cache was cleared. \[success\]

I added this line:

```
export PATH="/Applications/MAMP/bin/php/php5.6.2/bin:$PATH"

```

to my `.bash_profile` and restarted bash and MAMP. Still no luck. Any ideas?

This is my `drush` status:

```
 Drupal version         :  7.36
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  srod
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush script           :  /Users/srod/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/srodsite
 Site path              :  sites/default

```

I'm running it from Drupal project folder.

# Answer
I figured out that you will need a mysql server installed and included in path, even if you are using mysql from AWS RDS.
> 2 votes

# Answer
For people working on Windows, you need to verify that your PATH Variable for MYSQL is properly set. I had the problem when I had upgraded my WAMP.

Example like this : `C:\wamp\bin\mysql\mysql5.6.17\bin`
> 2 votes

# Answer
Haven't tried it myself, but maybe you want to try what is mentioned here , and which points to https://www.drupal.org/node/1428638 . Here is a quote from it:

> Edit the settings.php file of your drupal installation, and go to the database settings entry.
>
> change the host line to:
>
> 'host' =\> php\_sapi\_name() == 'cli' ? '127.0.0.1' : 'localhost',

Curious to hear if that could help ...
> 0 votes

# Answer
If you're running inside Drupal root folder, there are two possibilities which may go wrong:

1. `drush` cannot find Drupal core files (you don't have `index.php` or `common.inc`), check by:

```
find -maxdepth 2 -name index.php -o -name common.inc

```
2. Your PHP CLI doesn't have PDO extension (`php -m | grep pdo`).
> 0 votes

---
Tags: 7, drush, composer
---


# Question
Title: Insert values into custom field's extra columns in database
I'm new to drupal 7.

I've create a custom field with extra columns via field api, and create the field well(via UI), but I can't "save" it while using the field.

I've google for it and found some keywords like

```
hook_field_storage_write()、hook_field_attach_submit()

```

But still can't get what I want. Can someone give me advices?

# Answer
> 0 votes
Can you provide more details how did you implement schema, widget, formatter etc. I guess this link can be helpful for you http://www.slideshare.net/zugec/fields-in-core-how-to-create-a-custom-field

---
Tags: entities
---


# Question
Title: Cannot edit my views.. I get a JSON string?
I'm using Drupal v7.22 and whenever I try to Modify the Display on views, and press the 'Add and configure' button on adding a field, or any button that sends data to the server, the page reloads and I just get a long JSON String returned in Chrome, or IE will try to download the return... Sometimes it'll accept my change, but more often than not, it won't.

It was doing this on 7.21 and then I updated to 7.22 and it stopped for a day or two, now it's doing it again. I am extremely new to Drupal, but I am a quick learner and most things are going smoothly.

What did I break and how can I fix it?

# Answer
Based on @Clive's suggestion in the comments, I found this issue:
JQuery Update breaks Views UI

So Views UI is not compatible with jQuery 1.8, and the OP has already confirmed that this was the problem.

This problem isn't limited to Views though. Other contrib modules depend on the default core version of jQuery (including Rules). An issue exists in the jQuery Update queue to Allow different version for administrative pages. And a patch was applied to dev on 20 MAR 2013.

The dev version of jQuery Update provides a update to the Configuration Form that allows you to select a different version of jQuery on administrative pages.

**Before**

**After**

I can confirm that setting the "Alternate jQuery version for administrative pages" select list to "1.5" after upgrading to the dev version of jQuery Update fixes the issue with Views.
> 7 votes

# Answer
I have had this problem before, usually on reallly big queries too big for the default mysql sql packet size. Rather than mucking with that -- try turning off Javascript/AJAX in the Views in the views administration settings.

It's not as neat without ajax views admin pages -- but this usually fixes it.

EDIT:

Login as `administrator` goto `/admin/structure/views/settings/advanced` and check `Disable JavaScript with Views`. Then Save that configuration page.
> 3 votes

# Answer
In my case it was due to domain name conflict while configuring `Secure pages` module. make sure that the http and https url are same and also check firebug if there's anything not loading due to change in protocol, like js libraries and other third party libraries.
> 1 votes

# Answer
The most common reason behind JSON dump on the screen are:

* your JSON could contain some unexpected errors or debug dumps, validate its code first
* your web site has some Javascript errors, so check JS Console for more details and fix them first (in Chrome: *Developer Tools*)
* there is some conflict with some development modules, so disable the most suspicious one to test (`drush -y dis devel navbar`)
* if you're using jQuery Update, change the version to the recent one at /admin/config/development/jquery\_update (or the one provided by Drupal)
* make sure you don't use any fishy extensions on your browser, so test on another browser,
* clear caches and restart memcached after some of the changes described above,
* disable JS aggregation and Drupal caches (in Performance) and debug JS code,
* try to test it on different instance or in the clean environment.
> 0 votes

# Answer
I just experienced this issue today. The issue in my case was that I was accessing the website with "www", but the base\_url in my settings.php file had the domain name without "www". Once I added "www" to the base\_url, the issue was immediately resolved. The error message in Chrome's Dev Tools Console was "Uncaught Error: The callback URL is not local and not trusted"
> 0 votes

---
Tags: views
---


title: Twitter Block translation

text:
# Question
Title: Twitter Block translation
I've got a TwitterBlock on my website. It works fine but all texts are in english. Even if I change t('') function with my language (french) desired, it's still in english.

ex:ln422 twitter\_block.module

```
'#title' => t('Tweets by @username', array('@username' => $config['username'])),

```

to

```
'#title' => 'Tweets par @me',

```

It still display 'Tweets by @username' in my page. The language input seems to be ignored to in admin/structure/block/manage/twitter\_block/1 when I wrote 'fr' in it.

I hope that my problem is a minor oversight on my part. All tips are good (even the simplest).

Thanks in advance.

PS: when I try to do a `dsm($block)` in twitter\_block.module or `dsm($content)` in my override block I get all my values in french.

# Answer
1. Do you have French language on you site?
2. You should not change code of contrib modules. You can override, extend it in your custom module.
3. If you have fr language on site , back t() with EN labels, go to admin/config/regional/translate/translate try to search EN labels and translate them.

---

Another way to get translations, use module l10n\_update, it can get translation if they available on Localization servers.
> 0 votes

---
Tags: blocks, i18n-l10n, social-network
---


# Question
Title: Trouble adding conditional to page-title.html.twig
I am building my first D8 theme and I am new to Twig. I am trying to add a class to the h1 title tag on the home by editing page-title.html.twig, but I can't get it to take. Here is my code

```
{% set body_class = '' %}
{% if title == 'Welcome to My Website' %}
    {% set body_class = 'home-page-title' %}
{% endif %}

{{ title_prefix }}
    <h1{{ title_attributes.addClass(body_class) }}>{{ title }}</h1>
{{ title_suffix }}

```

# Answer
You're doing it wrong. The method you are using is not consistent if you change the page title to something else, or use another page as your landing page.

There are two ways to solve this:

## The long way, using `hook_preprocess_html()`

Instead of this, I recommend targeting the `<h1>` tag through a body selector, and add there a special class for front page through `hook_preprocess_html()`. This is a cleaner solution, and you can target other elements as well.

This code would go to your `YOUR_THEME.theme` file:

```
function YOUR_THEME_preprocess_html(&$variables) {
  // Add a custom class determining if we're on the front page.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['attributes']['class'][] = 'front';
  }
  else {
    $variables['attributes']['class'][] = 'not-front';
  }
}

```

In your `html.html.twig` file you need to have:

```
<body{{ attributes }}>

```

Then in your CSS file, you would use:

```
body.front h1.page-title {
  /* Your styles. */
}

```

## The short way, using only twig - by 4k4

The `root_path` variable provided to you by `template_preprocess_html()` will be set to `FALSE` when you are on the front page. This means that you can use it as condition argument, and give different class to the `body` element.

Here's an example:

```
<body{{ attributes.addClass(root_path ? 'not-front' : 'front') }}>

```

Hope this helps.
> 2 votes

---
Tags: theming, 8
---


title: Limit Fivestar for node author only

text:
# Question
Title: Limit Fivestar for node author only
I have a content type called Task, where I add tasks. After task being completed, I would like the node author to rate his satisfaction using Fivestar field.

While viewing the node (not in edit mode), how to enable voting on this satisfaction rating field by node author only on his task but others can't vote, they can see his/her vote.

# Answer
Here is an alternative answer, specific to the case where the voting happens on the frontend (using the "rated while viewing" widget).

1. Under "Manage Fields", configure your rating/fivestar field to use the widget "Stars (rated while viewing)". You also must configure the options:

* Allow users to vote on their own content: This must be on
    * Allow users to cancel their ratings: This is optional
    * Allow users to re-vote on already voted content: This should be off
2. Under "Manage Display", configure your rating/fivestar field to disallow voting via AJAX:

* Allow voting on the entity: This must be off, we will modify this dynamically
3. In a custom module, you should implement the following hook. It will activate the "Allow voting on the entity" only for the author of the node.

```
/**
 * Implementation of hook_field_display_ENTITY_TYPE_alter().
 */
function yourmodule_field_display_node_alter(&$info) {
  if($info['type'] == 'fivestar_formatter_default') {
    global $user;
    $node = menu_get_object('node');
    if($node && $user->uid == $node->uid) {
      $info['settings']['expose'] = TRUE;
    }
  }
}

```

This configuration+code delivered the result you wanted on my sandbox instance, hope it works for you!
> 2 votes

# Answer
Here are the steps you need to allow only the node author to rate the node.

1. For the Task content type, change the role permissions so that only the authenticated users (or whichever role you want to allow to complete and rate Tasks) have the "Edit own content" permission.
2. Under "Manage Fields" for the Task content-type, configure your rating/fivestar field to use the widget "Stars (rated while editing)". Now, only the node's autor can edit and rate a Task node. The vote will still be visible to other users.

Hope this helps!
> 2 votes

---
Tags: rating
---


title: Conditional filters for views

text:
# Question
Title: Conditional filters for views
I have 4 filters for my nodes. These filters work with taxonomy terms. So I have 4 taxony lists:

* Type (a,b,c)
* length (d,e,f,g,h,i,j)

If I select Type (a) then length should only give me the possibilities that actually are possible with the length for example f,g,h. Is this possible?

# Answer
> 0 votes
Yes, it is possible.
What you are asking for is typical faceted search functionality.
You should be looking in the direction of Facet API.

Cheers!

---
Tags: views
---


# Question
Title: How does one concatenate fields in title field in Panels (Pages)?
I have learned how to concatenate fields in Views, now I need to do the same thing in the title field in Panels. I have these fields \- first name \- last name

and I would like the title of the Panel to be first name + last name

I'm using a module which enables me to automatically update the title field and hides it. The automatic generation includes the first and last name plus the date. I don't want this to display on top of the panel for this content type.

TIA

# Answer
You need to use replacements tokens in your "Content" configuration page, this is how is looks on my local instance:

Good luck!
> 0 votes

---
Tags: entities, panels
---


# Question
Title: Migrate from xml with two attributes as condition
I have a problem with drupal migrate, i'm trying migrate content with this xpath:

```
item_xpath = '/import/content/contentInstance[@contentTypeId=\'ac1ssss___\' @window=\'blank\]';

```

when i execute drush ms return 0 results, however if i use only one condition in item\_xpath:

```
item_xpath = '/import/content/contentInstance[@contentTypeId=\'ac1ssss___\']';

```

Return 15 results

```
'/import/content/contentInstance[**@contentTypeId=\'ac1ssss___\' @window=\'blank\]';

```

Return 10 results

The xml have content with two attributes, not migrate allows two conditions as attribute?

Thanks for all.

# Answer
You don't mention what XML source plugin you're using - is it MigrateSourceXML? If so, note that (as documented), it does not read in the entire XML file thus general-purpose xpath is not available, it implements a limited subset of xpath syntax for selecting the items to import. You should use MigrateSourceMultiItems when you need full xpath syntax.
> 0 votes

---
Tags: migrations, feeds
---


# Question
Title: Get list of custom fields and update their settings programatically
I'm using D8's core contact form, I have added some custom fields and I want to change one of custom fields' settings config programatically.

I have tried this

```
\Drupal::service('entity_field.manager')->getFieldDefinitions('contact_form')

```

but I get error:

```
LogicException: Getting the base fields is not supported for entity type Contact form. in Drupal\Core\Entity\EntityFieldManager->buildBaseFieldDefinitions() (line 204 of core/lib/Drupal/Core/Entity/EntityFieldManager.php).

```

Is there any way to get list of fields and update their configs and settings?

# Answer
> 1 votes
Try this one:

`$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('contact_message', 'personal');`

You can change `personal` to your contact form bundle.

---
Tags: entities, 8, emails, configuration
---


# Question
Title: Where to modify feed status to change number of created and updated nodes
i want to change the message after a feed is completed that shows the number updated and created. What file in the feeds module is the one that outputs this message? using Feeds 7.x-2.0-alpha9

the progress is in feeds.pages.inc but I still cannot find where the number created and updated is

# Answer
in feeds.pages.inc, function feeds\_source\_status() the status information is shown for the importer, including the number of imported items. The number of items is calculated in FeedsProcessor::itemCount() in plugins/FeedsProcessor.inc.

The message of how many entities were created and updated happens in FeedsProcessor::process(). FeedsSource::$state keeps track of these numbers. The case where these numbers might not be accurate is if the same entity is updated multiple times in a single import. Usually, this is caused by a configuration error: the target that is configured as unique appearantly isn't unique in the source.
> 0 votes

---
Tags: feeds
---


title: Post Private Message to Selected User

text:
# Question
Title: Post Private Message to Selected User
I've built an iOS app on the Drupal iOS SDK. That said, I want my logged in user to be able to send a message to another Drupal user. Right now, I'm successfully pulling received Private Messages from my services endpoint - but does anyone know how I would go about successfully posting a message to a specific user id? Are there any tutorials out there for this?

# Answer
here is a rough sketch of how you could go about this:

iOS Side: Add a node using DIOSNode's add

Drupal Side:

1. Create you own custom content type, e.g. CustomMessage, with a UserID field for collecting the target user of each message. This could be a simple text field, or an Entity Reference field, single or multi-valued.
2. Create a Services View that will use a user's UID as a contextual filter, in order to display all messages targeted at a specific user.
> 1 votes

---
Tags: 7
---


# Question
Title: Is there any way to force https:// to be used for assets and still be able to define a theme CSS files in its .info file?
I have a theme which defines its CSS files in its .info file, for example with a line like the following.

```
stylesheets[all][] = css/style.min.css

```

The site is accessed using https://, but for some reason, Drupal tries to load all the files via http://.

Is there any way to force Drupal to use https:// on assets and still be able to define a theme CSS files in its .info file?

# Answer
For a Drupal 7 site using Cloudflare CDN and a Bootstrap theme, this worked for me: Set the base URL in your settings.php file, without including http:// or https://.

```
$base_url = '//my.domain.name';

```

For another Drupal 7 site with a different theme, just removing `$base_url` worked. In both cases, I needed the site to work with secure URLs and without.
> 4 votes

# Answer
You might need to set the base URL in the settings.php file, specifying the URL scheme.

```
$base_url = 'https://my.domain.name';

```
> 2 votes

# Answer
One option is to use AdvAgg as this will generate different aggregate filenames for http and https. If the issue is the cache then advagg will not fix it though.
> 0 votes

---
Tags: ssl, .info
---


# Question
Title: How do I add tags to Advanced Forum posts
I would like to add the type of tags this stackexchange forum has, so users can tag their posts and the tags appear at bottom of all posts. How do I do that?

# Answer
> 2 votes
**1.** If you want to create the Tag in the new topic content, you can follow as suggested by the @lixu (This method will add the tag below the body content, but you can also shift its position up-down by going at `manage-field`). But this method will not show the tags on the advanced forum topic list.

>

**2.** If you want to create the tag at the list of topics page, like stake-exchange but not completely like that, You need to go to views. Advanced forum provides 5 views, Go to `Structures->Views->Advanced Forum topic list->Edit`, to the field add new field `Content: tags`.

You can rearrange the position of it by rearranging option(Check second image). I have added to the last as shown in the image. What this will do, it will add one more column of Tags in the topic list page, besides the last-post column(check third image). You can shift the column of tag wherever you want, by shifting the tag filed in views.

>

# Answer
> 0 votes
in drupal 7 admin mode, structure-\>content types-\>forum topics-\>click manage field,

add existing field, select field\_tags/Autocomplete term widget (tagging)

tags now exist for forum post

---
Tags: nodes
---


title: Clear cache tables

text:
# Question
Title: Clear cache tables
I installed a 'test' theme and then uninstalled it. I ran `drush cache-rebuild` and I also cleared all caches in the Configuration-\>Performance menu. However when I run `drush config-export`, to export my configuration from my development environment onto my staging environment, the list of files that get exported still include references to the 'test' theme even though I uninstalled it and cleared my caches.

I looked at my database and in the cachetags table there are rows there that reference the 'test' theme that I uninstalled. I have a feeling these are the ones that get exported during the `drush config-export`. Is there any way I can clear these?? Because right now I can't carry on with the `drush config-import` command on my staging environment because I get an error stating that it can't install the 'test' theme because it's not included. And it shouldn't install it because it shouldn't be there.

I've looked around and all documentation points to `drush cache-rebuild` being used to clear all caches, however in my case it's not doing it.

I'm using Drupal 8 along with Drush 8 all running on Ubuntu.

I was considering doing that but since I'm new to Drupal I was a little concerned that it will cause some other problems if I manually deleted them.
I just removed them and sure enough the config files are gone like they should've been. Everything looks fine so far.
It'd still be nice to know what is the proper way to have a theme removed, uninstalled and completely cleared from the database. And also what caches `drush cache-rebuild` really clears and what it doesn't.

# Answer
> 5 votes
To clear all cache tables run this command in your server terminal.

```
# Truncate cache tables in MySQL regardless of the active cache backend
echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "TRUNCATE TABLE %;" | $(drush sql-connect) -v

```

this will loop through all cache tables and truncate them in one command.

*I can't remember the source and where I get this to give credit for the one who wrote it the first time.*

---
Tags: drush, caching
---


# Question
Title: Different colors and fonts dependent on roles in views results
Views listings are made from many users, but some of them have special role that is more important. Is there an easy way to give that special role different background color or font or font size when viewing views results ?

# Answer
> 2 votes
In your theme template.php file add this function

```
function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role {
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}

```

This will add the current role(s) to the body classes.

Now you can style it like this

```
body.role-admin .view-VIEW-CLASS {
  background: #eeeeee;
  font-size: 16px;
}

```

# Answer
> 1 votes
You could use a module like this https://www.drupal.org/project/views\_table\_highlighter.

It would take some php coding, inside views.

---
Tags: views, theming, users
---


# Question
Title: repeated results with Views Slideshow results and commerce products
I have a slideshow view where I am showing most recently discounted items.

each product display has 8 different variable combinations therefore, 8 product SKUs connected to the product content.

I have my view filtering by Content:product. However, it is showing all 8 products for each piece content.

# Answer
> 0 votes
First thing to do is to make sure that the relationship is set to be required, if the duplicate results still coming on .. go to views query settings and check both DISTINCT and PURE DISTINCT

---
Tags: views, commerce, javascript
---


# Question
Title: How to display an add content form inside another content view page?
Basically I'm looking to make a beefed-up comment system. I'd like to have a content-type B that acts as a comment like entity for content-type A.

**Question**: When content A is viewed, at the bottom of the page the `node/add/content_type_B` form should be there with a 'Save' button which will create a new piece of content. Is it possible to render the content type B add form inside the content A view page (no Panels/Display Suite please)?

# Answer
> 2 votes
With Advanced Form Block you can use a "Node add" form has a block, you could show it at the end of your node content using regions or node tpl file

---
Tags: 7, nodes
---


# Question
Title: How to create a page without any theme via custom module?
I created a page using a custom module, it has a template file too and it works well. But when i visit my page it shows wrapped by my default theme, it's obvious. The thing is that i would like to show that content in a clean page.

Is there a function or something that lets me do it? without modules like ThemeKey

# Answer
If you want to show content in clean page you can use theme\_hook\_suggestions in `THEME_preprocess_html` and `THEME_preprocess_page` with passing some GET variable. For example for clean pages you can add `$_GET['embed'] = 1` and in `preprocess functions` write the following code:

```
function THEME_preprocess_html(&$vars) {
  if (isset($_GET['embed'])) {
    $vars['theme_hook_suggestions'][] = 'html__embed';
  }
}

function THEME_preprocess_page(&$vars) {
  if (isset($_GET['embed'])) {
    $vars['theme_hook_suggestions'][] = 'page__embed';
  }
}

```

Then copy paste `html.tpl.php` and `page.tpl.php` and rename to `html--embed.tpl.php` and `page--embed.tpl.php`. Ultimately remove unnecessary code from template files.
> 4 votes

---
Tags: 7, theming
---


# Question
Title: Pull first image from each node to use in view
I want to take the first image from the images each node has in its body, to use it as a thumbnail when displaying nodes in a view. How can I do this?

# Answer
> 3 votes
This module makes things much easier: Teaser Thumbnail.

> The Teaser Thumbnail module allows you to automatically generate thumbnails for your node teasers and RSS feeds from the pictures included in the body or the attachments of the nodes. This module depend on ImageCache 2 and works with views.

# Answer
> 4 votes
I've used this regex in my views templates for this task -- it works by grabbing the src from the first image tag in the body content (assumes using fields view style):

```
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $fields["body"]->content, $matches);
$first_img = $matches[1][0];

if (!empty($first_img)) {
     print "<img src='$first_img'>";
}

```

You can also pass the source to your imagecache theme function, as Jim and jimajamma suggest, to scale the image.

# Answer
> 3 votes
And, if Jim Kirkpatrick's solution doesn't work for you, and you do need to screen scrape an image out of your body field, you can create a views template that does that for you.

SO, if you have the Node Body as a field in your view, and assuming the view name is stories, the display is page, and the field name is body, that template would be called `views-view-field--stories--page--body.tpl.php` which you can find by clicking on the Theme Information link in the view's Style Settings. Normally all this template does is output the formatted contents of the field, but what you could do is replace it with something like this:

```
<?php

  $foo=explode('<img',$row->node_revisions_body);
  $bar=explode('>',$foo[1]);
  $baz=$bar[0];

  if ($baz) {
    print '<img class="thumb-me" ' . $baz . '>';
  } else {
    print '<img class="thumb-me" src="/sites/default/files/default-image.png">';
  }
?>

```

This could most probably be done with one quick regex but basically what it is doing is exploding the contents of the body first by the beginning of an `<img` tag, then chopping it off by the closing `>`, which returns the contents of the first image in the body.

This is then output re-wrapped in an easily themable image tag so you can use CSS to change the size. Not too optimal, but quick and easy.

To put this into play, put that template in your theme directory and click "rescan template files" in the views Style Settings/Theme Information area mentioned above and make sure it highlights this new template. After that, hopefully there are no typos that result in a WSOD :)

Now, if you are using another CCK field for this, you would change the node\_revisions\_body to something based upon that field, so a quick dsm($row) in the template will show you the information you need to find that (or if my system is set up differently than yours, etc).

# Answer
> 1 votes
Assuming you have something similar to a `field_images` imagefield on your content type:

1. Install ImageCache and set up some 'Scale and Crop' or 'Scale' presets for the thumbnails you want.
2. In *Content management -\> Content types -\> {your content type} -\> Display fields (tab)* you can set the image field to use your new imagecache preset in teaser.

If you don't have an image field, things will be much harder to be consistent and will certainly need more editing. However, you can install Image Resize Filter, add it to your input format and use that to make nice thumbnails from within your WYSIWYG editor.

# Answer
> 1 votes
I solved this by installing Computed Field

This module Executes a piece of PHP code on every save/update action.

After installing and enabling it, add a separate Compute field to your Content Type.

Write a PHP code to Select the first IMG tag in body.

**Computed Code**

```
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $entity->body[LANGUAGE_NONE][0]['value'], $matches);
$entity_field[0]['value'] = $matches['1']['0'];

```

**Display Code**

```
$display_output = $entity_field_item['value'];

```

**Data Type**

longtext

Now this field will be saved in the Database. You can access this field in your Views by usual method.

Hope this helps.

# Answer
> 0 votes
For Drupal 7 the best way is used Teaser Image module. This module automatically generates thumbnail for teasers and RSS feeds from images included in node body (or imagefield which attached to node).

---
Tags: views, 6, media
---


# Question
Title: Private schema is always used for system.files route
I am trying to serve files from Amazon S3(s3:// stream wrapper) via system.files / system.private\_file\_download routes but no matter what I do the scheme is always set to private.

I have tried to use `/system/files/s3/file.jpg` for **system.private\_file\_download** and `/system/files/s3?file=file.jpg` for **system.files**

but I always get private scheme.

The system.private\_file\_download route seems to be completely broken due to htaccess rules(ie. serving image like this won't even make it to the controller) and system.files somehow completely ignores provided scheme argument.

---

So far I have observed that the routes get matched to requests in exact opposite as one would expect. The system.files route is defined first and it expects only "scheme" url argument(with "private" as default value in controller and also in the route itself), for example /system/files/public and what is provided as "file" query argument is used as target, so /system/files/public?file=foo/bar.jpg should result into public://foo/bar.jpg but instead the system.private\_file\_download route is used(even though it is defined after the system.files route). This route expects the "filepath" url argument, like /system/files/foo/bar/.jpg, and it automatically uses the private scheme because both of these routes use the same controller but this route does not provide the scheme in its definition or path so the default value from the controller itself is used.

I think the issue here is that the second route is using the filepath: .+ argument mask and therefore will match "better" with the path so it will have more priority over previously defined system.files route.

Also strangely the "filepath" url argument in system.private\_file\_download route has no match in the controller(`\Drupal\system\FileDownloadController::download`) so the resulting uri will be simply private:// no matter what values are provided to the route.

---

I have replaced the public stream wrapper with s3 so all files are now served from remote server and it is working just fine. I was able to get the image styles working(system/files/styles/thumbnail/public/foo/bar.jpg) but I am still not able to serve the original files from under /system/files path as well. Since I need to serve the physical files and not File entities, even if I would switch to private file system the files would not be served because file\_file\_download() handles only file entities.

---

I have ended up with custom route. If anyone is interested the important thing is to have two routes(just like the two mentioned above). The second one will transform the url arguments into query argument and return path to the first route. This is done via path\_processor\_inbound tagged service(see \Drupal\system\PathProcessor\PathProcessorFiles).

# Answer
> 0 votes
I looked into this. Long story short, it's a bug in core: https://www.drupal.org/node/2694129. It will be a bit tricky to fix, since it might require API change and not 100% sure when such a change can actually be made.

---
Tags: 8, files
---


title: Render custom block by block name

text:
# Question
Title: Render custom block by block name
I have created a custom block in the Drupal CMS. Say it is called "test\_block". Is there a way to render this block in a template file using the name of the block?

Thanks,

# Answer
**D7:**

```
<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print $block['content'];
?>

```

**'module\_name'** = The machine name of the module (i.e. the module's folder name). This is true for core modules too, so for instance 'search', 'user' and 'comment' would all work here.

**'block\_delta'** = The machine name of the block. You can determine what this is by visiting the block administration page and editing the block. The URL for editing a webform block, for instance, would be something like:

Drupal 7: admin/structure/block/manage/**webform**/**client-block-11**/configure

In this example, **'webform'** is the module's name, **'client-block-11'** is the block's delta.

Custom blocks will have module name of 'block' and a number for a delta, which you can also find by editing the block.

More information: http://drupal.org/node/26502

====== OR =============

```
<?php
//suppose 98 is the id of the block

   $block =block_load('block',98);
   $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
   print $output;
?>

```
> 19 votes

# Answer
## D8:

```
$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
$rendered_block = ['#markup' => render($block_view)];

```

Render a custom block programmatically
> 4 votes

# Answer
Try this

```
$block = module_invoke('block', 'block_view', 'test_block');
print render($block['content']);

```
> 2 votes

# Answer
If you are asking how to use a custom template for this block, then the answer is:

Assuming the machine name of your block is test\_block, then create a file called

```
 block--block--test_block.tpl.php

```

In your theme
> 0 votes

# Answer
On your template level you should be able to do something like this:

```
<?php
  $test_block = "test_block";
  print views_embed_view($test_block);
?>

```

This will display your block in the template.
> 0 votes

---
Tags: 7, theming, blocks
---


# Question
Title: Where are the add to cart form settings?
Im just trying to find the settings page for the add to cart form. I cant find it...

Im trying to change the setting when someone adds the same item to the cart twice it will combine it into one line item, rather than creating to separate line items as it is doing now.

I have attempted to add the setting here:  but no luck. still getting multiple line items.

# Answer
> 0 votes
Turn on the Combine options in your Line Item displays and Product displays.

If you use Commerce lisense module please check this issue Commerce license does not combine line items

If not I guess this link can be helpful , you will find example of `hook_commerce_cart_product_comparison_properties_alter()`

---
Tags: commerce
---


# Question
Title: Know if node is in view, edit, delete, etc. in page.tpl
I need to verify, in `page.tpl` file, if page is currently showing a node for viewing, editing, or deleting purposes.

I found I can write `arg(2)=="edit"` to verify if it is in "edit mode", but how to do for delete (`arg(2)` is empty such as for view).

What is the correct way to get this information?

Thank you

# Answer
Here's how to check against all paths related to nodes:

Node view:

```
arg(0) == 'node' && arg(1) && is_numeric(arg(1)) && !arg(2)

```

Node edit:

```
arg(0) == 'node' && arg(1) && arg(2) == 'edit'

```

Node delete:

```
arg(0) == 'node' && arg(1) && arg(2) == 'delete'

```

Node add "landing" page from where you choose which content type you want to create:

```
current_path() == 'node/add'

```

Node add page for a specific content type:

```
current_path() == 'node/add/YOUR_CONTENT_TYPE'

```

All node add pages:

```
arg(0) == 'node' && arg(1) == 'add' && arg(2)

```
> 3 votes

---
Tags: 7, nodes
---


title: How can I get comment creation date?

text:
# Question
Title: How can I get comment creation date?
How can I get comments creation date of a node and convert it to custom format in my theme, I tried to make some operations on node comments date in "MyTheme.theme" file and in `MyTheme_preprocess_comment` section.

# Answer
> 4 votes
```
/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}

```

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


# Question
Title: After Upgrading from D7 to D8, D8 does not look like D7 at all
I have successfully performed a D7 -\> D8 migration of my company site. Everything seemed to go well, but when I'm accessing the Drupal 8 site, the entire design is pretty much gone.

How can I get the old design back again for Drupal 8?

# Answer
Drupal 8 is very different from Drupal 7, same goes with previous major versions of Drupal.

This means that themes and modules can only work for a single Drupal major version (fx 6, 7 or 8).

When you migrate a site from D7 to D8 you have to re-implement the theme. In Drupal 8 we now use Twig as the template language so you pretty much have to start from scratch (unlike 5 -\> 6 -\> 7 where the theme differences wasn't that big and a lot could be reused).
> 10 votes

---
Tags: migrations
---


# Question
Title: Bilingual site - when adding translations to Organic Group, prevent creating a separate group/content node
We have a bilingual site. We use organic groups to separate suborganisations and their members.

The Organic Group content's multilingual option is set to "Enabled, with translation"

We just want the "Landing" page of the Organic Group to be translated.

When the Organic Group is translated, it creates a discrete Group that allows users to join.

Essentially, we'd like everyone to be in the same group, but still be able to see content in their preferred language.

Anyone have a workaround for this?

# Answer
> 1 votes
Basically the answer is to use Entity Translation. See here https://www.drupal.org/node/371181

---
Tags: organic-groups, i18n-l10n
---


# Question
Title: Cannot hide Superfish sub menu on active pages
I am using the horizontal NavBar style with Superfish. When I'm in a section, I do not want its sub-navigation bar to show up. I only want to see the sub-pages listed whenever I mouse over the parent link.

Example: Main section is called Products, and I have a sub-section called T-Shirts. If I click on T-Shirts or Products, it displays the sub-navigation without having to mouse over the Products link again. The sub-navigation menu becomes persistent when in that section. I only want to see the list of Products sub pages if I mouse over the main Products link.

I tried setting Path Class to blank instead of "active-trail," but that jacked it up. Also tried hiding .active-trail with CSS, but no luck there either.

Wondering if this is a Drupal issue with Menu settings or a Superfish issue?

Thanks in advance for the help!

# Answer
It's both. The active trail stuff has always been, and still is, a big mess, and Superfish herited the problems. You can check this thread for some information about it, but it remains unclear.
> 2 votes

# Answer
It's a problem with active trail. I found that changing the version of my superfish library fixed it. I was running 1.91 of the Superfish module with the master branch of Superfish library. When I changed the library to the stable branch, the active trail worked.
> 0 votes

# Answer
For me worked solution:

* open superfish block settings
* change "Path levels" to "0"

See here on the image:
> 0 votes

---
Tags: navigation
---


title: MAMP Pro with PHP 7 OPcode caching

text:
# Question
Title: MAMP Pro with PHP 7 OPcode caching
I installed Drupal 8 on MAMP Pro with PHP 7. I am getting this warning in my Drupal reports page:

> PHP OPcode caching Not enabled
> PHP OPcode caching can improve your site's performance considerably. It is highly recommended to have OPcache installed on your server.

I looked in MAMP's PHP 7 ini file and I see this code which seems to be related to OPcode caching.

```
[OPcache]
MAMP_OPcache_MAMP
  opcache.memory_consumption=128
  opcache.interned_strings_buffer=8
  opcache.max_accelerated_files=4000
  opcache.revalidate_freq=60
  opcache.fast_shutdown=1
  opcache.enable_cli=1

```

So I am not sure if I need to do anything else to enable it, it seems to be enabled based on the code above. I googled around and could not find any specific documentation with regard to MAMP and PHP OPcode caching.

# Answer
> 10 votes
Just make sure that the OPCache is selected as caching mechanism in MAMP preferences.

1. Click on "Preferences".
2. Click on the "PHP" tab.
3. Select "OPcache" under "Cache" field.

# Answer
> 9 votes
The UI is slightly different for Mamp Pro. Some may find this screenshot helpful.

More recent versions of MAMP Pro have a different layout for the UI.

---
Tags: 8, caching
---


# Question
Title: While migrating D6 to D7, should sites folder be replaced?
I am trying to migrate Drupal 6.29 to 7.22. Part of migration I have deleted all files & directories except sites in D6 site. Now I downloaded Drupal 7.22. D7 version also has sites folder, so do I need to replace sites folder or not? In documentation I read like while copying the sites folder which files need automatically will be replaced, when I am copying sites it is asking for replace or not. Totally confused, can anyone help on this, it would be greatly appreciated!

# Answer
The upgrade documentation is quite precise about this step:

> 2. Update to the latest available version of Drupal 6.x
>
> \[...\]
>
> 9. Remove all old core files and directories, except for the 'sites' directory and any custom files you added elsewhere. \[...\]
> 10. If you uninstalled any modules, remove them from the sites/all/modules and other sites/\*/modules directories. Leave other modules in place, even though they are incompatible with Drupal 7.x.
> 11. Download the latest Drupal 7.x release from http://drupal.org to a directory outside of your web root. Extract the archive and copy the files into your Drupal directory.

```
 cp -R drupal-x.y/* drupal-x.y/.htaccess /path/to/your/installation

```

Executing the above shell command, will copy all the content of the drupal-x.y directory recursively to your installation directory. This will silently overwrite all files in your installation **that are also** in the drupal-x.y directory and create directories that are not already there. If there is a directory in both, say sites/default/files, only those files will be overwritten that are also in the source, and **no files will be deleted** from a directory, that is why you had to remove the core files in step 9. This is the default behaviour of `cp`. If you want to know more about how this works you could read `man cp`.

If you are not on unix or you don't have shell access to your server, you have to emulate this behavior (at the moment I cannot think about a copy function either on Windows or Mac that behaves differently, e.g. replacing a folder with files inside with an empty folder), because it is the recommended one, using the admin interface you have.
> 0 votes

---
Tags: migrations
---


# Question
Title: How to export recent logs report in csv file drupal 7
Download all recent logs messages into csv file which is stored in database in Drupal 7 admin can filters records and all records and filters records should be export in csv format

# Answer
Assuming that you're looking for a module-driven solution to export the content of the 'watchdog' table, you could combine Views, Views Watchdog and Views data export.
> 2 votes

# Answer
You can now try the Export Logs module (first released after you posted your question).
> 0 votes

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