# Question
Title: How can I access the variable from other .tpl.php file?
I am working on Advanced forum. And for my need I am editing `advanced-forum.naked.post.tpl.php` and I want to add the author name at one place. But this template do not have author name, but it has entire author pane printed. Now the variable for the author name is in `advanced-forum.naked.author-pane.tpl.php`. And it has a author-name code

```
<?php /* Account name */ ?>
      <div class="author-pane-line author-name">
        <?php print $account_name; ?>
   </div>

```

now if I am direct pasting this code to `advanced-forum.naked.post.tpl.php`, it shows error, that variable is not defined. Moreover, both this tpl files are in the advanced forum module/style file. So, how can I access that variable in that .tpl.php file? Very Thanks.

# Answer
> 2 votes
You can add custom variables using `hook_preprocess_node()` in your theme's `template.php` file.

Here's how to add the account name:

```
function YOUR_THEME_preprocess_node(&$variables) {
  $variables['account_name'] = format_username($variables['account']);
}

```

# Answer
> 1 votes
you need to set it in the preprocess function of the template. or see this answer https://stackoverflow.com/questions/2383865/how-do-i-use-theme-preprocessor-functions-for-my-own-templates

you'll need to hook this preprocess function

```
/**
 * Preprocesses template variables for the author pane.
 */
function advanced_forum_preprocess_author_pane(&$variables) {
  // Author pane is used in various places. Check the caller to make sure
  // we are the one that called it.
  if (!empty($variables['caller']) && $variables['caller'] == 'advanced_forum') {
    advanced_forum_add_template_suggestions("author_pane", $variables);
  }
}

```

maybe the author pane module could do the job for you ;) here's a similar question How to modify Author Pane date fields?

---
Tags: theming, nodes
---


title: Using views in Drupal

text:
# Question
Title: Using views in Drupal
I want to create a view page with the city events /attractions ... I want to categorize them as family , kids , outdoors etc. So that when a user clicks on a particular category they see the events/attractions listed under it.

How do I do this using Drupal 7 and views?

# Answer
Another way of doing this is with Contextual filters

-Create a view display Page (Block also works)

-Add **Contextual filter** Content has Taxonomy Term ID

-Leave **When the filter value is NOT in the URL** as Display all results

-On **When the filter value IS in the URL or a default is provided** check 'Specify validation criteria' and choose the vocabulary that has your events categories, leave filter type as 'Term ID'

Now when you hit the page url example.com/events it will list all the events from all categories

When you hit example.com/events/1 it will only list events from the category that it's term ID is 1 (say family is id 1 and outdoors is id 2, it will show all events categorized as family)

You could also make it filter by more than one term with other configurations options, and create URL aliases so your url becomes example.com/events/family
> 1 votes

# Answer
In the **Filter Criteria** add a filter **Content: Has taxonomy term** .

Choose the Vocabulary with your category. In the next step check **Expose this filter to visitors, to allow them to change it** . Set the Label as you want and "Apply".

Anyway, try to be more specific in your question if you want a better answer.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I upgrade drush from 3 to the latest release?
On my debian 6 server, I used apt-get to install drush. However, it looks like it downloaded drush version 3. I want to upgrade to the latest stable release of drush (which I believe is drush 5). How can I do this?

# Answer
> 4 votes
The short answer is on the Drush project page under the heading Install/Update - Unix/OSX:

```
pear upgrade drush/drush

```

I first had to install PEAR, but that should not be an issue.

# Answer
> 2 votes
You can using Drush to upgrade itself like the following:

`sudo drush dl drush --destination='/usr/share'`

Then you can check which version has been installed by executing:

`drush --version`

# Answer
> 2 votes
You can install/upgrade to the latest version using Composer.

### Install/Update via Composer

* Install Composer globally (if needed).

+ via composer installer: `curl -sS https://getcomposer.org/installer | php`
    + via php: `php -r "readfile('https://getcomposer.org/installer');" | php`
    + on OSX (via homebrew): `brew install composer`
* Make sure Composer's global bin directory is on the system PATH (recommended):

```
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc
source $HOME/.bashrc

```
* To install Drush 6.x (stable):

```
composer global require drush/drush:6.*

```
* To install Drush 7.x (dev) which is required for Drupal 8:

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

```

with specifying folder to install:

```
sudo COMPOSER_HOME=/var/lib/composer COMPOSER_BIN_DIR=/usr/local/bin COMPOSER_VENDOR_DIR=/var/lib/composer/vendor composer require drush/drush:dev-master

```
* To update to a newer version (what you get depends on your specification in `~/.composer/composer.json`):

```
composer global update

```
* Alternate commands to install some other variant of Drush:

```
# Install a specific version of Drush, e.g. Drush 6.1.0
composer global require drush/drush:6.1.0
# Master branch as a git clone. Great for contributing back to Drush project.
composer global require drush/drush:dev-master --prefer-source

```

Fuller explanation of the require command.

**Tips:**

If Drush cannot find an autoloaded class, run `composer self-update`. Drush often tracks composer changes closely, so you may have some problems if you are not running a recent version.

**Troubleshooting:**

# Answer
> 0 votes
Run 'drush up' in your terminal or command line interface. (Update manager has to be enabled) After checking all available updates for modules is will also check to self update.

It will end up with something like:
A newer version of drush, 7.x-5.4, is available. You are currently running drush version 5.0-rc3. The update process depends on how you installed drush. Some common update commands are: `pear upgrade drush`, `git pull`, `drush dl drush --destination=[/path/to/drush]`. To disable this check, put "$options\['self-update'\] = FALSE;" in your drushrc.php configuration file.

For more information on drush use 'drush help' or 'drush help COMMAND'.

# Answer
> 0 votes
If you are using PEAR, running "pear upgrade drush" on drush 4.5 did not work for me and just told me there were no updates. But pear upgrade did work and spit out a warning that the channel has changed.

If your version is old, you may need to run this first: "pear channel-update pear.drush.org"

```
[root@localhost ~]# pear upgrade drush
No releases available for package "pear.php.net/drush"

[root@localhost ~]# pear upgrade
WARNING: channel "pear.drush.org" has updated its protocols, use "pear channel-update pear.drush.org" to update

```

# Answer
> 0 votes
To install `drush` globally (for all users), here is one-liner:

```
sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush

```

On OS X/Unix, use this instead:

```
sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar && sudo chmod +x /usr/local/bin/drush

```

**Windows and other**

Download release from https://github.com/drush-ops/drush/releases, then execute via `php`.

---

See: Install/Upgrade a global Drush at docs.drush.org

---
Tags: drush
---


title: What all does node_save do?

text:
# Question
Title: What all does node_save do?
What all does `node_save` do? Is there a comprehensive list somewhere? What all happens besides saving all the field data to the db and calling `hook_node_save`?

# Answer
If you look at the source of the node\_save function, you will see that it does a bunch of things, among others:

* Resetting entity cache
* Calling presave hooks
* Updating access role tables
* Saving revisions
* etc...
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Leaflet - Possible to go straight to node instead of popup on click?
I'm using the leaflet module in drupal and would like the user to go directly to the node instead of a popup when clicking upon a marker or polygon. Is there a way to do this?

# Answer
The easier way is to use the IP Geolocation Views & Maps module, which works a treat! Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
> 1 votes

# Answer
Well this is not the most elegant way of achieving what I needed but it works until something better comes along. I modified a module called leaflet-views-ajax-popups in order to cannibalize the part of the code which gets the node id of the popup. Here's the replacment js;

```
 (function ($) {
 $(document).bind('leaflet.feature', function (event, lFeature, feature) {
 $(lFeature).click(function (e) {
  var data = {};
  for (var key in this._popup._contentNode.childNodes[0].attributes) {
    data[this._popup._contentNode.childNodes[0].attributes[key].name] =    this._popup._contentNode.childNodes[0].attributes[key].value;
 }
    var mytaxid = data['data-id'];
    window.location = 'taxonomy/term/' + mytaxid ;
 });
 });
 })(jQuery);

```

Still hoping someone can steer me to some simpler code.
> 0 votes

---
Tags: javascript
---


title: Entity view mode and form mode schema

text:
# Question
Title: Entity view mode and form mode schema
`node_type_example` module provides a file that defines form display configuration for a custom node type defined in this module. The file is named core.entity\_form\_display.node.basic\_content\_type.default.yml.

The example file clearly sets some field settings but is there a a schema for these config files? How to build my own config file for view mode and form mode?

# Answer
> 0 votes
First, form/user mode and form/user display isn't the same thing.

But the schema for all of them is in in `core/config/schema/core.entity.schema.yml`.

That said, I'm not sure why you want to *build* that file? Especially for a node type. Create the node type and the fields, configure the form and view displays in the UI, export it, add the files to your modules, don't. You don't have to build them yourself.

---
Tags: 8
---


# Question
Title: How to override views-view-field.tpl.php in custom module?
I am trying to override `views-view-field.tpl.php` in my custom module as suggested in override views-view-fields.tpl.php in custom module but looks like it's syntaxes are old.

**My codes are like:**

In `mymodule.info`

```
 ; $Id$

  name = My Module
  description = Create custom views template.
  package = Views
  dependencies[] = views
  core = 7.x

  files[] = mymodule.module
  files[] = includes/mymodule.views.inc

 ; Information added by drupal.org packaging script on 2011-07-21
  version = "7.x-4.1"
  core = "7.x"
  project = "mymodule"
  datestamp = "1311290520"

```

In `mymodule.module`

```
function mymodule_views_api() {
  return array(
   'api' => 3.0,
   'path' => drupal_get_path('module', 'mymodule') . '/includes',

   );
 }

function mymodule_theme($existing, $type, $theme, $path)
  {

   return array(
    'views_view_field__views__ticker' => array(
    'variables' => array('view' => NULL, 'options' => NULL,'row' =>NULL),
    'template' => 'views-view-field--views--ticker',
    'base hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'mymodule') . '/includes',

         ),
       );
    }

```

In `/mymodule/includes/mymodule.views.inc`

```
  function theme_views_view_field__views__ticker($vars) {

    $view = $vars['view'];
    $field = $vars['field'];
    $row = $vars['row'];

    return $vars['output'];
   }

  function template_preprocess_views_view_field__views__ticker(&$vars)
   {

    $vars['output'] = $vars['field']->advanced_render($vars['row']);
   }

```

My custom template file `views-view-field--views--ticker.tpl.php` in `/mymodule/includes`

```
 <?php print $output; ?>

```

**Problem:** it is not overriding `views-view-field.tpl.php`

I am using drupal version `7.41`

# Answer
You should add the template file on your module info file:

```
name = My Module
description = Create custom views template.
package = Views
dependencies[] = views
core = 7.x

files[] = mymodule.module
files[] = includes/mymodule.views.inc
files[] = includes/views-view-field--views--ticker.tpl.php

version = "7.x-4.1"
core = "7.x"
project = "mymodule"
datestamp = "1311290520"

```
> -2 votes

---
Tags: views, theming, hooks
---


title: Comment permission settings

text:
# Question
Title: Comment permission settings
Please kindly help if you know a solution for this or a ready module you may be aware of:

1:I need to set a node a way that each user can only see their own comment and replies to that. 2:Also I need for some nodes, a user can see other users comments, only when he/she has a comment on that node already. 3: A group can see only each other comments on a node.

I hope this can be done by a setting when we are creating a node.

Thanks in advance for any help.

# Answer
AFAIK there are no modules that provide the functionality of 1), 2) & 3) out of the box.

There is an awesome module Comment Permissions that can help you achieve better customization of comment permissions than Drupal core provides. You can take it as an example and expand the functionality that it already has to suit your needs.

> The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

Permissions provided by module (accessible via Permissions page & can be configured for each content type):

* administer comment settings on any page content
* administer comment settings on own page content
* comment on any page content
* comment without approval on any page content
* comment without approval on own page content
* edit own comments on page content

Hope this helps.
> 2 votes

---
Tags: users, comments
---


title: Pass NID to contact form

text:
# Question
Title: Pass NID to contact form
I have a website with a lot of furniture products. Each node page has a link to "ask for more info" that opens the sitewide contact form. When I receive the e-mail message, I need to know to which product (node) the request refers to, because many people forget to say it. So I need to pass node url, title or nid to the form in order to insert it automatically in the sent contact e-mail.

Thank you very much

# Answer
Working code, thanx to all for the help:

```
/**
 * Implements hook_mail().
 */
function mymodule_mail_alter(&$message) {
  if($message['id'] == 'contact_page_mail') {   // is contact_page_autoreply for the sender
    if (isset($_GET['nid'])){
        $node = node_load($_GET['nid']);
        $message['body'][] = "Ref #".$_GET['nid'].": " . $node->title . " [".$node->path."]";
    }
  }
}

```
> 0 votes

# Answer
this link "ask for more info" needs the nid appended as query string. and then in the form this can be used.
> 0 votes

# Answer
Looked at the code of the core contact module, the following line is important (contact.pages.inc:151):

```
// Send the e-mail to the recipients using the site default language.
drupal_mail('contact', 'page_mail', $to, language_default(), $values, $from);

```

By using hook\_mail in your module, you could modify the body of the $message, like in the following example:

```
/**
 * Implements hook_mail().
 */
function yourmodule_mail($key, &$message, $params) {
  ...
  if($key == 'page_mail') {
    $nid = $_GET['mynid'];
    ...
    $message['body'][] = "Thanks for ordering the product " . $node->title;
    ...
  }
  ...
}

```

Hope this helps!
> 0 votes

# Answer
Append a query string to your links (for example, /contact?nid=123). Now add the applicable field to your form (ie field\_nid) - it can be hidden. In the field settings specify a default value using the token module - the format should be \[current-page:query:nid\] where nid is the name of the query string parameter.
> 0 votes

---
Tags: entities, emails
---


title: How to export GMap configurations?

text:
# Question
Title: How to export GMap configurations?
I have a View block which renders a map through **GMap** formatter and includes two fields - *Company Name and Address*. When I export it through *features* and try to render it on another system, the map doesn't show up. I've given custom height and width and some other configurations in GMap under *Configurations \> Web Services \> GMap*. I think the problem is that the configuration settings for GMap are not being exported with the feature. Is it possible? If so, how to export them?

Here's an image of the View

# Answer
I found from my seniors that these **configurations** (in this case GMap configurations) are stored in *variables* and **Strongarm** module can be utilised to ***export*** them. After enabling Strongarm module, these variables will be available for exporting under *Strongarm Feature Component* in *Features UI*. The other system/environment on which these variables need to be imported will also need to have Strongarm module enabled.
Though these configurations were exported from my system and imported on the other system properly, the map still didn't show up on the other system, the reason being that the *devel generate* module which we were using to generate content of *Contact* content-type was unable to generate dummy latitude and longitude for the **Location** field (enabled through *Location* module). I entered those latitude and longitude values manually, saved the changes and vola! the map was rendered.
**Note:** In my case, I wasn't using a Google Maps API key so that wasn't a problem.
> 2 votes

---
Tags: views, location, google-maps
---


# Question
Title: Is there a way to create CSS image styles?
**Is there a way to assign css to image styles?**

I don't see any drop down for custom...

Would be nice to add img-responsive style to ALL images on the site...

Is there a module that can do that? Shouldn't it be native functionality?

# Answer
> 2 votes
What you are looking for is considered theming and is done mainly in the theme's template.php file.

There is a guide available here: Add bootstrap image css class to pictures

```
<?php
/**
 *
 */
function THEMENAME_preprocess_image_style(&$vars) {
        $vars['attributes']['class'][] = 'img-responsive'; // http://getbootstrap.com/css/#overview-responsive-images
}
?>

```

---
Tags: media
---


title: Log output to syslog

text:
# Question
Title: Log output to syslog
I run various Drush commands, including lots of queues, in a loop. I want to see the output in my syslog.

I am currently using `drush -r /var/www queue-run my_queue_name_here 2>&1 | logger`, which outputs the following line.

> Processed 2 items from the my\_queue\_name\_here queue in 0.58

This is OK, but I feel like this must be wrong. Surely many people want to direct Drush messages to the syslog. Is it possible without using the logger as above?

# Answer
This is not possible natively. You could write a Drush commandfile, and call `drush_set_context('DRUSH_LOG_CALLBACK', 'my_log_function');` to intercept log messages. See drush\_log() for details.

A pull request could be considered; it would need to fail gracefully if someone attempted to use it on a system that did not have syslog. Drush avoids platform-specific features where possible, though, which is probably why this has not been added as a standard feature to date.
> 1 votes

# Answer
I just found a possible solution from askubuntu.com - How do I log all input and output in a terminal session?

```
$script $HOME/yourlogfile.log
$drush {your command}
$exit
$cat $HOME/yourlogfile.log

```

Hope this works out for you. :)
> 1 votes

---
Tags: drush
---


# Question
Title: Display set of Views rows with different view modes
I have a Drupal 8 View with a set of rows, which are each rendered as a compact list teaser. Additionally I need to display those rows inside the same view in a another view mode (e.g. "grid teaser" with an extra image). As a result the visitor should be able to switch between the different view modes by toggling the display.

The template `views-view.html.twig` should contain this:

```
<!-- [...] -->
<!-- Display rows as list teaser -->
<div class="view-list row">
  {{ rows }}
</div>
<!-- Display rows as grid teaser -->
<div class="view-grid row">
  {{ rows_grid }}
</div>
<!-- [...] -->

```

I don't really know how to render those additional rows. I thought about using the hook `template_preprocess_views_view`:

```
function template_preprocess_views_view(&$variables) {

  // collect node ids
  $nids_rows = array();
  foreach ($variables['view']->result as $row){
    $nids_rows[] = $row->nid;
  }

  // load nodes
  $nodes_rows = Node::loadMultiple($nids_rows);

  if(!empty($nodes_rows)){
    // get views of nodes as grid
    $variables['rows_grid'][] = node_view_multiple($nodes_rows, 'grid');
  }
}

```

But the resulting render array is not in the same form like `$variables['rows']` and I'm not able to loop through those `rows_grid` to wrap them with specific html (like in `views-view-unformatted.html.twig`).

Is there a function like `view_load_rows($nids, $view_mode)`? Or is there a way to alter the render array with some additional keys like '#theme' to get a real `rows` render array?

Maybe there is even an much simpler way to accomplish this. Any Ideas?

# Answer
> 2 votes
You can add another view display and put it below the main view output using block or view attachment.

---
Tags: views, 8, entities
---


title: Entity error on add new user

text:
# Question
Title: Entity error on add new user
I am using Drupal 8.05

I am unable to add a new user. I get the following error when I press "Add User" button:

*Drupal\Core\Entity\Query\QueryException: 'field\_housing\_coop\_ref' not found in Drupal\Core\Entity\Query\Sql\Tables-\>ensureEntityTable() (line 252 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).*

'field\_housing\_coop\_ref' was an entity reference field (pointing to Content Type A) on Content Type B. I deleted the 'field\_housing\_coop\_ref' field and get the error.

If I recreate the field then I can add a new user. When I delete the field I get the error again.

I put this on the Drupal core issues list as support request but it got closed as not a reproducible error. So it seems to be something particular to my site.

Currently I have the field existing but unused and hidden on the form/display modes. Any idea about what I have done and how I might better resolve this much appreciated.

# Answer
***NOTE:Make sure to take backup of database before doing below changes to avoid any issues.***

Search for "**field\_housing\_coop\_ref**" field in entire database including cache tables, mostly **cache\_\*** and **key\_value** tables. Once you've all matching records with you, delete one by one very carefully by reading there names properly to make sure nothing else get deleted.

Once you've deleted matching records for "**field\_housing\_coop\_ref**" field, **rebuild cache** by navigating to "**Admin =\> Configuration =\> Development =\> Performance**" or using Drush command "**drush cr**".

**Updates:**

If there are any other references for this field inside other fields in key\_value table, make sure to delete those field from Field UI and then cross verify again.
> 1 votes

---
Tags: users, entities
---


# Question
Title: How can I replace all my internal links automatically?
I have changed the domain of my website from `www.mysite.com` to `mysite.net`. I upload the site to the new domain and all is fine, but I have more than one thousand nodes, and in almost all the nodes I have a link to another node on the site.

The link are absolute so they have this form: `www.mysite.com/node/22` and I need to change all nodes to the new domain.

Changing 1,000 links manually is too much. How can I do this automatically??

# Answer
> 8 votes
Why are you using absolute links? If you were using relative links, of the form */node/22*, the problem would not arise.

I am assuming you are using Drupal 7. The answer for D6 would be a little more complex.

If the links are in the node body, and if you have direct access to your database, you can update the text by running a query on the `field_data_body` and `field_revision_body` tables.

First, back up your database in case this goes wrong.

Then run the following query on your tables:

```
UPDATE field_data_body SET body_value = REPLACE( body_value, 'a href="http://www.mysite.com/','a href="http://mysite.net/');

```

Repeat with the `field_revision_body` table.

This should change all references to the old domain with the new domain.

If you have links in the comments, you might also want to do `field_data_comment_body` and `field_revision_comment_body`, scanning for references in the `comment_body_value` field.

In the event the links are being generated automatically by a text filter, change the REPLACE patterns accordingly.

# Answer
> 3 votes
You can use the Pathologic module to correct links in your contents.

# Answer
> 0 votes
A really nice module to help you do this is Search and Replace Scanner

Or if you prefer something simpler (as a drush command) without the interface you could use Drush Search & Replace

# Answer
> -3 votes
What you could do if you don't want to touch the db is using hook\_process\_html, so that you use relative path's for all content, scripts and stylesheets:

```
function MY_MODULE_process_html(&$vars) {
  //use relative path
  $vars['scripts'] = str_replace("http://www.mysite.com/", "/", $vars['scripts']);
  $vars['styles'] = str_replace("http://www.mysite.com/", "/", $vars['styles']);
  $vars['page'] = str_replace("http://www.mysite.com/", "/", $vars['page']);
}

```

# Answer
> -3 votes
Finally I use this http://interconnectit.com/products/search-and-replace-for-wordpress-databases/

Thanks a lot!!

---
Tags: navigation
---


title: Sending test mails locally

text:
# Question
Title: Sending test mails locally
I can't test sending emails with Drupal 7 on my local host. I have been searching for some solutions for more than 10 days but unfortunately the problem still exists.

Any help?

# Answer
> 1 votes
You can also use Maillog to test emails locally.

> Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally you can immediately display the mail through the devel dpm() facility.

# Answer
> 0 votes
Use toolheap which will work for windows. Add SMTP module and set in configuration of

**SMTP Authentication support \>\> SMTP SERVER SETTINGS**

SMTP server: smtp.gmail.com

SMTP port: 465

Use encrypted protocol: Use SSL

**SMTP Authentication support \>\> SMTP AUTHENTICATION**

Username: --emailid--

Password: --password--

Click SEND TEST E-MAIL.. Then Save. That's it.

# Answer
> 0 votes
If you are running on windows using something like xampp, you can do this without using the drupal smtp module:

1. edit your sendmail.ini
2. you will then need to set variables like:
smtp\_server=
smtp\_port=465
smtp\_ssl=auto
auth\_username=....
auth\_password=...
3. edit your php.ini and uncomment out sendmail line, for instance:

sendmail\_path = "\\"C:\xampp\sendmail\sendmail.exe\\" -t"

Then it should work once apache is restarted.

---
Tags: 7, emails
---


title: Flag the node after login

text:
# Question
Title: Flag the node after login
I am using flag module to bookmark the content. Authenticated user can normally flag the content. For anonymous user when they click on flag link it should go to login page. After successful login it should flag the node automatically.

I have the code for flagging the content, but I could find how to flag after login.

```
$flag = flag_get_flag('wishlist');
$flag->flag('flag', $nid, user_load($uid), TRUE);

```

# Answer
> 1 votes
You can try using hook\_node\_view for doing this. What it does is:

> Act on a node that is being assembled before rendering.

Here is an idea to try out:

```
/**
 * Implements hook_node_view
 */
function yourmodule_node_view ($node, $view_mode, $langcode) {

  // use a one-timer boolean for this action
  if(user_is_logged_in() && !isset($_SESSION['autoflagging_once']))
  {
    $_SESSION['autoflagging_once'] = true;
    $flag = flag_get_flag('wishlist');
    $flag->flag('flag', $node->nid, user_load($uid), TRUE);
  }

}

```

Good luck!

---
Tags: 7, flags
---


title: Drupal view filter by date

text:
# Question
Title: Drupal view filter by date
I have multiple events, each event can have multiple dates. When an events first end date is passed the event no longer shows, even though future dates are still available.

Current view filter settings:

I'm not sure what Date:delta(= 0) is but when it's removed, all versions of events are shown. Even though published filter is set it shows all unpublished and drafts.

I've been debugging this for several hours and would appreciate any help.

# Answer
I just tried such a Views configuration:

* Nodes with a Date field, with multiple dates
* Some nodes have dates only in the past, some only in the future, some in both.
* Configured a Views page with a simple date filter, when value is greater than now

Views filters:

And Views filters with end-date also works:

End result:

It seems to work out of the box, with the simplest setting for me. Regarding the delta, this is simply an index number for the value in a multiple value field, its position in the list.
> 1 votes

---
Tags: 7, views
---


title: EU Cookie Compliance module not working

text:
# Question
Title: EU Cookie Compliance module not working
got a problem with the EU Cookie Compliance module. I installed it and it only worked when you were logged in (my site uses SSL). Then I realized I hadn't set the permissions so that the cookies message is displayed to Anonymous users. Now the message doesn't appear to anyone, logged in or not. I've made sure the cookie is deleted from the browser, but still no luck. Any ideas please?

The site is http://idea.nottingham.ac.uk.

No message displayed for anyone since I added Display permissions for anonymous users. Before, it wasn't displaying message for 'guests', only logged in users.

Interestingly, it does work (for both guests and logged-in users) on my Bitnami development copy of the website where SSL is switched off.

# Answer
> 0 votes
I used something else in the end as I couldn't get the module to work, so used cookieassistant.com in the end. As for the speed, thanks for that, I think it's down to good hosting to be honest. – pixelshrink

---
Tags: 7
---


# Question
Title: I can't login to Drupal as my session cookie was deleted?
I'm using Drupal 7, and have Pound running in front of Varnish for HTTPS. I can browse the site via HTTPS, but can't login - each time I do, the server returns a 403 forbidden error. Any ideas as to what is causing this? I'm guessing something may need to be changed in `settings.php`, but not sure.

Output from Firebug:

**POST user**

*Response Headers*

```
Accept-Ranges   bytes
Age 0
Cache-Control   no-cache, must-revalidate, post-check=0, pre-check=0
Connection  keep-alive
Content-Length  0
Content-Type    text/html; charset=UTF-8
Date    Tue, 09 Oct 2012 17:49:08 GMT
Etag    "1349804948"
Expires Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified   Tue, 09 Oct 2012 17:49:08 +0000
Location    https://drupal.domain.com/user/2
Server  Apache
Set-Cookie SESSe15687525d17b8ec181665a71c88775c=EttXyyPvqESdU4RapW7xZkrRagGNHgRH5I9P6x0yRRE; expires=Thu, 01-Nov-2012 21:22:28 GMT; path=/; domain=.drupal.domain.com; httponly SSESSe15687525d17b8ec181665a71c88775c=mAdWa_a_OvcIIoWBuiVbLqFJzwyHiukfd_xBOVz_eaQ; expires=Thu, 01-Nov-2012 21:22:28 GMT; path=/; domain=.drupal.domain.com; secure; HttpOnly
Via 1.1 varnish
X-Drupal-Cache  MISS
X-Varnish   2081364495

```

*Request Headers*

```
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Connection  keep-alive
Cookie  has_js=1; __utma=194497400.1529654640.1349804906.1349804906.1349804906.1; __utmb=194497400.3.10.1349804906; __utmc=194497400; __utmz=194497400.1349804906.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
DNT 1
Host    drupal.domain.com
Referer https://drupal.domain.com/user
User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1

```

**GET 2**

*Response Headers*

```
HTTP/1.1 403 Forbidden
Server: Apache
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified: Tue, 09 Oct 2012 17:49:08 +0000
Cache-Control: public, max-age=300
Etag: "1349804948-1"
Content-Language: en
X-Generator: Drupal 7 (http://drupal.org)
Set-Cookie: SSESSe15687525d17b8ec181665a71c88775c=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.drupal.domain.com; secure; httponly
SESSe15687525d17b8ec181665a71c88775c=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.drupal.domain.com; httponly
Vary: Cookie,Accept-Encoding
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Content-Length: 8916
Accept-Ranges: bytes
Date: Tue, 09 Oct 2012 17:49:09 GMT
X-Varnish: 2081364496
Age: 0
Via: 1.1 varnish
Connection: keep-alive

```

*Request Headers*

```
GET /user/2 HTTP/1.1
Host: drupal.domain.com
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Referer: https://drupal.domain.com/user
Cookie: has_js=1; __utma=194497400.1529654640.1349804906.1349804906.1349804906.1; __utmb=194497400.3.10.1349804906; __utmc=194497400; __utmz=194497400.1349804906.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); SESSe15687525d17b8ec181665a71c88775c=EttXyyPvqESdU4RapW7xZkrRagGNHgRH5I9P6x0yRRE; SSESSe15687525d17b8ec181665a71c88775c=mAdWa_a_OvcIIoWBuiVbLqFJzwyHiukfd_xBOVz_eaQ

```

# Answer
> 1 votes
Pound passes along the client IP appropriately, but it needs to be forcibly set for non-https (http) requests to Varnish.

```
if (req.http.X-Forwarded-Proto !~ "https") {
  remove req.http.X-Forwarded-For;
  set req.http.X-Forwarded-For = client.ip;
}

```

# Answer
> 0 votes
I had the same issue when I have enabled such settings in my sites/default/settings.php file:

```
$base_url = 'https://shkodenko.com';  // NO trailing slash!
$conf['https'] = TRUE;

```

I have fixed this by adding .htaccess mod\_rewrite rules:

```
# Force SSL for user login
RewriteCond %{REQUEST_URI} ^/user/login
RewriteCond %{SERVER_PORT} !443
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

```

# Answer
> 0 votes
You may want to configure your Varnish 3 with Drupal 7 by checking this page: Configure Varnish 3 for Drupal 7.

Based on your 2nd GET response, the interesting part of it is the header which is:

```
Set-Cookie: SSESSe15687525d17b8ec181665a71c88775c=deleted

```

which means this cookie was deleted (most likely by Varnish), so you need to setup `req.http.Cookie` in your configuration to allow `SESS`/`SSESS`-like cookies, so they can remain for your session, otherwise other cookies may be removed (`unset req.http.Cookie`).

Here is the relevant part of `.vcl` config file to parse respond to incoming Drupal requests:

```
# Respond to incoming requests.
sub vcl_recv {
  # Use anonymous, cached pages if all backends are down.
  if (!req.backend.healthy) {
    unset req.http.Cookie;
  }

  # Allow the backend to serve up stale content if it is responding slowly.
  set req.grace = 6h;

  # Pipe these paths directly to Apache for streaming.
  #if (req.url ~ "^/admin/content/backup_migrate/export") {
  #  return (pipe);
  #}

  if (req.restarts == 0) {
    if (req.http.x-forwarded-for) {
      set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
    }
    else {
      set req.http.X-Forwarded-For = client.ip;
    }
  }

  # Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
      req.url ~ "^/update\.php$" ||
      req.url ~ "^/admin$" ||
      req.url ~ "^/admin/.*$" ||
      req.url ~ "^/flag/.*$" ||
      req.url ~ "^.*/ajax/.*$" ||
      req.url ~ "^.*/ahah/.*$") {
       return (pass);
  }

  # Do not allow outside access to cron.php or install.php.
  #if (req.url ~ "^/(cron|install)\.php$" && !client.ip ~ internal) {
    # Have Varnish throw the error directly.
  #  error 404 "Page not found.";
    # Use a custom error page that you've defined in Drupal at the path "404".
    # set req.url = "/404";
  #}

  # Always cache the following file types for all users. This list of extensions
  # appears twice, once here and again in vcl_fetch so make sure you edit both
  # and keep them equal.
  if (req.url ~ "(?i)\.(pdf|asc|dat|txt|doc|xls|ppt|tgz|csv|png|gif|jpeg|jpg|ico|swf|css|js)(\?.*)?$") {
    unset req.http.Cookie;
  }

  # Remove all cookies that Drupal doesn't need to know about. We explicitly
  # list the ones that Drupal does need, the SESS and NO_CACHE. If, after
  # running this code we find that either of these two cookies remains, we
  # will pass as the page cannot be cached.
  if (req.http.Cookie) {
    # 1. Append a semi-colon to the front of the cookie string.
    # 2. Remove all spaces that appear after semi-colons.
    # 3. Match the cookies we want to keep, adding the space we removed
    #    previously back. (\1) is first matching group in the regsuball.
    # 4. Remove all other cookies, identifying them by the fact that they have
    #    no space after the preceding semi-colon.
    # 5. Remove all spaces and semi-colons from the beginning and end of the
    #    cookie string.
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|SSESS[a-z0-9]+|NO_CACHE)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");

    if (req.http.Cookie == "") {
      # If there are no remaining cookies, remove the cookie header. If there
      # aren't any cookie headers, Varnish's default behavior will be to cache
      # the page.
      unset req.http.Cookie;
    }
    else {
      # If there is any cookies left (a session or NO_CACHE cookie), do not
      # cache the page. Pass it on to Apache directly.
      return (pass);
    }
  }
}

```

If you're using other modules which defines alternative cookies (such as OpenAM), you need to modify the regex for Cookie pattern accordingly, e.g.

```
set req.http.Cookie = regsuball(req.http.Cookie, ";(_MYCOOKIE_[a-z]+_[a-z]+|SESS[a-z0-9]+|SSESS[a-z0-9]+|NO_CACHE)=", "; \1=");

```

---
Tags: 7, users, cookies, proxies, ssl
---


# Question
Title: Which cache have to clear to update new hooks?
I added a new hook inside a module (hook\_cart\_commerce\_pricecomponent\_type\_info\_alter), which cache have to clear to only update that new hook? I mean i do not want to clear all caches.

Administration menu? Class registry? Menu? Page and else? Theme registry? Token registry? Update data?

# Answer
> 3 votes
To register a new hook, you can clear the following caches:

```
cache_clear_all('module_implements', 'cache_bootstrap');
cache_clear_all('hook_info', 'cache_bootstrap');

```

More info: https://api.drupal.org/api/drupal/includes%21module.inc/function/module\_implements/7

# Answer
> 1 votes
If using drush, `drush cc registry` will suffice for that hook.

# Answer
> 0 votes
**Theme Registry**

> The most common case for manually registering hooks is in forms. Form elements are them-able but there is another dimension to how they are processed. There are the generic elements such as check-boxes, radio selects, submit button, drop down menus, etc. Each element is them-able on its own and overriding it does not require manually registering the hooks associated with it. The extra dimension comes in with custom forms where each element is arranged in very specific ways. In some forms, they are already arranged, themed and registered. For these forms, manually registering is not required. The forms that are not explicitly themed will default to how form API renders them.

# Answer
> 0 votes
You can use:

# Answer
> -1 votes
You can rebuild the registry to force Drupal to re-scan the code files and register your hook implementations. To do this with `drush`:

1. Before first use, install `registry_rebuild`:

```
drush dl registry_rebuild

```
2. Rebuild the registry:

```
drush rr

```

This worked for me in a case where both `drush cc registry`, `drush cc all` and clearing the `hook_info` and `module_implements` caches failed.

---
Tags: 7, hooks, caching
---


# Question
Title: How do Pressflow Drupal sites handle user Cookies?
Is this something handled by Drupal? What PHP, Apache, Varnish settings affect cookies?

Additionally, what's the difference in cookie handling between plain-vanilla Drupal and Pressflow?

I was seeing that in `drupal_session_commit()` boostrap.inc calls session\_destroy():

> `session_destroy()` destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, `session_start()` has to be called.
>
> In order to kill the session altogether, like to log the user out, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. `setcookie()` may be used for that.

Apparently in Pressflow drupal\_session\_commit() gets called on every page like this:

```
// Perform end-of-request tasks on every page.
drupal_page_footer(), common.inc
    // Write the session, and open one if needed.
    drupal_session_commit(), bootstrap.inc
        // If our user is anonymous, Pressflow "Destroys empty anonymous sessions"
        // Destroy all data registered to a session
        session_destroy();
            // Called by PHP session handling with the PHP session ID to end a user's session.
            sess_destroy_sid($sid), session.inc

```

What implications, if any, does this have for user tracking in software like Omniture and Google Analytics?

See related post to cookies here: https://stackoverflow.com/questions/871283/how-do-tracking-cookies-work

Link to Pressflow documentation.

# Answer
Cookies/sessions are handled by both Drupal and PHP. Drupal register some functions that PHP will call, when certain things need to happen, like destroying a users session. PHP handles most of the basic stuff and Drupal override some of it, store users sessions in the database.

I'm not familiar with Omniture but if it's anything like GA, a users session/cookie wont effect tracking at all. Cookies are used to identify the user, so they don't have to type in their username/password at every page. Without cookies, Drupal wouldn't be able to tell the users apart and would need some other form of identification, like a login for every new page load.

This is why, some people try to steal cookies, as that is the same as having the user log in and leave the computer, given the thief full access.
> 3 votes

# Answer
**1) Is this something handled by Drupal?**

Drupal does handles cookies, but it only handles it's own first party cookie. Like @googletorp said, Omniture and Google Analytics use their own cookies.

**2) What PHP settings affect cookies?**

`drupal_session_initialize()`, on boostrap.inc calls `session_set_save_handler()`, which overrides PHP's default session handling funcitons with Drupal's.

On Pressflow, at the end of every page, `drupal_page_footer()` is called. The code shows that if the user is anonymous, Pressflow deletes the current session id from the database and empties any cookies that might have been set. Refer to `sess_destroy_sid()` on session.inc.

**3) What Varnish settings affect cookies?**

Both Google Analytics and Omniture are able to generate visitor statistics without cookies because statistics are generated using hard-coded image requests (web beacons). However, *in order to track **persistent statistics** (how often x user comes to my page), Omniture issues a cookie with an unique user ID* \- and when that user comes back to my page, he presents me with that cookie and I can say "OK, user x visited me for second time this week, and third time this month, and so on". This is done using **persistent cookies**, which are an actual file sitting in the user's computer.

The problem with Varnish is that it is generally set to strip cookies from the request because *if the request comes with a cookie attached to it, then Varnish doesn't serve a cached page*. Because Omniture sets these cookies for every user out there, it means that if you don't strip the Omniture cookie from the request, Varnish is never going to serve a cached page.

So it's either you track persistent statistics, or you find a way to pass that cookie through Varnish, and yet manage to serve the cached page, which is something I haven't heard of yet.
> 1 votes

# Answer
The real answer is that both Google Analytics and Omniture use specific cookies (not the cookies used by Drupal), and perform their tracking completely independently of Drupal sessions.

The new session handler introduced by Drupal 7 (and later backported to Drupal 6) in Pressflow does not interfere with either Google Analytics or Omniture tracking of users.

For the same reasons, cookie-stripping in Varnish do not interfere with the tracking of users.
> 0 votes

# Answer
All components handle user cookies on different levels.

Web browsers sets the cookies and make sure they're passed over to the next requests based on the domains criteria and expiration date (as par of a HTTP header).

Drupal reads cookies via PHP (`setcookie`/`session_destroy`) functions and authenticate the users.

Varnish parses incoming requests and decides whether page should be cached or not and it may have the logic to keep, modify or drop all other cookies that Drupal doesn't need to know about. Here is example Varnish logic (in `.vcl` file config) as result of configuring Drupal with Varnish:

> 1. Append a semi-colon to the front of the cookie string.
> 2. Remove all spaces that appear after semi-colons.
> 3. Match the cookies we want to keep, adding the space we removed previously back. (\1) is first matching group in the regsuball.
> 4. Remove all other cookies, identifying them by the fact that they have no space after the preceding semi-colon.
> 5. Remove all spaces and semi-colons from the beginning and end of the cookie string.
> 6. If there are no remaining cookies, remove the cookie header. If there aren't any cookie headers, Varnish's default behavior will be to cache the page.
> 0 votes

---
Tags: 6, cookies
---


title: Update $form based on $form_state

text:
# Question
Title: Update $form based on $form_state
Shouldn't the form generating function get executed every time the form is rendered? Because I need to update some field suffixes based on the `$form_state` values and I don't know how to do this.

I have something like this:

```
function xxxx_some_form($form, &$form_state){
  $form["some_field"] = array(
    "#type" => "textfield",
    "#required" => true,
    // bla bla bla
  );
  drupal_set_message("whatever");
  $form["actions"]["do_action"] = array(
    "#type" => "submit",
    "#value" => t("Do action"),
  );
  return $form;
}

```

When I submit the form, the validation messages are displayed ( Eg: X field is required ) but the message from `drupal_set_message("whatever")` is not displayed.

Also, no other logic is executed there.

# Answer
> 1 votes
When a form has a validation error, the form is rebuilt from cache, meaning that the form function isn't invoked.

I could move the `drupal_set_message` call over to a `#process` or `#preprocess` function on the form itself or on one of the methods. These should be called again.

If the form is displayed with `hook_menu` you could also make a callback function which calls `drupal_set_message` and then fetches the form. There are a lot of ways to get around this.

# Answer
> 0 votes
Are you trying to get the form to be interactive? Have you looked at the #states ability of the form which lets you set up conditional display of other fields, markdown elements, etc?

Field suffixes sounds like a very weird thing to modify on form submission, since the expectation with a submission is that the user is now done with the form. And as for the messages, it is possible the template for the page you are working with does not have the message print lines.

---
Tags: 7, forms
---


# Question
Title: How to get data from previous step in Drupal commerce checkout process
I have Drupal commerce checkout process where user choose shipping and in next step choose payment method.

I need data about chosen shipping in payment method form alter.

Is there any way how can i get info about chosen shipping in payment method form alter?

# Answer
I have found solution.

```
global $user;
$order = commerce_cart_order_load($user->uid);
$line_items_ids = array();

// get all line items IDs
foreach($order->commerce_line_items as $line_item){
  $line_items_ids[] = $line_item["line_item_id"];
}

// load only "shipping" line items
$shipping_line_items = commerce_line_item_load_multiple(
  $line_items_ids,
  array('type' => 'shipping'),
  FALSE
);

```

I haven't found cleaner way how to do this. Hope it helps somebody. I still would be glad if anyone knows how to do this better.
> 2 votes

---
Tags: commerce
---


# Question
Title: How to change "to" to "-" while displaying start and end date in views?
When using views to display start and end date by default it adds "to" text in between two dates, I was wondering what is the appropriate way to convert "to" to "-" or anything else.

Thanks

# Answer
My answers assume I have a field called "field\_event\_date" which shows as Content: Event Date in my view.

**Answer #1 - Use View Template**

1. Under the Advanced Section of the view, under the Other section, open Theme Information
2. Copy the filename of the last theme option for Field Content: Event Date, in my case it will be views-view-field--VIEWMACHINENAME--BLOCKMACHINENAME--field-event-date.tpl.php
3. Copy the following into it:

```
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php print date("Y-m-d H:i:s", strtotime($row->field_field_event_date[0]["raw"]["value"])); ?>
 -
<?php print date("Y-m-d H:i:s", strtotime($row->field_field_event_date[0]["raw"]["value2"])); ?>

```

This will output something like 2014-08-09 20:15:00 - 2014-08-12 20:15:00, format using the date() format string.

**Answer #2 - Use View Fields**

1. Under Fields, add Content: Event Date and set the Display to "Start Date Only"
2. Under Fields, add Global: Custom Text and set Text to -
3. Under Fields, add Content: Event Date and set the Display to "End Date Only"
4. Under Field Settings, Set the three fields above as Inline.

This will output something like Sunday, December 1, 2013 - 12:00 - Sunday, December 1, 2013 - 12:00, based on the format you have chosen.
> 9 votes

# Answer
Although the answer above is correct, it is best practice not to use php in a TPL like this. Drupal comes with a bunch of fancy API's, one of the is the template\_preprocess\_views\_view\_fields (As seen here)

In your template.php do this:

```
function YOURTHEME_preprocess_views_view_fields(&$vars) {
 if($vars['view']->name == 'YOUR_VIEW') {
  if (strpos($vars['fields']['YOUR_FIELD']->content,'to') !== false) {
    $vars['fields']['YOUR_FIELD']->content = str_replace('to','-',$vars['fields']['YOUR_FIELD']->content);
  }
 }
}

```
> 4 votes

# Answer
In Date 7.x-2.8 and higher, the entire "start date to end date" string is translatable. This means that an easy way to do change the "to" to a "-" is to use the String Overrides module. Simply download and enable the module, then visit /admin/config/regional/stringoverrides. On that page, add "!start-date to !end-date" (without quotes) under "Original" and "!start-date - !end-date" (without quotes) under "Replacement." Click save. You may also need to flush you site's caches before seeing the change.

One benefit to this method is that it will change the "to" to a "-" on nodes *and* views at once.
> 3 votes

---
Tags: views
---


# Question
Title: D8 HTML tags from field converted to special characters when printing variables
I have WYSWYG editor enabled on my fields when there is html in these fields. When I print out the variables in my template, the html gets converted to special characters.

for example my print statement

```
{{ node.field_hours.value }}

```

My full HTML in the field becomes this.

```
 <li>Camping : <p><strong>Equestrian, Group and Primitive Sites:</strong></p> <li>46 miles of marked multiuse trails.</li> <li>Florida law requires bicyclists under 16 to wear helmets.</li> </ul>

```

Bird Watching :

- Site 64 on western section of
```
<ul>

```

# Answer
it was autoescaped so |raw filter worked http://twig.sensiolabs.org/doc/tags/autoescape.html
> -2 votes

# Answer
It is unsafe to print raw data from a field value.

Instead of using `{{ node.field_hours.value }}` put this in your node template:

```
{{ content.field_hours }}

```

This will print out the field as configured in the view mode. In the view mode you can select a text filter that matches the allowed tags of the ckeditor. In Drupal 8 all necessary text formats are predefined to be used together with ckeditor.
> 3 votes

# Answer
It seems as if the `<strong>` tags are not allowed by your input formats.

Go to `/admin/config/content/formats`, click on "Configure" for the text format you are using, make sure that the "Limit allowed HTML tags and correct faulty HTML" checkbox is checked.

Once it's checked, make sure that under the tab with same name there is `<strong>` tag listed. If it's not there, just add it to the end of that field.

For example:

```
<a href hreflang> <li> <strong> # and so on

```

Hope this helps.
> 0 votes

---
Tags: 8
---


# Question
Title: Strict warning: Only variables should be passed
In Drupal 7. I am printing a cck field image to my page.tpl like this

```
<?php print render(field_view_field('node', $node, 'field_slide_photo1',
array('label'=>'hidden'))); ?>

```

and I get this error php Strict warning: Only variables should be passed by reference in include() (line 59 of var/www/html/upgrade2a/sites/all/themes/themea/page.tpl.php

But I can use this in node.tp with out errors? print render($content\['field\_upload\_thumbnail'\]);

How do a print a field that is available in the page template?

# Answer
You should attrubute the result of function to variable and then pass to render. The difference is that in sencond case you're passing certain variable instead of result of function.
> 5 votes

---
Tags: 7, theming
---


# Question
Title: Dependency Injection in Custom Field Widget
I am trying to inject the entity query service into a custom field widget. This is the relevant code:

```
/**
 * Plugin implementation of the 'address_options' widget.
 *
 * @FieldWidget(
 *   id = "address_options",
 *   label = @Translation("Addresses"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class MyCustomWidget extends WidgetBase {

  /**
   * The entity query factory service.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQuery;

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, QueryFactory $entity_query) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityQuery = $entity_query;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity.query')
    );
  }

```

The following error results:

> Recoverable fatal error: Argument 6 passed to Drupal\custom\_module\Plugin\Field\FieldWidget\AddressWidget::\__construct() must be an instance of Drupal\Core\Entity\Query\QueryFactory, none given, called in /homedir/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line 130.

Is it not possible to use dependency injection in this case or am I missing something?

# Answer
> 20 votes
What you are missing is to implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface, which defines the create() method.

See \Drupal\file\Plugin\Field\FieldWidget\FileWidget for an example.

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


# Question
Title: Avoid duplicate entries when programmatically adding field values
This pretty cool answer taught me to push new term references like this:

```
$node->field_tags[] = 6;

```

... but if that reference already exists you get a duplicate.

This isn't possible through the UI and isn't what you would usually want. The duplicates show up in the rendered view.

Here's the horrible thing I did to check for the reference I'm trying to add:

```
$term_refs = $node->field_tags->getValue();
$has_ref = count(array_filter($term_refs, function ($term_ref) use($tid) {
return in_array($tid, $term_ref);
  }));
if (!$has_ref) $node->field_tags[] = $tid;

```

Is there a **hasValue()** method or **magic PHP function** I'm missing that I can use instead?

The structure of `$term_refs` (the `field_tags` value) looks like this:

```
Array
(
    [0] => Array
        (
            [target_id] => 6
        )

)

```

**Update:** Clive's solution is what I'm looking for but I couldn't get this to work. So I modified George's answer to this so I can skip existing refs:

```
if (in_array($tid, array_map(function ($i) { return $i['target_id']; }, $term_refs))) continue;

```

# Answer
> 1 votes
array\_unique could solve your problem here, perhaps employing a similar solution to the one proposed in https://stackoverflow.com/questions/10408482/how-to-get-unique-value-in-multidimensional-array

---
Tags: 8
---


# Question
Title: Compress Images that are already uploaded
I working on a website which has a content type. The content type contains an image field. Thousands of images uploaded already. Because image size is very big, there is requirement to compress the size of images.

I found a module Image API Optimize, but this module works only when a new image is uploaded. But my requirement is that I want to compress the images which are already uploaded.

Can anybody help me solve this problem?

# Answer
A module like Max Image Size will resize the original images that have already been uploaded, but I don't believe it is possible to also use an optimization on the images when they are resized. You can only specify a new maximum width and height.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Ubercart - Stay on page when you add product to cart
In Ubercart, each time i add a product to the cart, i'm redirected to the cart page. Then i have to click on the link "continue shopping". Is there an option to stay on the actual page after adding product to page?

# Answer
Yes.

```
1. Log in as admin, and go to: admin/store/settings/cart
2. Click on Basic Settings
3. Then in the "Add to cart redirect" section, enter: <none>
4. Got to "Continue Shopping Element" and set "Make continue shopping go back to the last item that was added to the cart."

```
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: How can I reduce the file sizes of the original versions of uploaded image files?
I have a Drupal 7 site that allows users to upload pictures of themselves. While the pictures aren't using much space on the server's filesystem now, I am worried that if my membership grows substantially I will have to add more space to cover all the images.

Right now, I allow users to upload images up to 10 MB in size. I want to leave this limit high if possible because many of my users are not technically skilled and they do not know how to resize their images.

At the same time, the largest resolution that will be used on the site is 1024x1024. So, I have configured the core image field to automatically scale down the images to 1024x1024. This significantly reduces the file size.

Are there any other ways to automatically reduce the size of uploaded images? Please note that I am talking about **the original files, not image styles**.

# Answer
A module like Max Image Size will resize the original images that have already been uploaded, you can specify a new maximum width and height.
> 1 votes

# Answer
Interesting question - this should be a standard option on community distributions to avoid the space issue you raised but you're right that the focus seems to be on image styles as a solution..

Two ways to handle this

* More custom way would be to add a hook\_form\_alter to your form that would add a submit handler to resize the image file after uploaded to the correct size -- if you are able to do image styles than your server already has the image libraries needed to do this.
* An easier way would be to use an uploader that can be configured to do this work for you on the upload. One example is the plupload module / widget which has a clientside resize option during the upload (also saving bandwidth)

> ```
> resize
>
> Enables plupload to resize the images to clientside to the
> specified width, height and quality. Set this to an object with those
> parameters.
>
> ```
> 2 votes

# Answer
I love your question, because it's exactly what I am looking to do. In fact, I think it'd make a great module to:

* Allow virtually any size/dimension images
* Resize the stored Original behind the scenes to some web-reasonable maximums (even larger than reasonable but well below 2MB) and discard the uploaded bloat
* Other image style / imagecache settings apply against the new original as normal

Then as a maintenance task, say, on activation of said module, the meat of the process runs and smashes down all originally uploaded biggies the way you (and I) both came here to find a way to do.

To answer specifically your original question, I think a mogrify op may be in order. It's part of ImageMagick (sic), like one of either:

```
mogrify -define jpeg:extent=567KB *.jpg
mogrify -geometry 1024 *.jpg

```

Here, I'm showing the -geometry switch constraining to 1024 px wide and whatever proportionate height. 1024 square would be 1024x1024.

Note, other examples on the web include a "-path" directive which didn't work for me, I presume because of an ImageMagick version difference.
> 1 votes

# Answer
you could hook in to "theme\_image\_style()" and do a check on every image for size every time it loads.

if I was doing it though, since it's just a one time thing, you may be better off doing a bootstrap and writing your own script to resize.
> -1 votes

---
Tags: media
---


# Question
Title: How to batch upload images and generate multiple images
I am planning my new website with Drupal 7. The site will have two core features: blog and photos. Blog is no problem and for photos I know how to implement most of my requirements. Except one ;-)

I plan to add a content-type "Photos" (or "Media"). Each photo will be stored in its content. These contents are categorized using a taxonomy so each photo can be in multiple terms (aka albums). For example a whale can be in "Underwater", "Big-fish" and "Salt water". Views with contextual filters will render the "album"-views etc. So far no problem.

What we don't know how to do yet is bulk-upload of images. Any idea would be great. If there is a gallery module or profile that handles that taxonomy thing / dynamic albums it would be an option to.

Idea: Maybe I can define a "Bulk-Upload" content type which is for uploads only. This conent-type has an "image" field set to "unlimited". When creating such a content a Rule will be triggered which creates multiple "Images" contents for it and deletes the "Bulk-Upload" content afterwards. ...sounds possible but a little tricky.

Any ideas?

Thanks and cheers, Marc

# Answer
To upload more than one image to a field you can change the number of values the field will accept:

To get a photo album configuration you could also look at the node\_gallery module, or roll your own arrangement.

The plupload module will allow you to select multiple images to be uploaded into a single field through one upload process.
> 0 votes

---
Tags: 7, media, files
---


title: Create Custom Search and result page

text:
# Question
Title: Create Custom Search and result page
I am trying to create a custom search page with two input fields.

**Company Name** and **Certification Code** are two fields to be entered by user.

I have a content type called **certification** and the search will be performed based on this Content type.

A field collection is used to enter certifications details(*Certificate Name ,Certificate Number ,Certificate ,Issuing Date: ,Date of Expiry*).

The result page will separated one or under the same page of search form.

I tried many ways and i am not convinced with the results. I created a page node--certification.tpl to show the result

Here i want two things :

1. In the search page Two input fields to be entered ,the combination of two items in content type(company name,Certificate number.) Here certificate number is a field collection value.I couldn't search from the field collection.I used **custom search** module.
2. Show the result in this page directly when we search from the search page instead of showing the intermediate result page.

**Search Page**

**Search Result looks like**

I hope someone will help me to get a perfect search page.

# Answer
> 1 votes
Installing module or modifying .tpl files are not required to get a simple search page.

Creating a view and using Exposed Filters setting will get the job done.

Providing you high level steps below, you may need to research a bit more to accomplish this task.

**Steps**

1. Create a View.
2. Choose "Table" in Format section.
3. Add "Certificate Name ,Certificate Number,Certificate,Issuing Date,Date of Expiry" in field section.
4. In filter criteria, select your content type.
5. Also add "Company name, Certificate number" in the Filter Criteria.
6. Click Advanced \> Better Exposed Forms \> Better Exposed Filters.
7. Expose the fields "Company name & Certification number" as text fields.
8. You can expose this fields as a Drupal Block and assign it anywhere in the page.

---
Tags: search
---


title: How can I add a "no result" text?

text:
# Question
Title: How can I add a "no result" text?
I am using contextual filters to populate a view.

How can I display a text like *No results found* when the view doesn't show any result?

# Answer
It's under 'Advanced' on the right hand side. Then 'add' a NO RESULTS BEHAVIOUR.
> 4 votes

# Answer
You can also add a "no results behavior" view element in code in your own module.

That's useful if the element has to be dynamic – in the example below, it's a configurable button to add content to the view. (Content is added to an OG group with a node ID supplied as contextual filter parameter to the view.)

```
/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  if($view->name != 'my_view_machine_name') {
    return;
  }

  if (isset($view->args[0])) {
    $target_group_nid = $view->args[0];
    $button_html = _generateButtonHtml($target_group_nid);

    // Create a "Global: Textarea" view element.
    $options = array(
      'id' => 'button2',
      'table' => 'views',
      'field' => 'area',
      'empty' => FALSE,
      'content' => '<div>No results yet. Add one:</div>' . $button_html,
      'format' => 'filtered_html',
      'tokenize' => 0,
    );
    $view->set_item('default', 'empty', 'button2', $options);
  }
}

```

Note: `_generateButtonHtml()` is just a stub for your own function to return HTML code for a button.

**Relevant API docs:**
> 3 votes

---
Tags: 7, views
---


# Question
Title: Why does nothing change when I attempt to restore a backup?
I have a drupal 7.43 installation and it has been doing regular backups using the Backup and Restore module. I wanted to do a restore but I'm blocked at every turn it seems. I go to Configuration \>\> System \>\> Backup and Migrate \>\> Saved Backups and click on "restore" next to the one I want to restore from. I get a new page where I choose "Entire Site" to restore to, as that is what I'm backing up, and then click "Restore." That takes me to a white page. When I reload my site, nothing has changed, so I assume this means failure, although I have no way of knowing what failed or why that I can tell.

So I tried drush:

```
drush bam-restore archive scheduled drupal.xxxxx.net-2016-03-21T09-44-17.sitearchive.tar.gz

```

This gave me a mysterious error:

> Restoring will delete some or all of your data and cannot be undone. ALWAYS TEST YOUR BACKUPS ON A NON-PRODUCTION SERVER!
> Are you sure you want to perform the restore? (y/n): y
> PHP Fatal error: Call to undefined function file\_directory\_path() in /var/www/drupal.wealthychef.net/public\_html/sites/all/modules/backup\_migrate/includes/sources.archivesource.inc on line 211
> Drush command terminated abnormally due to an unrecoverable error.
> Error: Call to undefined function file\_directory\_path() in /var/www/drupal.wealthychef.net/public\_html/sites/all/modules/backup\_migrate/includes/sources.archivesource.inc, line 211

Can someone help me understand how to restore my site?

# Answer
This sounds like a bug of Backup and Migrate module, since `file_directory_path()` no longer exists in Drupal 7.

So instead of `file_directory_path()` you should use:

```
file_stream_wrapper_get_instance_by_scheme(file_default_scheme())->getDirectoryPath()

```

or:

```
variable_get('file_public_path', conf_path() . '/files')

```

So please upgrade your module to development version (but it's not fixed yet at time of writing) or use this patch available at: #2618516 - Fatal error when restoring "Entire Site" which goes like:

```
--- a/includes/sources.archivesource.inc
+++ b/includes/sources.archivesource.inc
@@ -208,7 +208,7 @@ class backup_migrate_files_destination_archivesource extends backup_migrate_dest

       // Move the files from the temp directory.
       if ($filepath && file_exists($filepath)) {
-        _backup_migrate_move_files($filepath, file_directory_path());
+        _backup_migrate_move_files($filepath, variable_get('file_public_path', conf_path() . '/files') );
       }

```
> 3 votes

# Answer
Depending on your version of the Backup Migrate module you may have this bug https://www.drupal.org/node/2618516 \- try upgrading the Backup Migrate module and see if you can then restore.

Don't forget to search Google/Duckduckgo/your-favourite-search-engine for issues, and if it is related to a specific module there is no harm in looking in the issue queue for similar issues...
> 1 votes

---
Tags: 7, drush, backups
---


# Question
Title: field collection - taxonomy term can't display
I used taxonomy term with field collection and taxonomy term can't display look this video

https://www.youtube.com/watch?v=cEI1yDcJXT4

# Answer
> 0 votes
By default the taxonomy term page will list all content (NODES) that is referenced by this term. In your case you are referencing the field collection item by this term.

To display the nodes in the term page you need to create a new view as below:

1. Create a view of type content and add a relation to the field collection type.
2. In the view filters you need to add filters by content type and another filter to restrict the result by the taxonomy you are using.
3. Add a contextual filter that will filter the results by the term id - provide a default value from the URL, thus will ensure that you are displaying only nodes referenced by the term id you are viewing.

now you need to use page manager, context, custom code, etc... to place this view in the term page.

How it will work: When you are viewing a term page it will display the view we previously created. this view will extract the term id from the URL and query nodes related to the term.

---
Tags: entities, taxonomy-terms
---


# Question
Title: Creation of a Grid/Matrix using views in Drupal 7
Does anyone know of a good way to automate the creation of matrix/grids/tables like this?

Basically what I'm trying to accomplish is to create a grid that can show links to other nodes based on an entity (or node) reference.

There could be many of these grids on the site so I'm trying to figure out an automated way to create them (i.e. go to a page like /grid/1/3 and the 1/3 tells the page what columns and rows to pull in - and then based on references how to fill the grid)

It's a little confusing to get across what I mean but hopefully it's understandable.

# Answer
*There is a module for that* \- if you are using Drupal 7 check this: Views Responsive Grid
> 1 votes

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


# Question
Title: Hotel Diamond and Metatag: the META information doesn't appear in front page
I have a site using Drupal 7 and the Hotel Diamond theme. I am trying to add META tags to all the pages in my site (description, Open Graph tags, etc.), and it's working in all of them except the front page. What I do is:

* I have Metatag 7.x-1.13
* In the admin page, I go to "Modules/SEO", and I make sure that Metatag, Metatag:OpenGraph, Metatag:Facebook, Metatag:Twitter Cards and Metatag:Views are activated.
* I go to "Content" and, in each of the pages, I hit "Edit" and add the descriptions in "Meta tags".
* I go to "Configuration/Search and metadata/Metatag" and, in "Global: Front page", I add my description for the front page.

When I check my pages, all of them have the proper META tags... except the front page.

I've seen this question, but I don't really understand the answer: how do you assign a node to be front? Besides, in the case of Hotel Diamond, there seems to be a front page already assigned that you modify by editing it directly when logged in.

# Answer
> 1 votes
To change/set the front page go to admin/settings/site-information, where you can set the path for the node that you want to be your front page.

---
Tags: meta-tags
---


# Question
Title: Message - Item already in cart (commerce)
I want to disable the ability of adding a product twice to the shopping cart.

Is there a way to prevent or prompt a message when a user tries to add the same product twice?

# Answer
> 2 votes
```
    <?php
/**
 * Implements hook_form_FORMID_alter().
 */
function mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $product_ids = mymodule_get_products_in_cart();

  $line_item = $form_state['line_item'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
  if ($product->type == 'program') {
    if (in_array($product->product_id, $product_ids)) {
      // Product is already in cart! We only want to allow a quantity of 1,
      // so disable the submit button and change its text accordingly
      $form['submit']['#disabled'] = TRUE;
      $form['submit']['#value'] = t('Already in cart');
    }
  }
}

/**
 * Return the product_id values for all products in the cart
 *
 * @return
 *  An array of product ids
 */
function mymodule_get_products_in_cart() {
  $product_ids = &drupal_static(__FUNCTION__);

  if (!isset($product_ids)) {
    global $user;
    $product_ids = array();
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
      $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
      foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
        $product_wrapper = $line_item_wrapper->commerce_product;
        $product_ids[] = $product_wrapper->product_id->value();
      }
    }
  }

  return array_unique($product_ids);
}
?>

```

# Answer
> 0 votes
Checkout #5 of the following link - it shows how to do it if you have the stock module activated and disables the add to cart button.

https://www.drupal.org/node/1658788

Quote:

The commerce-stock add the event : "Check if a product add to cart form should be enabled" which is exactly what we want to do.

I added 2 conditions inside an "AND" condition set:

1. Data comparison (to check if the product page is of a product type B) : Parameter: Data to compare: \[commerce-product:type\], Data value: Product B
2. "Order contains products of particular product types" and select your other product type.

And then the magic comes from the action : "Advanced configuration of the add to cart form", also added by the commerce-stock module. With the following parameters : Parameter: Hide the Quantity field if it is visible: true, The text to set the action to: not compatible with..., Add a class to the add to cart form: no-eshop, Disable the add to cart?: true, Clear the submit array first: false, Clear the validation array first: false

# Answer
> 0 votes
I'm not sure if this is a bug. if you tried to add the same item to the cart more than once it will increment the item count instead of adding a duplicate item.

---
Tags: commerce
---


# Question
Title: Commerce, how to show 'view' of 100 products without speed/loading issues
I am attempting to work out my own delivery/collection slot setup.

Each delivery 'slot' is its own 'commerce product,' 10 x 1 hour slots per day for 10 days - 100 slots to span 10 days. Pick a slot and add it to the cart.

For the year I think there is around 4000 variants in one spreadsheet which i can import with feeds - so I have all the raw 'product data.'

Only thing is when I create a view of the 100 products it seems to get bogged down and takes ages to load - sorry for being non-technical.

Below is a screenshot of what I have and would like to achieve, how can I display my products as below but rapido!

# Answer
As the commenters above indicate, there's nothing in particular that should be causing this slowdown. You'll want to look into what might be happening during the render phase of your View and see if some Views query caching and / or render caching might help. The challenge, of course, would be preventing double bookings of fully utilized time slots - but maybe you could easily invalidate the cache in those cases.

If anything is causing the slowdown, it could be price calculation across 100 products happening multiple times per pageload. Commerce by default runs price calculation to determine if an Add to Cart button should be enabled or disabled and also to display the calculated price to render on the product page. That shouldn't be coming into play if you're just rendering product entities directly - typically you'd only see that on the product display node, and you could easily prevent it by editing the Views field to simple display the price as loaded.

To check out what's happening w/ price calculation, you can simply enable the Rules log and see if it's firing off a bunch of rules and then figure out how to disable it. I think Views caching with some smart invalidation as products are purchased is the right thing.
> 0 votes

# Answer
Have you tried to use Views Load More or Views Infinite Scroll modules? these will create an Ajax request to load more content on demand instead of loading mass number of items at page load.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Allow users to access only terms that he created
Terms from user that created nodes are stored in vocabulary tags. When user creates new content i would like to allow him to only choose from list of terms he created instead of whole vocabulary. Is that possible ?

# Answer
> 0 votes
There is a module that stores authoring information (author, published date and updated date) for the taxonomy term.

This module is views integrated. Exposes authoring information fields (author, published date and updated date) to views configuration (fields/filters/arguments/sorts/relation).

Taxonomy Term Authoring Information

After installing this module, create a view that filters terms and displays only terms created by the current user then change the field widget to use that view.

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


# Question
Title: How do I install multiple drupal sites in a single installation?
I am trying to install multiple sites in a single installation on a local server.

But I don't have any idea about how to do this.

Can anybody tell me how to create multiples site using Drupal 6?

# Answer
> 1 votes
Look at Aegir to help you, and/or look at the multisite documentation.

# Answer
> 1 votes
If you want each site to be after your base domain (example.com/site1, example.com/site2), then do something like: In the sites directory you will make directories other than default that will have their own settings.php and files directories. One directory for each site. Then you make symbolic links in your document root to point whatever site name to your drupal directory. Index.php will magically take care of pointing to the right directory once everything is set up. I recommend checking out http://drupal.org/documentation/install/multi-site for more detailed instructions.

# Answer
> 0 votes
Depending on what you're trying to achieve, Domain Access could be an interesting solution too. For instance it would work well for affiliates sites which have localized as well as shared content.

# Answer
> 0 votes
Try to read the Drupal 7 multi site installation article here or Click here

# Answer
> 0 votes
Best documentation for what you are looking for is here: Multi-site - Sharing the same code base

---
Tags: 6, multi-sites
---


# Question
Title: How to override confirmation messages when saving or updating content in Drupal 8?
I've got a few taxonomy vocabularies, but the confirmation message on save/update is generic - `Created new term %term.` or `Updated term %term.`. Those messages come from `\Drupal\taxonomy\TermForm`. Usage of that class is defined in `\Drupal\taxonomy\Entity\Term` class annotation.

I would like to have custom confirmation messages specific to each vocabulary.

What's the best way to accomplish that? Ideally I'd like to have separate form handler classes for each vocabulary.

# Answer
> 2 votes
Don't know if that's the best way, but it worked for me.

In your `my_module.module`:

```
/**
 * Implements hook_entity_type_alter().
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
 *
 */
function my_module_entity_type_alter(array &$entity_types)
{
    $entity_types['taxonomy_term']->setFormClass('default', '\Drupal\my_module\Form\MyTermForm');
}

```

Create `my_module/src/Form/MyTermForm.php` and override the `save()` method of `Drupal\taxonomy\TermForm`.

```
/**
 * @file
 * Contains \Drupal\my_module\Form\MyTermForm.
 */

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\TermForm;

class MyTermForm extends TermForm
{

    /**
     * {@inheritdoc}
     */
    public function save(array $form, FormStateInterface $form_state) {
        $term = $this->entity;

        $result = $term->save();

        $link = $term->link($this->t('Edit'), 'edit-form');
        switch ($result) {
            case SAVED_NEW:
                drupal_set_message($this->t('Created new :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName())));
                $this->logger('taxonomy')->notice('Created new :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName(), 'link' => $link));
                break;
            case SAVED_UPDATED:
                drupal_set_message($this->t('Updated :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName())));
                $this->logger('taxonomy')->notice('Updated :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName(), 'link' => $link));
                break;
        }

        $current_parent_count = count($form_state->getValue('parent'));
        $previous_parent_count = count($form_state->get(['taxonomy', 'parent']));
        // Root doesn't count if it's the only parent.
        if ($current_parent_count == 1 && $form_state->hasValue(array('parent', 0))) {
            $current_parent_count = 0;
            $form_state->setValue('parent', array());
        }

        // If the number of parents has been reduced to one or none, do a check on the
        // parents of every term in the vocabulary value.
        $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
        if ($current_parent_count < $previous_parent_count && $current_parent_count < 2) {
            taxonomy_check_vocabulary_hierarchy($vocabulary, $form_state->getValues());
        }
        // If we've increased the number of parents and this is a single or flat
        // hierarchy, update the vocabulary immediately.
        elseif ($current_parent_count > $previous_parent_count && $vocabulary->getHierarchy() != TAXONOMY_HIERARCHY_MULTIPLE) {
            $vocabulary->setHierarchy($current_parent_count == 1 ? TAXONOMY_HIERARCHY_SINGLE : TAXONOMY_HIERARCHY_MULTIPLE);
            $vocabulary->save();
        }

        $form_state->setValue('tid', $term->id());
        $form_state->set('tid', $term->id());
    }

    /**
     * @param \Drupal\taxonomy\TermInterface $term
     */
    private function getType($term)
    {
        $vocabularyId = $term->getVocabularyId();
        switch ($vocabularyId) {
            case 'pages':
                return 'page';
            default:
                return 'term';
        }
    }

}

```

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


title: elysia_cron setup for custom callback

text:
# Question
Title: elysia_cron setup for custom callback
I have created a custom callback to perform some batch operation. How can I set schedule for execution using elysia\_cron?

# Answer
> 2 votes
Elysia cron has a hook specifically for that; `hook_cronapi()`:

```
function hook_cronapi($op, $job = NULL) {
  $items['key'] = array(
    'description' => 'string',
    'rule' => 'string',
    'weight' => 1234,
    'callback' => 'function_name',
    'arguments' => array(...),
    'file' => 'string', // External file, like hook_menu
    'file path' => 'string'
  );

  $items['key2'] = ...
  ...
  return $items;
}

```

Taken from the API.txt file included with the module.

# Answer
> 1 votes
Elysia cron manages all `hook_cron()` implementations, meaning that you need to have `hook_cron()` implementation in your module in order to be able to schedule execution.

Here's an example:

```
function YOUR_MODULE_cron() {
  // Check if the system is already processing your task.
  if (lock_acquire('YOUR_MODULE_cron')) {
    // Do whatever you need here.
    //
    // Release the cron once done, so the process can be triggered again later.
    lock_release('YOUR_MODULE_cron');
  }
}

```

Clear caches, then navigate to `/admin/config/system/cron/settings` and configure how often you want your cron task to run.

See also:

# Answer
> 1 votes
I had the same issue on a project where I was trying to add individual cron jobs for feeds importers and run them with elysia cron.

check what I have used to accomplish it.

```
<?php
/**
  * Feed import managed by Elysia
  */

function MY_MODULE_cronapi($op, $job = NULL) {
  $items['feeds_english_cron'] = array(
    'description' => 'Import feeds in english.',
    'rule' => '5 3 * * *', // Everyday at 03:05 AM
    'callback' => 'MY_MODULE_CALLBACK_cron',
    'arguments' => array(array('FEED_NAME')),
  );
  return $items;
}

function MY_MODULE_CALLBACK_cron($feednames) {
  if (function_exists('feeds_source')){
    foreach($feednames as $feedname) {
      $source = feeds_source($feedname);
      $source->import();
    }
  }
}

```

---
Tags: 7, cron
---


# Question
Title: add link programmatically to views field Drupal 7
I am generating views result using ldap query and eliminating some result by checking it against Drupal node title using hook\_views\_pre\_render() and looping through views result.

I want to add link to this ldap views using Drupal node id.

Tried adding in the same pre\_render function using drupal l() function. But it displays full html i.e

```
    <a href='node/nid'>title</a>

```

instead of html.

Can anyone help resolving this issue?

Thanks...

# Answer
> 1 votes
Instead of coding why you don't use views fields.

1. Add the title and node id fields to the view.
2. Exclude them from display.
3. Add a global: custom text field.
4. Use tokens to print the HTML you want.

It should look like this:

```
<a href="/node/[nid]">[title]</a>

```

---
Tags: 7, views
---


# Question
Title: Administration menu - How to remove the number of users + search bar
Out of the blue, our administration menu now shows a number like `192/7` on the right side and a search bar.

Does anyone know what causes these items to appear on the administration menu? And how can I remove them?

# Answer
> 0 votes
Navigate to `admin/config/administration/admin_menu` Under the Plugins tab uncheck *Search bar* and *Account links* then click Save configuration

---
Tags: 7
---


# Question
Title: How to use expert class settings for display suite for images?
I've tried different combinations, but it's now working or showing up in chrome inspector...

I'm also using Bootstrap template, could that by a problem?

Or maybe I'm not filling out the information correctly in the field boxes?

# Answer
Ok, got it figured out.

It didn't work because I had nothing selected for:

```
 "Use custom display settings for the following view modes"

```

So I had to select "full content" then use that one for custom fields.

The default tab page doesn't work....

So using ***only default*** will NOT work, you MUST have a custom diplay.
> 0 votes

# Answer
Have you tried Image Class.

> Extends the Image formatter by adding an option to add an element class.

It does not work in combination with Display Suite unfortunately as per this post: Merge Image Class into Display Suite
> 1 votes

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


title: Webform skip page programmatically

text:
# Question
Title: Webform skip page programmatically
I know how to `hook_alter` a Webform build form. I also know how to validate it using a `hook_validate`.

Is there a chance to skip a certain Webform page when some validation code results in false?

I cannot find any solution ;-(

# Answer
> 0 votes
I has just found a solution for it. Perhaps, somebody can find more pretty realisation.

**So, first step:** Lets your 'hook\_node\_view' in custom module call early than webform 'hook\_node\_view', you can do it through hook\_module\_implements\_alter() something like it:

```
function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    if(isset($implementations['YOUR_MODULE'])){
      $group = $implementations[YOUR_MODULE];
      unset($implementations[YOUR_MODULE]);
      $implementations = array_merge(array(YOUR_MODULE => $group), $implementations);
    }
  }
}

```

**Second step:** Remove unnecessary webform components from node object.

```
function YOUR_MODULE_node_view($node, $view_mode) {
  if (isset($node->webform['components']) && YOUR_CONDITION) {
    foreach ($node->webform['components'] as $key => $component) {
      if ($component['page_num'] == 2) {
        unset($node->webform['components'][$key]);
      }
    }
  }
}

```

---
Tags: forms, webforms
---


title: How can I remove nodes?

text:
# Question
Title: How can I remove nodes?
How can I remove nodes using Drupal Console?

# Answer
Drupal Console is for creating boilerplate code (also known as scaffolding) rather than for general administration and day-to-day work. You can see an overview of the features of Drupal Console:

How does Drupal Console help?

To delete a node you would be advised to use drush which is a general purpose DRUpal SHell. Drush doesn't have a command to do this out of the box but there are a number of different approaches outlined in this post, Can I delete nodes of a given content type with Drush?
> 0 votes

---
Tags: 8, console
---


# Question
Title: How to create charts in Views using Google Analytics data?
I'm trying to generate charts in Views using Google Analytics data.

I have the Google Analytics Reports module installed, but this module doesn't allow aggregation of data which make charts very difficult to develop.

Does anybody have a working solution to get charts in Drupal 7 using Google Analytics data?

# Answer
You could pull in the data to your Drupal DB via the Google Analytics API (https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtDataImport)

Then create views to display the reports/charts you want. Then install and build data visualizations packages like Views Dataviz with Google Charts API.
> 0 votes

# Answer
# Use the 7.x-3.x version of Google Analytics Reports

As of Jul 31, 2015, the Google Analytics Reports module completed the Migrating from the Chart to the Charts module. Refer to my answer to "How to transform data from the Google Analytics Reports module into charts?" for new options (features) that became available as of the 7.x-3.x version of that module, and which may better fit your needs.

# Roll your own cookies

If you'd rather want to consider an alternative, you could try to create those charts, by just using the Charts module to achieve your goal. After importing relevant data (as suggested in another answer also), you could use either its Views integration, or its API (in your custom module). The Charts Community documentation may help to do so also.

Specific to your question here, there is an interesting Charts-issue you may want to look at. I.e. Graph node input over time (support date formatting on a continuous axis). In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.

Part of the recommended solution there is to (also) use the Views Date Format SQL module. Here are some details (from its project page):

> The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.
>
> The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

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

# Answer
activate the 3 submodules of charts module and the google analytics report module will display charts

EDIT :

Using google analytics report module + charts module with its 2 sub-modules do generate a chart by defaut.

The corresponding view can be modify and implemented with GA variables and chart add-ons.

I have not been trying to customize charts further than exposing some filters so i can't talk of limitations when trying to create specific custom charts with these views
> 0 votes

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