# Question
Title: Long wait time for website and taking too much CPU+Memory
My drupal site is taking too long wait time, and it uses CPU + memory. My server setting is

16GB RAM, 8 processors. So it is good.

I am using Commerce Kickstart distribution have enabled 180 modules all are required cant disable a single module, I cant use caching coz content is mostly dynamic. My site loads in 8 second (most pages) in which wait time is only 6-7 seconds. Multiple hits takes CPU usage to 100%. I have checked reports with xhprof, top command on server, database tuning script, front page executes 4,52,600 functions, PDO commit taking 31% CPU, Database connections are not properly closed.

I have tried database tuniing module, database tuning script but nothing is working fine right now for me.

Cant use caching even default drupal views caching.

Please suggest some steps, any help will be a big big favor. Website i am building is dynamic so caching is prohibited.

# Answer
> 2 votes
There are tons of performance options, I think with the beefy server resources you have we can tune it tremendously by doing the following:

1. **Database** tuning
    * **MySQL** \- make sure QueryCache is setup, and InnoDB is the only table type being used. You'll want to look at the high performance sample my.cnf (config) that ships with MySQL.
    * **Memcache** \- configuring Memcache will speed up *tons* of the queries and sub-queries Drupal is notorious for.
    * **Session Cache** \- for handling a lot of concurrent \[unique\] login sessions you can consider using a NoSQL database engine like CouchDB/MongoDB, it'll free up your MySQL db from managing those sessions.
2. **Web Serving** tuning
    * **OpCode Caching** \- speeds up PHP *a lot*, is basically a requirement on all Drupal servers nowadays. I use **APC**, and there are other solutions but APC will work reliably with very little setup; this one is a no brainer.
    * **Caching** \- you seriously need to cache at least the home page for anonymous users, and when a user logs in their unique session will be handled correctly. Consider using **Varnish** (it'll allow your site to handle over 100x more anonymous traffic and there are tons of tips on how to use it with Drupal.

These are just the quick highlights of what you need to utilize. If someone says you can't use caching on your website then there is a flaw in either the product design or the system design. There are literally thousands of popular Drupal sites that manage tons of logins and anonymous traffic working just fine with this recipe.

---
Tags: database, performance
---


# Question
Title: Upgrading drush under Windows using self-update
I installed Drush on a W/XP workstation using MSI and want to upgrade it.
I've tried using `drush self-update` but the suggestions it gives all seem to pertain more to Unix installations than Windows.
The best suggestion looks like drush dl /path/to/drush but I'm not 100% sure what the /path/to/drush would be on a W/XP system.

# Answer
> 1 votes
If you stick to using the *Pear* installation method for Drush then you can just update all Pear modules (or just Drush) at will. I don't even see the `selfupdate` command in Drush 6.2, but it just may be hidden now.

# Answer
> 0 votes
> In WinXP the folder to copy into is C:\Documents and Settings\All Users\Application Data\Drush. The Application Data directory is also a hidden folder. (Please see above instructions regarding hidden folders).
>
> There is an extra folder named classes (containing one file named DrushRole.php) in the unzipped drush-All-versions-5.x-dev that was not in the download on the Windows 7 machine. I went ahead and copied it over with all the others into the C:\Documents and Settings\All Users\Application Data\Drush directory with all the rest of the folders and files.
>
> Source : https://groups.drupal.org/node/265678

You can read more about upgrading drush on Windows XP, by this article

---
Tags: drush, upgrading
---


title: Lots of generated queries

text:
# Question
Title: Lots of generated queries
I enabled devel to **Display query log**

**UPDATE: this problem only happens for logged users**

I found that the **`Frontpage`** generate 900 queries.

```
**67** of them generated by the **Locale** module

```

and

```
**480** of them are of the type: **DrupalDatabaseCache::set**

```

How can I track this problem?

I read that I should disable the i18 module, but I can't do this since it is a multilingual site and I there are other modules that need the i18 module.

This only happens in the **Frontpage** in other pages the queries downs to 300.

# Answer
Problem was in theme. I change to the site Bartik theme and the problem was gone.

I'm using the commerce kickstart distribution if that helps someone. I run into other issues in the past with the frontpage in this distribution. I just remember that and that is why I thought it could be a problem related to the theme. The theme of this distribution has some lines in the preprocess file and that imho may be the source of the problem.

I my situation I will use other theme since I don't need a responsive theme at all.
> 1 votes

# Answer
If performance is an issue then consider tuning Drupal a little. Here's a recent optimization tips for Drupal I did just a few minutes ago. Then you can run your site with all it's queries and wonderful, useful modules with less pain.
> 0 votes

---
Tags: database, i18n-l10n, debugging
---


# Question
Title: How do I submit a form with limit_validation_errors?
I want to create a node. If users put something in the required field, it will show an error message; if users don't put any value in the required field, the node will be saved without the required field.

# Answer
> 1 votes
If I understand well what you're saying, I think you should not put this field as a "required field" as the field can be empty.

So what I would do is:

* set the field has not required
* add a custom validation function that checks, if the field is not empty, that the submitted value validates your requirements. You should look at the hook\_field\_validate or hook\_validate to add your custom validation

# Answer
> 0 votes
I am not clear with the question though but if your issue is to allow a certain user role to use a particular field and not by other user roles than probably the way should be to not show/hide that field on the basis of field accessibility for user roles.

In the above mentioned use case Field Permission module can be helpful.

---
Tags: forms
---


# Question
Title: Is there a module to create incentivized social media marketing conditionals?
Currently I'm looking to implement a feature where a user can facebook/twitter share a link or a snippet of text to their social media network and then have drupal capture that feedback to see if they did it or not. From there I want to be able to give them a % discount when purchasing something from my site which is running drupal 7 commerce. Is there something like this built already? if not how would one go about doing this feature?

# Answer
I've never seen a module that does this.

You're going to have to be pretty familiar with Drupal, Commerce, PHP and the APIs of the platforms you'd like to use.

Because this question is so huge, it's not a good fit for this forum. This forum is only for asking direct questions, with clearcut answers.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Are views cached through the core caching mechanisms or should I be setting the caching directly in each view?
I see there are cache settings in each of my views. Do I need to set these or does the core caching mechanisms in /admin/config/development/performance automatically do some of this and these "extra settings" in views are if I want to override the default caching behavior of drupal core?

# Answer
**WHAT:** Core performance caching stores and serves the whole rendered page with a cache id of the URL. Views caching goes beyond this to cache just the view output.

**WHY:** It's great for logged in users; other blocks on the page may be more dynamic but the view doesn't have to run a query every time for every user... just the occasional user who generates the page cache upon cache lifetime expire.

**SETTINGS:** Allowing the "rendered output" to be fresher than the query is useful for things like marking content as new, otherwise just match them up.

**BIG PICTURE:** Drupal serves page dynamically, using a server to build pages in PHP and access a database (or in-memory cache). This allows awesome features and content editor velocity... but the trade off is needing to understanding caching and do it right.

**MODULES!**

There's also a lovely Views Content Cache module which clears views cache on content edit. If you want to go further you may want to check out Cache Actions as well, I'd recommend Rules to fine tune this.

Additionally, Blockcache Alter allows you to set "per role", page, user, etc. caching options for each block on your site.

You can also add Page manager and Panels. This allows you to do interesting things like setting the cache "per user", "per role", or a number of other very useful configurations. Though I personally avoid panels.

**DOCUMENTATION:** For caching and performance in general check out the Drupal.org page.
> 38 votes

# Answer
Views uses the Drupal cache APIs but it creates its own cache that isn't related to the normal Drupal page/block cache.

Views caches the view definition itself along with the rendered view itself. The rendered view can be cached in two ways, either the query result or the actual HTML of the view. Normally you want to cache the outputted HTML since this is the most performance effective. In some cases where you want to alter the output based on the logged in user, caching the query can be quite effective as well.

The tables Views uses for storing the cache is:

* `cache_views`
* `cache_views_data`
> 5 votes

# Answer
There is an interesting module now available called views cache bully that automatically caches all views (query results and output), except for views with exposed forms. The module also allows you to manually exclude views from its caching. This makes it possible set caching for all views (except those excluded) from a central point.
> 3 votes

# Answer
Drupal 7 provides page caching however page caching only works for anonymous users and does not cache views

Views caching however works for both anonymous and logged in users
> 2 votes

---
Tags: 7, views, blocks, caching
---


title: Search API + Views

text:
# Question
Title: Search API + Views
How can I retrieve fields from other entities using relationships to an indexed node in a View?

As an example... if I create a relationship using "Indexed Node: Author". And then try to display the Author's name in my search results view, the name is empty. I've tried every combination of relationship and field from the selectors, but the name is always empty.

# Answer
> 1 votes
In case this helps someone else... Upgrading to the latest dev version of the Entity API (currently 7.x-1.3+4-dev) made this work as expected.

My related entity's fields appeared in the view as soon as I upgraded the module.

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


title: Profile2 Template for edit page

text:
# Question
Title: Profile2 Template for edit page
i already searched all relevant drupal sites - but without success. I have to create a own template file for the "edit user profile" site of the module Profile2.

As far as i know, i have to hook the new templatefile in the template.php of my theme - but what keywords and syntax do i need to accomplish that?

Every hint would be great! Thanks.

# Answer
I did this way to create my own "edit user profile" for profiles of profile2 module.

```
function customtheme_theme() {
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'customtheme') . '/templates',
        'template' => 'user-profile-form',
        'preprocess functions' => array(
             'customtheme_preprocess_user_profile_form'
        ),
    );
    return $items;
}

```
* I put **customtheme\_theme()** function into my **template.php** file of **customtheme theme**. (a custom theme that i used for my website)
* After that i created the template file **user-profile-form.tpl.php** and placed in the **templates** folder of my theme. The **customtheme\_preprocess\_user\_profile\_form** function you can use that for changing some variables before render the profile form or if you dont need any changes you can remove the preprocess\_functions.
* After add the **customtheme\_theme()**, create **user-profile-form.tpl.php** template. You have to clear cache and you can see the layout change for user-profile-form.
> 3 votes

# Answer
Thanks for this very detailed reply. I made all entrys in the template.php and user-profile-form.tpl.php and cleared all cache multiple times. Unfortunately the edit site does not change. Iam confused about the $items\['user\_profile\_form'\] keyword - is there any reference, because in other forums i read something about $items\['user\_profile2\_edit'\]?

I keep on trying and will reply as soon as it works! Thx
> 1 votes

# Answer
This is how I accomplished different template files for each Profile2 Edit Page.

First, form\_alter to set up the form #theme properly

```
function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    if ($form['#user_category'] === 'writers') {
      $form['#theme'] = 'profile2_writers_edit_form';
    } else if ($form['#user_category'] === 'secondary') {
      $form['#theme'] = 'profile2_secondary_edit_form';
    } else if ($form['#user_category'] === 'main') {
      $form['#theme'] = 'profile2_main_edit_form';
    }
  }
}

```

Then you can set up the templates this way

```
function THEME_theme() {
  return array(
    'profile2_writers_edit_form' => array(
      'arguments' => array(
        'form' => NULL,
      ),
      'template' => 'profile2-writers-edit',
      'render element' => 'form',
    ),
    'profile2_secondary_edit_form' => array(
      'arguments' => array(
        'form' => NULL,
      ),
      'template' => 'profile2-secondary-edit',
      'render element' => 'form'
    ),
    'profile2_main_edit_form' => array(
      'arguments' => array(
        'form' => NULL,
      ),
      'template' => 'profile2-main-edit',
      'render element' => 'form',
    ),
  );
}

```

Now all you have to do is add the files to your theme folder and clear cache. In this case I ended up with the following files for Profile2

```
profile2-writers-edit.tpl.php
profile2-secondary-edit.tpl.php
profile2-main-edit.tpl.php

```

A basic tpl should look something like this

```
<article id="node-user-edit" class="profile2-user-edit writers-profile">
  <?php print drupal_render_children($form); ?>
  <?php print drupal_render($form['#submit']); ?>
</article>

```

Print fields singularly like so

```
<?php print drupal_render($form['FIELD_NAME']); ?>

```
> 1 votes

---
Tags: users
---


# Question
Title: Views removes style attribute in "Rewrite Results"
I've got screenlists for videos and I need to put them into the div tag to as a background and then change bacgkround position with JS to show the preview. I've downloaded Image URL Formatter for this purpose and added code to "Rewrite Results" field of the field in my view:

```
<div class="episode-screenshot" style="background-image: url('[field_episode_screenlist]');"></div>

```

But there is no such attribute "style" in rendered html of the page. Does Views module block it?

# Answer
> 6 votes
Yes, Views does block style attribute for security reasons. Class attribute is allowed.

Here's one long discussion about it https://drupal.org/node/853880 and some other ideas for workarounds Add style attribute to view fields.

---
Tags: views
---


title: Region won't show on front-page

text:
# Question
Title: Region won't show on front-page
I'm customizing a theme and need to have a leaderboard on top of the page. Everything good - on all pages but not the home (front-page)... Any ideas what I did wrong?

I've added a region to the .info file

```
regions[topad] = Leaderboard header

```

and printed that region to the page.tpl.php like that:

```
 <?php if ($page ['topad']): ?>
   <div id="topad">
        <?php print render($page['topad']); ?>
   </div> <!-- /#topad -->
 <?php endif; ?>

```

I added a block with the leaderboard infos to the region and told it to show up on every page (also tried specific pages with "" - didn't work).

I'm happy for every hint.

Thank you!

Best

Chris

# Answer
Do you have a specific template for your front page? Is your front page pointing at a node? Or just a list of recent updates?
> 0 votes

---
Tags: theming
---


# Question
Title: Some MyISAM tables not converted to InnoDB during 6 to 7 upgrade
When I upgraded from Drupal 6 to Drupal 7 using the upgrade script I was under the impression MyISAM tables would be converted to InnoDB. This doesn't seem to be the case. Tables like comment, node, and block and many others remain as MyISAM. Tables like cache and field\_\* are InnoDB.

As far as I can tell it's best practice to use InnoDB. My website is a blog and forum, so users are posting comments, creating nodes, and voting on content. The site serves up an average of 30k pageviews a day.

Assuming everything was InnoDB I configured MySQL with: innodb\_log\_file\_size = 256M and innodb\_buffer\_pool\_size = 11G.

I believe it makes sense to convert all my tables to InnoDB. I wanted to ask here to see if anyone ran into this issue (conversion not taking place) or if anyone knew why the tables weren't converted. And, if I do convert everything to InnoDB, is there anything I need to know?

# Answer
> 4 votes
It does make sense to convert all tables to InnoDB. The core 6 -\> 7 update does not change the engine type; so the reason they weren't converted is that it was not programed to do so.

Use READ COMMITTED for MySQL transactions https://drupal.org/node/1650930#comment-8437127 Use 7.25 Core or higher https://drupal.org/node/937284

By doing both of these you will significantly reduce the number of deadlocks that occur on your database.

Using a non database cache backend like memcache is a good idea, as explained in this presentation: http://www.percona.com/resources/mysql-webinars/drupal-and-mysql-performance

---
Tags: 7, database
---


# Question
Title: How can I pass user real name as a contextual filter in views
I am trying to simply provide a view of author content by passing a contextual link for the author ID to provide a URL with the author's name as selected with the Real Name module.

For instance: "/sitename/content-type/realname".

When I set up the filters, the only way I can get it to work is by providing the user name, not the real name as set by the real name module. I would like to keep the login name private, and use the real name as assigned.

Has anyone had any success doing this?

# Answer
> 1 votes
If the real name is stored in one field in your user, you can set up a relationship with the user and then point to that in the contextual filter, eg, here I just created a "real name" text field in the user and then did this:

and then for nice looking urls, did this in the filter:

so I can go to

`www.example.com/by-real-name/this-real-name`

or

`www.example.com/by-real-name/that-real-name`

It's really up to you re: case transformation, but two real caveats: you have to make sure real names are unique AND it gets really squirrelly if and when special characters are in the real name field.

---
Tags: views, users
---


# Question
Title: How to find machine module name for `drush dl`?
Long time Drupal front-end dev but doing more site building lately and have been using Drush much more. One of the biggest limitations I've found with downloading (dl) command is that you have to know the machine name of the module, which is not a big issue for say Views or Context. But who knows the machine name of stuff like node reference or simple google maps?

I guess and get it right sometimes, or I have to hit d.o to figure it out. Is there a list function I havent uncovered? The other answers to this on Stack Overflow and Drupal Answers are pretty bad.

```
drush dl module-name-here

```

# Answer
> 3 votes
According to my experience, I know machine names of some commonly used modules, but basically when it is for new module or when I have doubt in machine name, I google it the module name, it should provide you with link for drupal project page,

the url will be in the format https://drupal.org/project/\[project-machine-name\]

```
drush dl [project-machine-name]

```

for multiple module you can do like this

```
drush dl [project-machine-name1] [project-machine-name2][project-machine-name2] ..

```

# Answer
> 1 votes
There are thousands of modules available for Drupal 7 alone, and new modules are added to drupal.org at a fairly high rate. It would be hard to compete with Google + drupal.org searching in terms of finding modules, and you're probably going to want to visit the module's project page to figure out if it's the right one for you anyway.

Once you are on the drupal.org module page, you can look at the URL: the machine name is the name used there (i.e. https://drupal.org/project/machinename).

---
Tags: 7, drush
---


# Question
Title: how to create a custom skin in jCarousel
I want to create a custom skin in jCarousel. I have seen this website http://timonweb.com/how-create-custom-skin-jcarousel-drupal-7, but I don't want to create any new module. How to do it in a simple way? I had tried creating a new skin folder inside the skins directory of jCarousel module, but it didn't worked.

# Answer
OK, after a moment of googling, I can say that apparently you cannot go without writing a tiny module, but even though I myself have been reluctant to write YABM (Yet Another... Module), it took me about 5 minutes. Have a glimpse at this article, copy and paste the code, change the skin name occurrences and there you go - your skin recognized with clean hands. Thanks to http://timonweb.com.
> 1 votes

# Answer
There's no need to create any module. I used a Zen subtheme and used the navigation.css file (or any other .css file you like). There's a Drupal convention to write CSS settings in an appropriate CSS file, but I am not much familiar with this convention. Its best if you create your own CSS file custom.css and write all the overriding CSS properties there. In that navigation.css file I wrote, there are the CSS settings for jcarousel, or you may say I override the previous jcarousel skin settings. I used the tango skin, and override the CSS settings in navigation.css. You may create custom pointers and create an image sprite for those pointers.
> 1 votes

# Answer
A quick glimpse at the sites/all/modules/jcarousel/skins/default/jcarousel-default.css file gave me a good idea of what already was there. I wrote all my custom CSS straight into my theme's CSS file and used the Default theme in Views jCarousel, then just used CSS overrides to get it to look just the way I wanted it.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to see the individual fivestar ratings in a view?
How do I design a view to see every user's fivestar rating? I want to see a node, and below that list all users' ratings (and not connect it to comments). The only thing I've been able to do is list every user that has rated a node and get the value of their vote (percent) but if I change the value to show the "rate widget", so that I can see the nice fivestar rating, it can either show me the logged-in user's rating or the average rating. It will not show me the actual user's rating.

# Answer
I believe you can create a relationship to Votes, and then you can show the users who voted and their vote values.
> 2 votes

---
Tags: views, rating
---


# Question
Title: Dynamic link in nodes to hidden Quick Tabs tab
How can I make an URL that points on the same page Quick Tabs TAB. It will be good if link works without reloading page.

# Answer
In Drupal 7, you can achieve it by using **jQuery**

* **Without reloading page** : Just create a Dynamic link using **ID attribute or some other attribute**, by using these attribute just click the TAB using jQuery.
* Dynamic link like

`<a href="#" id="tab1">Link text</a>` OR

`<a class="tab1" href="#">Link text</a>` OR

`<a href="#" data-tab="your_selecting_tab_ID">Link text</a>`

```

  jQuery("#dynamic_link_ID").click(function(e) {//OR by using other attribute
    e.preventDefault();//it will not redirect when link is clicked
    jQuery("#quicktabs-tab_ID").click();//OR use any selector as per you requirement
  });

```
> 1 votes

---
Tags: blocks
---


# Question
Title: How to take contents of a tab and insert them inside a node
I guess this is a pretty basic Drupal thing, but I'm not experienced with coding. I am using the Petition node module which displays a petition form and the results of that petition inside a tab on the same page. I found the code for this on line 174 of the petition.module:

```
$items['node/%petition_menu/signatures'] = array(
'title' => 'Signatures',
'page callback' => 'petition_signature_page',
'page arguments' => array(1),
'access callback' => 'petition_signature_access',
'access arguments' => array(1),
'weight' => 1,
'type' => MENU_LOCAL_TASK,

```

I want to render the signatures right next to the petition form, on the petition node page. How can I do this? My guess is that I could use this code and insert it inside the node template, but I need some instructions for that.

# Answer
You can create a block using the block module hooks and you can generate the content of the block by using the page callback function in the menu to get the signatures displayed inside the block. You can then configure the block in whichever region you want.

Another option would be to use the page callback function inside the template file (.tpl file) of the petition node and print the content near to the petition form.
> 0 votes

---
Tags: nodes, routes, entities
---


# Question
Title: Access multiple values by index in a view
I have a multi-value field. When I output this field in a view I use `Rewrite results` and reference this field as `[field_product_image]`. This outputs all the images of the field.

How could I output only certain element of this array, e.g. second image **using rewrite results** (this is essential)? Neither of these works:

`[field_product_image:0]`, `[field_product_image_0]`, `[field_product_image-0]`

# Answer
For that you need to check the **Group multiple values** and then set to show **1** values and set starting from **1**. see the below screenshot for clarification

>

if you check the rewrite output of this filed you can see the token for that filed, for your case it would probably

> **\[field\_product\_image\_1\]**

So if you want to retrieve the image separately from the array, you have to do the above steps for each image, for example if you want the 3rd image, then you have to set starting from **2** and its tokes is `[field_product_image_2]`, if you want 4th image, then you have to set starting from **3** and its token is `[field_product_image_3]`.

Below screenshots will help you to understand easily.

I added each filed separately to retrieve each image

>

and its tokens and above method is for Drupal 6, you can do it in the same way for D7.

>
> 1 votes

# Answer
I would suggest to create a template specific for this view field, so you can access all your variables with PHP, which is way more convenient to do such things.

So if your field id is "field\_product\_image", then you should find and download views-view-field.tpl.php, rename it "views-view-field--field-product-image.tpl.php", put your code inside and upload it to your theme/template folder.

You can see in your view, under "Advanced" \> "Theme" what is the name to override default views field template and if the overriding template is used.
> 0 votes

# Answer
It is assumed in this question that defining **which** values to output and **how** to output them would have to happen in the same place, Rewrite results. However, there is nice support for separating these in (D7) Views Configure Field dialog: Multiple field settings for "what" and Rewrite results for "how".

So for D7 use "Multiple field settings". For example "Display 1 starting from 1" outputs the second image. Now you can access your image in "Rewrite results" simply using \[field\_product\_image\].

In D6 these settings are in the same dialog, but they work the same way, I believe.
> 0 votes

---
Tags: views, entities
---


# Question
Title: product in cart but when clicking on cart it shows empty
I really don't understand this one... I have Drupal commerce on Drupal 7.

When I'm adding a product it shows in the cart summary just fine. but when I go on mysite/cart ...the cart is empty. It is not a browser issue I think. Any help on that odd problem would be more than just appreciate, please.

I tried clearing the cache on the server, browser ..none worked

# Answer
> 1 votes
If you do a quick search of the issue queue for "Views results empty", you should turn up the solution: you've probably customized your shopping cart View to include a product relationship, but your test user must not have access to view all products. When Views goes to render the results and performs the access check on the View results, it won't show anything as a result.

If this is the case, my recommended solution would be to edit the View, open the advanced settings fields, and edit your query settings to disable SQL rewriting for the View.

# Answer
> 0 votes
You may do the next variants to solve this problem:

1. check orders manage page on backend /admin/commerce/orders For all users (for without registration mode disable "Commerce Checkout Redirect") created new order with "Cart" status
2. Check View for Cart page admin/structure/views/view/commerce\_cart\_form/edit Maybe contains wrong settings

---
Tags: commerce
---


title: Displaying 5 decimals in shopping cart

text:
# Question
Title: Displaying 5 decimals in shopping cart
I'm developing a website that mostly sells electrical wire. Prices are per kilometer and imported into commerce with 2 decimal places. Order amounts are per meter though, so in a rule I divide the price by 1000 when calculating the unit price. I use the following module for formatting the price with 5 decimals after the decimal point: https://drupal.org/project/commerce\_price\_decimals\_formatter . In the display node this renders the price per meter correctly.

In the shopping cart view, I can also choose to format the price with 5 decimals, but the extra decimals are not shown, and simply show zeros.

So if I have a cable that's priced at

* € 124.44 / km, it shows
* € 0.12444 / m in the product display node, but
* € 0.12000 / m in the shopping cart

The totals in the shopping cart are correct. I'm guessing views is only getting the unit price up to 2 decimals out of commerce. What can be done to fix this?

# Answer
I ended up soling this problem in a stupid straightforward way:

I edited the shopping cart and order summary view to

* include a relation to the product
* print the personalized product price instead of the line item price, formatted to 5 decimals

Obviously this is going to be trouble when I start including non-product line items, but for the time being I don't.
> 0 votes

# Answer
Prices are always going to be rounded when saved unless you've updated the definition of the currency itself to support storage to the 5th decimal place. It sounds like that module is simply offering part of the solution, while the whole solution will involve hooking into the currency info array and then updating whatever prices you've already entered to be saved with the new precision.
> 1 votes

---
Tags: views, commerce, rules
---


# Question
Title: Why kpr() shows different content than var_dump()?
In one vital part of code I started to get "Trying to get a property on a non-object" type of errors. So I wanted to investigate it.

```
var_dump($download);
die();

```

Gives:

```
array(3) {
  [1]=>
  array(5) {
    [5]=>
    object(stdClass)#156 (11) {
      ["idDownload"]=>
      string(1) "5"
      ...
    }
    [6]=>
    object(stdClass)#155 (11) {
      ["idDownload"]=>
      string(1) "6"
      ...
    }
    [7]=>
    object(stdClass)#151 (11) {
      ["idDownload"]=>
      string(1) "7"
      ...
    }
    [8]=>
    object(stdClass)#185 (11) {
      ["idDownload"]=>
      ...
    }
    [10]=>
    object(stdClass)#177 (11) {
      ["idDownload"]=>
      string(2) "10"
      ...
    }
  }
  [2]=>
  array(5) {
    [5]=>
    object(stdClass)#186 (11) {
      ["idDownload"]=>
      string(1) "5"
      ...
    }
    [6]=>
    object(stdClass)#155 (11) {
      ["idDownload"]=>
      string(1) "6"
      ...
    }
    [7]=>
    object(stdClass)#151 (11) {
      ["idDownload"]=>
      string(1) "7"
      ...
    }
    [10]=>
    object(stdClass)#177 (11) {
      ["idDownload"]=>
      string(2) "10"
      ...
    }
  }
  [3]=>
  array(5) {
    [5]=>
    object(stdClass)#184 (11) {
      ["idDownload"]=>
      string(1) "5"
      ...
    }
    [6]=>
    object(stdClass)#155 (11) {
      ["idDownload"]=>
      string(1) "6"
      ...
    }
    [7]=>
    object(stdClass)#151 (11) {
      ["idDownload"]=>
      string(1) "7"
      ...
    }
    [8]=>
    object(stdClass)#185 (11) {
      ["idDownload"]=>
      string(1) "8"
      ...
    }
    [10]=>
    object(stdClass)#177 (11) {
      ["idDownload"]=>
      string(2) "10"
      ...
    }
  }
}

```

But if I'll switch to kpr() like this:

```
kpr($download);
//die();

```

I get this:

Why can it happen? And can how I get `kpr()` to work? using `var_dump()` in form debugging is not really an option.

# Answer
> 3 votes
`$download[1][6]` and `$download[2][6]` are the exact same object (`object(stdClass)#155`), not just two objects with equal values. To avoid potential infinite recursion, Krumo (the k in `kpr()`) only display a single object once. The screenshot shows this, `$download[2][6]` is displayed as "∞ (Recursion)" because the object is already displayed (but collapsed in the screenshot) above as `$download[1][6]`.

`var_dump()` does not have this *limitation* as it does not try to prevent infinite recursion.

---
Tags: debugging
---


# Question
Title: Importing pages with different node ids to the live site
We have a site in drupal 6.

It's placed in 2 different server with separate databases. One is used for staging and the one is used for live.

We have created a new language section and imported the data with xliff tool to the staging. We have completed the modifications in staging and now we need to push them to live.

But the thing is that the node id's are different in staging and live, and also some pages contains view , block and nodes.

And also I must say that I am a newbie in drupal.

I would appreciate if someone could show me a way to import this new language pages to the live site without using xliff.

Thanks in advance

# Answer
> 2 votes
I've had this problem myself in the past, and importing nodes into a livesite can be quite a head ache at times.

Luckily there's a great module available for D6 called Node Export. It allows you to import / export nodes using a host of different formats such as JSON, CSV, XML etc.

I've used it before exporting a large dataset and I was impressed with how easy it was to implement.

Hope this helps.

---
Tags: 6, i18n-l10n, importing-exporting
---


# Question
Title: Views taxonomy listing of terms linked via contextual path
What this really boils down to is a contextual block view of terms with relative paths to a second taxonomy vocabulary, I'm just not sure on how to get there.

Here is what I'm trying to do:

I've created a basic block that contains links to taxonomy pages, but I need the links to which they point to be contextual based on the path that's in the current URL.

I have a content type that uses two different vocabularies on each node. One is a location type vocabulary of terms something like this:

* Florida
* USA
* North America

Then I also have another vocabulary that contains a number of different award types something like this:

* Award X
* Award Y
* Award Z

The same set of awards can be listed in each of the location type pages above as well.

By request we've created the Views to display the locations as pages, then the awards listed under each location.

So when we have visitor on the "Florida" page for example, we want to present a list of taxonomy links that point to awards by type, with the location included in the link contextually/dynamically. We don't want USA links showing on Florida pages, nor "Florida" links showing on "North America" pages.

Our path currently looks something like this from the Views Page displays:

domain.com/VIEW-PATH/term-name

domain.com/florida/award-x
domain.com/usa/award-x
domain.com/north-america/award-x
etc.

our **taxonomy** View pages look like this:

domain.com/term-name

domain.com/award-x
domain.com/award-y
domain.com/award-z

I need to find a way to contextually set the link in the taxonomy list block include that location vocabulary term, dynamically.

They NEED to look like the first set only with the location added dynamically:

domain.com/**\[florida\]**/award-x
domain.com/**\[usa**\]/award-x
domain.com/**\[north-america\]**/award-x

The problem is that we don't have the location term in the path. Any ideas on how to make this happen? Hope this makes sense.

Thanks in advance.

*edited for clarification:*

The end result I'm trying to achieve for the taxonomy link created by the View would look something like this:

domain.com/florida/award-x/node where **florida**

(the location) is added dynamically depending on the location taxonomy page that the visitor is on. I've not seen a way to set the location taxonomy term variable in to the path in admin/config/search/path/patterns which is where I've been looking the most for a solution. It seems I should be able to do it here, but I've not been able to figure it out due to the location being a different vocabulary that the award name.

# Answer
> 0 votes
You dont have to pass all these parameters via the URL. If you know the `location` or `award` from within your master view simply embed another View into the view passing it hidden or visible `Fields` in from the parent view. You want to use views\_field\_view to do this:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.
>
> It's highly recommended to use this module in conjunction with views caching. Views Content cache and Cache Actions are good ways of caching views.

# Answer
> 0 votes
I simplified this whole thing because it has to be done yesterday. I just manually created all the menus with the paths that I need. It's not elegant. It's probably not the best solution either for the future, but it had to get done. I created the first one I needed then, cloned it and adjusted the paths as needed for each additional menu.

We'll revisit this in the future, and I'd still like to hear other solutions, if someone has a better, more efficient, content manageable way of doing this, but for now the manual menus as blocks will have to work.

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


title: CKEditor buttons not showing

text:
# Question
Title: CKEditor buttons not showing
I'm using Drupal CKEditor module 7.x-1.13 and CKEditor 4.3.2.
Everything is installed and appears to work fine... except that there are some buttons that don't appear despite being configured to do so, notably "Select All" and the justify left/right/centre/justified buttons.
Here are the buttons as configured:

And here are the buttons as they appear:

# Answer
You'll need to get and install the Full Package here: http://ckeditor.com/download

Then the missing buttons will show up.
> 7 votes

---
Tags: wysiwyg
---


# Question
Title: Close commenting after X comments have been posted
I would like to ask if anyone knows how I can set a limit to the number of comments that can be made on a node with Drupal 7.

Perhaps what I'm asking isn't the best solution for what I'm trying to achieve.
I have created a content type (Event); each event will have a guest list which people can sign up to on a first-come-first-served basis. I would like each event to have a limit (ranging from 10 - 100) to the number of people who can register for the guest list position.

Any advice would be much appreciated.

# Answer
> 4 votes
You could use the drupal rules module to set up a system to close your comments after X amount of comments. In combination with the views bulk operations module, you could set up a rule for "new comment has been posted."

For the condition compare the number of results from a VBO created that counts the number of comments on the node the comment was posted to and compare it to the number of comments you want before closing. If there are 20 comments posted and the number you want to close at is 20 the rule will move on to the action.

The action would be a custom php snippet to set comments from read / write to read only. The snippet I was using for Drupal 6 was

```
$node->comment = '1';
return array("node" => $node);

```

so it may need to be modified slightly for 7.

With that all being said, if you are looking to set up an event registration setup where a certain number of people can sign up, you are actually looking for the entity registration module.

From the drupal.org website

> Entity Registration does lots of things you are expecting from a registration system (like allowing you to restrict the number of total registrations for a given event), and other stuff you are crossing your fingers and hoping for (like building in automated reminder messages for your registrants).

# Answer
> 0 votes
Check this: https://drupal.org/node/304616#comment-1004389

And this module is in dev, so use at your own risk: https://drupal.org/project/comment\_limit

---
Tags: nodes, forms, comments
---


# Question
Title: Alter a panel page variant provided by another module (programmatically)
How can I alter a panel page variant provided by another module in my own module?

I am using Advanced Forum, and it provides a panel page to override Drupal's core forum display behavior and some variants: Top Level Forum, Container and Forum. But I have changed some layout options, and added a few more panes, and disabled some other panes etc in page manager UI. Now I want to export this into code, i.e. in my custom module. I can export the code using the export option in the UI, but I don't know how to add that code in my module. In other words I don't know which hook to implement to override this variant provided by Advanced Forum, instead of creating my own variant.

I know how to provide default panel pages or variants using `hook_ctools_plugin_api()` and `hook_ctools_plugin_directory()`, but I couldn't find out how to **alter** an existing page variant provided by another module.

Is there a hook for that?

# Answer
You might try creating a clone of this variant and then making your custom changes to it. You can then reorder this variant so it is above the original. This way your custom variant will always get executed and the original one ignored.

Once that is completed, you should then be able to export your variant using features.
> 1 votes

---
Tags: 7, panels, chaos-tool-suite
---


title: Custom views sort handler without table

text:
# Question
Title: Custom views sort handler without table
I am trying to expose data fetched from remote API and stored to $user object. I have accomplished that with a custom views handler suggested in this post Custom views handler without table.

However, I need to add sorting and filtering, so any help will be great.

This is the custom views field handler code.

```
/**
 * A handler to provide a field that shows the license type.
 *
 * @ingroup views_field_handlers
 */
class views_handler_apms_license extends views_handler_field {

  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);

    // Remove the checkbox
    unset($form['alter']['alter_text']);
    unset($form['alter']['text']['#dependency']);
    unset($form['alter']['text']['#process']);
  }

  function render($values) {
    $user = user_load($values->uid);
    if (isset($user->apms['userLicense'])) {
      return $user->apms['userLicense'] ? t('BASIC') : t('FREE');
    }
    else {
      return NULL;
    }
  }
}

```

# Answer
Ok, just to put another idea out there...

If your data set is not too big then output all the unfiltered unsorted data to an html table, and then use a jQuery plugin to do all your sorting and filtering client side. Something like this would be suitable.
> 3 votes

# Answer
You can use the post\_execute() method on your handler to remove entries from the list of all results. This is certainly a bit tricky but it works.
> 4 votes

---
Tags: 7, views
---


title: About the Media Gallery Module

text:
# Question
Title: About the Media Gallery Module
Right now in each gallery, when a user clicks on the thumbnail, a larger version will show up in the middle of the screen. With it are arrows to navigate, a "1 of x" caption, a link to start a slideshow, and an x to close it. When I click the image, it takes me to the page of the media. What I want it to do is take me to the next image in the slideshow (like the arrows would have done). I tried looking at the configuration of the Media Gallery Module but there were only options on column and row layout. When I tried to check the settings in the gallery content type, all of the fields were locked and could not be edited. I tried Google for a solution, but not really anything turned up for this specific problem.

# Answer
You should use Firebug and take a look at the function that gets called, when clicking on the "Next"-Button.(Something like onClick() )

Now take a look at the function, that gets called, when you click on the image.

Now just place the "Next"-Button function into the image. Delete the old one.

The functions are usually in a .js-File.

This is not so hard, i am a beginner and managed it with the shadowbox.
> 2 votes

# Answer
You may use this JQuery script to achive your required result. You can use JS Injector Module to insert this script or simply upload a js file in your theme folder and call it through .info file

```
/*
Redirects lightbox image click to advance to next image instead of opening image details.
Via http://drupal.org/node/1088738#comment-4362570
code from #12
Posted by stephandale on April 10, 2011 at 12:26pm
*/
(function ($) {

Drupal.behaviors.initColorboxDefaultStyle = {
  attach: function (context, settings) {
    $(document).bind('cbox_complete', function () {
    $('.lightbox-stack .gallery-thumb-inner a').click(function(e) {
        e.preventDefault();
        $.colorbox.next();
      });
    });
  }
};

})(jQuery);

```
> 0 votes

# Answer
I have had the same problem, and I can tell a little more about the reasons, in an example:

On the Gallery ( /galleries/myGallery) , you click on a photo and the colorbox opens. But the content of the colorbox is not only the image, but the body of /media-gallery/lightbox/11/22 . And this content features a link around the image, namely /media-gallery/detail/11/22 .

I cannot find a way to remove that link, but maybe this helps somebody to remove the problem without overwriting the standard behaviour with JavaScript. Which works of course, but there should be a better way.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Calling a field in views-view-fields--view-name.tpl.php ---- Error
I am trying to call a field by using the line of code:

```
<?php print $field->handler->view->field['title_1']; ?>

```

But i keep getting this error:

I used devel dpm() to look for what was the correct path to call it and it said `handler->view->field['title_1']`. I am absolutely stumped and I am not sure if I am using the right .tpl.php file or what. Anyone have any ideas?

**---EDIT---**

```
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
  <?php print $field->separator; ?>
<?php endif; ?>

<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php print $field->content; ?>
<div>
    <?php print $field->handler->view->field['title_1']; ?>
</div>
<?php print $field->wrapper_suffix; ?>

```

# Answer
From the commentary, some points are being missed, but this template is used to create the "row" of fields from a View.

Let's create a simple one:

which has three fields, a title, a new field and a custom field, which when run looks likes this:

Now, let's create a `views-view-fields--for-da.tpl.php`, rescan for templates, and add some debugging information to the top of it:

```
drupal_set_message('<pre>' . print_r(array_keys($fields), TRUE) . '</pre>');

```

and running it again, this will give us:

So, now, anyplace we want inside this template, we have access to the individual field's content as:

```
$fields['title']->content
$fields['field_new_field']->content
$fields['field_my_custom_field']->content

```

so throwing them in similar `drupal_set_message()`s produces:

But now, let's say you are exluding one of these fields from display, eg:

then you will get this:

but some more digging into `$row` via:

```
drupal_set_message('<pre>' . print_r($row->field_field_my_custom_field, TRUE) . '</pre>');

```

will give you this:

or access to the content of the excluded field via:

```
$row->field_field_my_custom_field[0]['rendered']['#markup']

```

Obviously, the field names are different here than in your specific example, but I hope you can follow the logic.

Also, if you don't want to dig into `$row` you could always include the field in the display via the Views UI and then exclude it in this template, eg, something like this:

```
<?php foreach ($fields as $id => $field): ?>
  <?php if ($id != 'field_my_custom_field'): ?>
    <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>

    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>
      <div class="insert-custom-field-content-here">
        <?php print $fields['field_my_custom_field']->content; ?>
      </div>
    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

```

which would print all the fields with the exception of the custom one, but would then include its content after the content of each of the other fields.
> 2 votes

---
Tags: 7, views, theming, debugging
---


# Question
Title: Strange debug prints appear in the system log
I have two Drupal 7 sites on an Apache server that are printing strange debug messages in a system log. The sites are set in their vhost config to use error logs within each local site folder, like the following.

* /var/www/site1.com/log/errorlog
* /var/www/site1.com/html/\[drupal installation\]
* /var/www/site2.com/log/error.log
* /var/www/site2.com/html/\[drupal installation\]

These error logs are fine and happy, but I am seeing a large number of entries in /var/log/messages. These debug lines look like the following.

> Feb 5 08:51:56 server012 drupal: `http://site1.com|1391619116|form_debug|5.10.83.11|http://site1.com/eform/submit/apply-for-a-program?pid=127||0||Array#012(#012` \[#parents\] =\> Array#012 (#012 )#012#012 \[#entity\] =\> Entityform Object#012 (#012 \[uid\] =\> #012
> \[entityType:protected\] =\> entityform#012
> \[entityInfo:protected\] =\> Array#012 (#012
> \[label\] =\> Entityform#012 \[entity class\] =\> Entityform#012 \[controller class\] =\> EntityformController#012 \[base table\] =\> entityform#012 \[fieldable\] =\> 1#012
> \[entity keys\] =\> Array#012 (#012
> \[id\] =\> entityform\_id#012 \[bundle\] =\> type#012 \[revision\] =\> #012
> )#012#012 \[bundles\] =\> Array#012
> (#012 \[apply\_for\_a\_program\] =\> Array#012
> (#012 \[label\] =\> Apply for a thing or Ask a Question#012 \[admin\] =\> Array#012 (#012
> \[path\] =\> admin/structure/entityform\_types/manage/%entityform\_type#012 \[real path\] =\> admin/structure/entityform\_types/manage/apply\_for\_a\_program#012
> \[bundle argument\] =\> 4#012
> \[access arguments\] =\> Array#012
> (#012 \[0\] =\> administer fields attached to entityform entities#012
> )#012#012 \[original access arguments\] =\> Array#012
> (#012

> Feb 5 08:51:48 server012 drupal: `http://site2.com|1391619108|content|90.8.28.253|http://site2.com/fr/node/2/edit|http://site2.com/fr/node/2/edit|44|voir|page`: updated Qui sommes nous?.

I've just been informed that `/var/log/messages` is linux "syslog".

* Why is Drupal printing to syslog?
* Is this normal behavior?
* Is there a setting to enable/disable syslog output?

# Answer
> 2 votes
That is what the Syslog module that comes with Drupal does. It is not enabled by default, but enabling it will cause what you are noticing.
The module doesn't have its own settings to disable logging the messages into the system logs; to stop that, just disable the module. Since you are not going to use it anymore, you can then uninstall it. (Don't delete its files, since they are copied every time you update Drupal.)

---
Tags: 7, debugging
---


# Question
Title: How do I grab the current product SKU in code, as early as possible?
In Drupal Commerce, using programming, what is the way to grab the product SKU of the product entity that is about to fire off and display on the page in a product display node, as early as possible? I'm looking for something that is before panes and views are executed and drawn.

I know the SKU lives in $form\_state\['default\_product'\]-\>sku within a hook\_form\_alter, but that is too late.

In panels, I know there is a time in hook\_panels\_pane\_content\_alter where I can scrape the SKU out of $content-\>content\['#markup'\]. That doesn't seem to update though as I change the selectors that affect which product is currently displaying. So that's no good.

I need it as early as possible, because I want to pass that value into a view during hook\_views\_pre\_view, which is executed very early.

# Answer
Have you tried using menu\_get\_object? It provides access to objects loaded by the current router item.

Once you've got the node, the product reference field is just going to list the products and Drupal Commerce may exclude products from the add to cart form based on rules and other modules. But you can get the SKU of the first referenced product on the product display like this:

```
$node = menu_get_object(); // May want to check that it's a node.
$node = entity_metadata_wrapper('node', $node);
$products = $node->field_product->get(0)->sku->value(); // field_product is my product reference, may want to check that it exists.

```
> 1 votes

---
Tags: commerce
---


title: Allow user to change views template

text:
# Question
Title: Allow user to change views template
I have a view configured with a custom template. Now I need to represent the same information arranged in two different ways. What I want is for the user to have an option to change between the three different templates. This doesn't seem to out of the ordinary but I am having trouble finding an example.

Using Drupal 7.

# Answer
I would build the different displays as separate blocks and then use the quicktab module.

https://drupal.org/project/quicktabs

That way, it will be very easy to switch between the blocks.

Configuration in quicktabs:

Results:
> 0 votes

---
Tags: views
---


title: Preventing SQL injection

text:
# Question
Title: Preventing SQL injection
In Drupal 6, queries are issued with `db_query()`. Using %-modifiers, query arguments are substituted into the query after being filtered. Strings %s (and only strings) are ultimately run through `mysqli_real_escape_string()` (using `db_escape_string()`).

Looking at the php docs for `mysqli_real_escape_string()`, I see the following security warning:

> The character set must be set either at the server level, or with the API function `mysqli_set_charset()` for it to affect `mysqli_real_escape_string()`.

The answer to another question about mysql\_real\_escape\_string / SQL Injection explains that:

> Another way to get yourself into hot water using mysql\_real\_escape\_string is when you set the database connection encoding using the wrong method. You should do this:
>
> `mysql_set_charset('utf8', $link);`
>
> You can also do this though:
>
> `mysql_query("SET NAMES 'utf8'", $link);`
>
> The problem is that the latter bypasses the mysql\_ API, which still thinks you're talking to the database using latin1 (or something else). \[...\] This can be used for injection attacks in certain multibyte string situations.

Drupal does not call mysqli\_set\_charset(), and instead issues the query 'SET NAMES utf8'. This can be seen in db\_connect().

In order to properly protect Drupal 6 against SQL Injection, does the charset need to be set at the server level?

# Answer
> 1 votes
This answer to a stackoverflow question does a great job at explaining the attack that can get around mysqli\_real\_escape\_string() using multi-byte character sets.

I've concluded that when running Drupal 6, we do **not** have to set the charset at the server level in order to be safe from the attack.

Drupal always sets the client to UTF8 (and not the GBK or BIG-5 charsets that are required for the exploit). Newer versions MySQL (\> 5.1) are also not vulnerable.

HOWEVER, although Drupal is safe from this exploit, we should still follow the installation documentation which states, "The database should be created with UTF-8 (Unicode) encoding, for example utf8\_general\_ci.".

One helpful comment on the installation docs outlines *how* to create your database with UTF8 encoding, and how to ensure that UTF8 is used when performing a backup/restore:

> To achieve this by the mysql command line interface use the following commands:
> `$ mysql -u root -p # Login`
> `mysql> CREATE DATABASE databasename CHARACTER SET utf8; # Create with utf-8`
>
> When using mysqldump/mysql for backup/restore also force both server and client to utf8 by inserting into */etc/mysql/my.cnf*:
> `default-character-set = utf8 # Server`
> `skip-character-set-client-handshake # Force client`

---
Tags: 6, database, security
---


# Question
Title: How do I add custom CSS styles to the body field?
I have a content type "page with fields" which I made out of "Basic page" by adding two text fields at the beginning of the page which now looks like this:

* Page title
* Field1 Label: field1 text
* Field2 label: field2 text
* Here goes the body field text which is long text.

The problem is the lack of space between the body text and the fields 1 and 2. Now I want to add some custom CSS styles to the body field in order to put some extra space and later to be able to add some other visual changes.

My theme is Bartik 7.26 on Drupal 7.

# Answer
Use the "html inspector" of your browser (Ctr-Shift-I for Chrome) to find the the css classes of thoses fields.

Then add the proper css code in /themes/bartik/css/style.css.

That will be the quickest way to do it but I strongly recommend you to create a sub-theme of the bartik theme (https://drupal.org/node/225125) so if the theme gets updated, you won't loose your changes.

You should check out Display Suite too (https://drupal.org/project/ds), it a fantastique module to change the way nodes are displayed.
> 1 votes

---
Tags: entities, theming
---


# Question
Title: Next/previous links in a view based on contextual filter in the url
I have a page view in a Drupal 7 view with contextual filters in the URL. something like /events/%1/%2 - the first parameter is the year, the second is a taxonomy term. So /events/2014/3 is all the events in 2014 in category 3.

I want to provide next and previous links based on the year (the first filter parameter). Is this even possible?

# Answer
> 3 votes
Not sure what your strengths are, but you could easily accomplish this with a custom php block. If you did something along the lines of

```
<?php
$previous = arg(2) - 1;
$next = arg(2) + 1;
?>
<a href="/events/<?php print $previous . '/' . arg(3)?>/">Previous</a>
<a href="/events/<?php print $next . '/' . arg(3)?>/">Next</a>

```

I would clean up that code and use the l() function to create a link, but that is the general concept.

---
Tags: views
---


title: Time shown in incorrect language

text:
# Question
Title: Time shown in incorrect language
I have a php\_view field in a view, it basically pulls a date field on a specific node, and then use the php function setISODate to get the 'monday' date of the week.

The thing is, i'm on a french language site and the date that the function return is in english, not that I don't like english hehe but the month just doesn't fit very well in the display on that view

Here's the code.

```
// Retrieve the date field of that node.
$node = node_load($data->nid);
$date_field = $node->field_date;
$date = $date_field['und'][0]['value'];

// Put the year in $annee and the week number in $semaine.
$annee = date("Y", strtotime($date));
$semaine= date("W", strtotime($date));

// Get the monday date of that week
$lundi = new DateTime();
$lundi->setISODate($annee , $semaine);
print "Semaine du " . $lundi->format('j F Y');;

```

?\>

I've tried to use the following code, but it doesn't do anything.

```
setlocale (LC_TIME, 'fr_FR.utf8','fra');
print (strftime("%j %F %Y", $lundi));

```

# Answer
> 1 votes
This is working :

```
setlocale(LC_TIME, 'French_France.utf-8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
//setlocale(LC_ALL, '') ;// if you try on local windows server

$annee = date("Y", strtotime($date));
$semaine= date("W", strtotime($date));

// Get the monday date of that week
$lundi = new DateTime();
$lundi->setISODate($annee , $semaine);

print "Semaine du " . strftime("%A %d %B %Y",strtotime($lundi->format('j F Y')));

```

---
Tags: views
---


# Question
Title: How to select multiple values for Drupal Facets (Facet API + Search API)
I am using Facet API + Search API to develop Filtering for the data within my site. I am also using Ajax Facet Filters to process the selection as soon as it's clicked.

It all came out great but there's one slight problem. I can only select one option per category. As soon as I select an option, all the inactive options hide and only the active (clicked one) shows.

I want the option to select multiple option but with my settings of Facet API & Search API, there seems to be no option.

Here's the picture to explain.

I'll be very thankful for any assistance.

Best.

# Answer
I found the first comment here to answer this question.

> the OR operator is required for the facet instead of the default AND. If the implementing search module you are using supports OR facets, you will have an option in the "Global settings" fieldset located in the bottom left hand corner of the facet's display settings form.
> 3 votes

# Answer
You can follow the below step:

* Go to Administration -\> Configuration -\> Search and metadata
* Click on `Search api` link and it redirect you to `search api` page.
* Go to `facet` page using `facet` link from drop down.
* Select `Configure filters` from drop down in your active `filters` and it will redirect you to `filter` configuration page.
* You can unchecked check-box `Hide items that do not change search result.` to show all filters.

Kindly see that you can unchecked other check-boxes to configure different functionality.
> 0 votes

---
Tags: javascript, search
---


# Question
Title: Error when aggregation is turned on in Views
I have a view for Organic Group (og) that displays a list of the groups, a picture, the language, the categories the groups fall into, and a summary of the mission statement. All of this is neatly organized in a grid.

I want to add a membership count for each group in the view. As soon as I turn aggregation on, I get the following error message:

> SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS node\_og\_field\_data\_field\_group\_image\_, node\_og.title AS node\_og\_title, node\_' at line 1

Does anyone know what's going on and how to fix it?

# Answer
I finally found the answer for this. My view had a group picture; removing the group picture, turning the aggregation on, and putting back the group picture field solved the problem.

It's a problem others have had and that's how they all fixed it; See https://drupal.org/node/1809584.
> 1 votes

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


title: How do I make #cols work in textarea?

text:
# Question
Title: How do I make #cols work in textarea?
According to the Form API, you control the number of columns in a textarea with the #cols attribute. However, setting this seems to have no effect when I use it inside a $form array (the companion #rows attribute works as expected).

This is question is already on stack overflow however the answer utilizes css instead of the cols attribute which seems like a cheat.

```
    $form['message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#resizable' => FALSE,
        '#cols' => 20,
        '#rows' => 10,
    );

```

# Answer
> 2 votes
Drupal will add the cols attribute to the textarea, however its CSS which controls it. i.e Width of the textarea or its container is controlling it.

Here is the fiddle example explaining this scenario

In the above example first textarea didn't affected by any CSS so it has 100 cols, however the second one is bounded with another container and its width is restricted, so textarea is rendered within the available width that's why cols value didnt affected the textarea.

The same is applicable for rows attribute when you set height attribute.

---
Tags: theming, forms
---


title: File field not getting updated

text:
# Question
Title: File field not getting updated
i tried to update file cck field of a content type as below from another node as below.

```
<form action="" method="post" id="tfrm" enctype="multipart/form-data">
    <input id="tf" name="tf" type="file" />
    <input id="btn" type="submit" value="Submit" name="btn" />
</form>
<?php
if($_POST['btn']){
$node=node_load(32);

$filename = basename($_FILES['tf']['name']);
$image = file_get_contents($_FILES['tf']['tmp_name']);
$file = file_save_data($image, 'public://' . $filename, FILE_EXISTS_RENAME);
$filesinfo = (object) array(
          'uid' => 1,
          'uri' => $file->uri,
          'filemime' => file_get_mimetype($file->uri),
          'status' => 1,
 );
$node->field_ftest[LANGUAGE_NONE][0]=(array)$filesinfo;
print_r($filesinfo);
  node_save($node);

}
?>

```

file gets uploaded but results error in updating file field .

```
localhost
Error
The website encountered an unexpected error. Please try again later.
Error message

    Notice: Undefined index: fid in file_field_presave() (line 219 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of C:\xampp\htdocs\drupal\includes\entity.inc).
    Notice: Trying to get property of non-object in file_field_presave() (line 220 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Warning: Creating default object from empty value in file_field_presave() (line 221 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Notice: Undefined property: stdClass::$uri in file_save() (line 601 of C:\xampp\htdocs\drupal\includes\file.inc).
    Notice: Undefined index: fid in file_field_update() (line 261 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Notice: Undefined index: fid in file_field_update() (line 287 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Notice: Undefined property: stdClass::$fid in file_usage_add() (line 685 of C:\xampp\htdocs\drupal\includes\file.inc).
    PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 32 [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 692 of C:\xampp\htdocs\drupal\includes\file.inc).

```

# Answer
You should use Form API to create and manage file uploads and their management. You can do something like this instead:

```
...
$form['file'] = array(
    '#title' => t('File'),
    '#type' => 'managed_file',
    '#description' => t('File formats: %format. Maximum: %max_size. Resolution %resolution', array('%format' => 'Jpg, Jpeg, Png, Gif', '%max_size' => '800 Kb', '%resolution' => '80x100')),
    '#upload_location' => 'public://',
);
...

```

and submit function:

```
...
$node = node_load(32);
$file_d = $form_state['values']['file'];
$file = file_load($file_d);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'node', 'TYPE', $file->fid);
$file_info = image_get_info($file->uri);

$file_arr = array(
  'fid' => $file->fid,
  'alt' => '',
  'title' => '',
  'width' => $file_info['width'],
  'height' => $file_info['height'],
  'uid' => $file->uid,
  'filename' => $file->filename,
  'uri' => $file->uri,
  'filemime' => $file->filemime,
  'filesize' => $file->filesize,
  'status' => 1,
  'timestamp' => $file->timestamp,
  'rdf_mapping' => array(),
);

$node->field_ftest[LANGUAGE_NONE][0] = $file_arr;
node_save($node);
...

```
> 1 votes

# Answer
I guess you should use this way:

```
$file = file_save_data($image, 'public://' . $filename, FILE_EXISTS_RENAME);
$node->field_ftest[LANGUAGE_NONE][0]=(array)$file;

```
> 1 votes

---
Tags: files
---


title: Portable content types

text:
# Question
Title: Portable content types
I'm used to leverage Bundle Copy to import/export content types with Drupal 7. One of my expectations with Drupal 8 is that I could theoretically achieve this with CMI. On the Bundle Copy project page it's also mentioned that "*Bundle Copy is in Drupal 8 Core CMI!*" so it all looks promising.

However, due to UUIDs and CMI's focus being on supporting content staging across multiple instances of a same site, it doesn't seem that obvious to create a generic content type that you would export on N number of sites.

For instance, take a photo gallery content type. Once you've created it and that you're happy with everything, you probably don't want to go through the same hassle again and would likely prefer to simply import the YML files onto the active configuration dir via CMI's single import tab (by manually copying the content of your YML files) or via the Synchronize tab (by making YML files available under the staging dir).

I thus wonder if a) I've missed something and b) if yes, what's your recipe for portable content types, if any?

# Answer
> 2 votes
It should be possible to take most relevant config files (content type, fields, displays, ...), create a module, put them in the config folder of it and install that module on any site you want. Or the same with an install profile, I made some relatively successful\* tests there by throwing all config of an actual site into an install profile and was able to install it.

You can also manually edit them, as long as you're not doing in the active storage.

Problematic are for example config files that contain a mix of things. Translation settings for example, which are stored in a single yml file for all entities and bundles, or rest.module settings, all enabled resources are also in a single file. So you would have to write code that manually updates that configuration in hook\_install().

* Relatively successful, which means I had some troubles with config that referenced content (custom blocks, default images of image fields) but I think that can be sorted out.

---
Tags: nodes, 8
---


# Question
Title: views slideshow force al link to basic page instead of the slideshow's custom made url
I am using Views Slideshow for my front page and I want the url output of the image to go to a basic page but there is a conflict because the slideshow creates a page with that image and it makes it a different page than the one it should point to. Example: I have a slideshow image that should point to the about-us page but when creating the about us image slide it creates a new url...so I end up with one about-us page and the slideshow image points to /node/23.

I tried the image link formatter module, created the proper field in Slideshow (Content type) field\_image\_custom\_link and linked the image to this field. And in views I set a rewrite result to output the field as a link and put \[field\_image\_custom\_link\] and it will simply send the image to the url: `/field_image_custom_link#overlay-context=!` Any help would be appreciated, I just want the slides to point to specific existing pages! :)

# Answer
> 0 votes
Add a field to the content type which you are using in your slideshow. Use this field to hold the URL it should point to. Then, add the field in your slideshow view and make it hidden. Now you can use that hidden field to rewrite the URL of the image in the view.

---
Tags: javascript
---


# Question
Title: Subdomain with shared database for users: subdomain not accessing primary database
I've successfully set up a multisite Drupal installation. I now have:

www.example.com --\> main site sub.example.com --\> a secondary site

However, I want the users to be shared. I know about shared databases and prefixes, but according to the comments in the settings.php, you can also use the prefixes to access a different database. I'd like to choose that root.

So my main site goes to the primary database, the subdomain goes to the secondary database, **except for the users**.

This is relevant section of the settings.php of my subdomain:

```
$databases = array (
    'default' =>
        array (
            'default' =>
                array (
                    'database' => 'secondary_database',
                    'username' => 'username',
                    'password' => 'password',
                    'host' => 'localhost',
                    'port' => '',
                    'driver' => 'mysql',
                    'prefix' => array(
                        'default'   => '',
                        'users'     => 'primary_database.',
                        'sessions'  => 'primary_database.',
                        'role'      => 'primary_database.',
                        'authmap'   => 'primary_database.',
                        ),
                ),
        ),
);

```

My primary database already has many users, but when I log into my secondary site, I only see my admin user. Also, I cannot log in to my subdomain with any user of my primary database.

So my conclusion is that the subdomain is still using its own database.

Both databases are on the same server and I've given the username/password for the secondary database access to the primary database.

There are also no errors in the log.

Any suggestions on what I'm missing?

# Answer
I would advise to look into the answers of this question. One solution is indeed a specific setup in settings.php, however all your sites need to make use of the same database when using that option. E.g.:

```
$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);

```

The solution above uses the same database for all sites, but different table prefixes. So in the example above most tables will be prefixed with "main\_", but the users, sessions, role and authmap tables will be prefixed with "shared\_". For your additional sites, you will use a different prefix for 'default' (maybe 'site2\_', 'site\_3', etc.) but the same 'shared\_' prefix.

*(all credits to zdecibel & Dalin for the example & explanation above)*

Another option is using the Domain Access module, which is developed for this kind of purposes.
> 0 votes

---
Tags: users, database, multi-sites
---


# Question
Title: Caching pages with boost based on a cookie value
I have a Drupal website where a part of each page varies depending on the value of a certain cookie. In order to use Boost in this situation, I was thinking of rewriting the cookie value into a query parameter, because Boost takes these into acccount for its cache.

To achieve this, I put the following lines in my .htaccess before the Boost code:

```
RewriteCond %{HTTP_COOKIE} cookie=([a-zA-Z0-9\-]+)
RewriteRule ^(.*)$ $1?cookie=%1 [QSA]

```

I tested this on a simple PHP script which shows all GET parameters, and the cookie parameter is added based on the cookie. Which is the way it should be. I also tested that these rules actually rewrite the %{QUERY\_STRING} for later use, and they seem to do that. However, Boost does not seem to take into account this new query parameter.

Any ideas about what could be wrong? Does Boost do something special with the query string?

Thanks in advance!

# Answer
> 1 votes
Ok, it took me a while, but I solved it. It lead me to learn some interesting details about Apache and Drupal.

In my question above I wondered why the rewrite rules did not alter the QUERY\_STRING in Apache because apparently, the correct page was not fetched from the cache. However, the problem was not that the correct page was not fetched, but that the correct page was not written to the cache in the first place.

Looking into the code of Boost showed that it uses Drupal's request\_uri() function to determine the name of the cache file. This function in turn uses PHP's $\_SERVER\['REQUEST\_URI'\] if set. Some tests in PHP then showed that the rewrite rules do actually change $\_SERVER\['QUERY\_STRING'\], but that this change is not reflected in $\_SERVER\['REQUEST\_URI'\]. In other words, the query parameters in $\_SERVER\['REQUEST\_URI'\] are the ones of the original request, not the ones as potentially rewritten by mod\_rewrite.

To solve this, you can add some code to (for example) Drupal's settings.php to update $\_SERVER\['REQUEST\_URI'\] similarly as done in your .htaccess. This worked for me:

```
if(isset($_SERVER['REQUEST_URI']) && isset($_GET['cookie'])) {
  $cookie = $_GET['cookie'];
  if(strpos($_SERVER['REQUEST_URI'],'?') === false) {
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . '?cookie=' . $cookie;
  } else {
    // I'm not sure what happens if &cookie is already set
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . '&cookie=' . $cookie;
  }
}

```

Note 1: $\_GET does contain the rewritten request parameters, so I guess this is based on QUERY\_STRING.

Note 2: code above only adds my application-specific cookie. I guess a generic solution would be to completely remove the request string of $\_SERVER\['REQUEST\_URI'\] and add all elements in $\_GET again.

Note 3: you need both the rewrite rules in .htaccess and this code in settings.php. The former are needed to have Boost fetch the correct page from the cache, the latter to have Boost write the correct page in the cache.

---
Tags: caching, cookies
---


title: Building an online print shop

text:
# Question
Title: Building an online print shop
I am trying to build an online print shop where user will upload their own images and select the size and quantity of the print they want and pay for the service.I want to use Drupal commerce for the backend.

I don't know how to store the images. Should I store the images as single nodes, or files entities, or products, or something else so that I can easily added them to a product or to the shopping cart?

I have tried googling a solution or something similar, but I haven't get anything.

> The issue with the images is that the same image can be re-order multiple times without been uploaded multiple times and also the users can upload and delete any of their own images at any time.

# Answer
> 2 votes
I would either add an image field directly to the line item type and expose it to the Add to Cart form (along with any other pertinent fields) or figure out some sort of entity reference scenario with an Inline Entity Form on the line item to show the entity add form in the Add to Cart form. Might be a bit general, but googling any of those topics will turn up more info.

---
Tags: 7, commerce
---


# Question
Title: Fatal memory Error at the bottom of the page but not WSD. What this means?
I occasionally get the following error showing at the bottom of some pages when I'm logged in as Admin. I have seen this error before when the server didn't have enough php memory. But then always the page was WSD.

However I don't get WSD with the php memory error message I'm getting now. It's just showing at the bottom of the page and the page itself works as usual. What is the difference between this one and the one we get on WSD? Can I just ignore it?

```
Fatal error: Out of memory (allocated 175112192) (tried to allocate 7015932 bytes) in  /public_html/includes/database.inc on line 225

```

# Answer
You can change the amount of memory available in your php.ini file (i think) - making more memory available to your drupal installation and thereby doing away with this error

see https://drupal.org/node/76156 and https://drupal.org/node/1915140

for further details
> 0 votes

---
Tags: 6
---


title: Contextual filter by author id

text:
# Question
Title: Contextual filter by author id
Ok, so here's my problem. I feel it's really very simple and I am missing something. I have a Drupal 7 view which shows a certain type of content. Say it has a url `mysite.com/article`. What I want is, if the url is like `mysite.com/article/me`, it would load the articles posted by this current user. "me" will always be "me" and would not take any id/username.

Hope the problem is clear. Thanks

# Answer
> 2 votes
I think you are missing one of the buried options.

* Make a view, configure it the way you need.
* Make a **Page** display, and set the path to article/me
* Add a **Relationship** for **Content: Author**. This is likely not needed, unless you want to pull in author fields and display them or if you need the author name explicitly somewhere in another filter.
* Add a **Contextual Filter** for **Content: Author uid**; it should automatically pick up the relationship. In the options for **When the filter value is *not* available**, select **Provide default value**. In the dropdown, choose **User ID from logged in user**.

I think you are missing the last part of the final step. I always forget where that one is. It helps if you configure views to always show the advanced settings (see admin/structure/views/settings).

# Answer
> 0 votes
Well thanks MPD, your answer provided the solution. I am just re-iterating the same here in case anyone else needs

What I did was

* create a view with two separate pages, one having the url `mysite.com/articles` and the other `mysite.com/articles/me`
* In the "me" page I simply added a contextual filter on author:uid (didnt need the relationship as it comes by default) and gave a default value of "User ID from from logged in user" for filter not being present in the url and made that for the "me" page only.
* As for the original without "me" page, which will also extend the contextual filter of the "me" page, we need to set the filter not being present in the url to "Display all results for the specified field" and make it "All displays (except overriden)".

Bingo!!! your view is ready now. Hope I explained myself clearly, and thanks again to MPD.

---
Tags: 7, views
---


title: imagecache permissions

text:
# Question
Title: imagecache permissions
How to allow authenticated users to see all versions of images but prevent anonymous users to see 'large' images created with an imagecache preset?

I've ticked the correct boxes under the permissions tab of imagecache so that anonymous users aren't able to see these images but still they show up. What am I doing wrong? (I've flushed the cache of the imagecache)

Cheers.

# Answer
A quick look through the imagecache module suggests that the only time the module itself enforces the "view imagecache \[preset\]" permission is when it is serving private files. This makes sense in that once the image derivative is created in the public files structure, it is never called; once a file "really exists" drupal is never bootstrapped up, it is only booted up to create the derivative the first time it's not found.

So, then, what are these permissions useful for? Well I'd imagine so you could do something like this...

```
$presets=array('small', 'medium', 'large');

foreach($presets as $preset) {
  if (user_access('view imagecache ' . $preset)) {
    // do whatever your module wants with that preset, create a link, show the image, whatever
  }
}

```

...in your own module.

As for lightbox2, a quick look there shows it just presents a list of possible Display Field options using all of the imagecache presets. As to why it doesn't check these permissions when building these links is a question for that module's maintainer on its issue queue on drupal.org.
> 0 votes

---
Tags: 6, users, media
---


# Question
Title: How to get uid from a node on which is commented?
I'm using `hook_comment_view($comment)` and I'd like to confer the uid from the comment (`$comment->uid`) with the uid from the node on which is commented. I thought of `$node->uid`, but I don't know how I can define `$node`.

Any suggestions?

# Answer
> 1 votes
I could load the `$nid` via the comment and confer the uid's like this:

```
function mymodule_comment_view($comment) {
 $nid = $comment->nid;
 $node = node_load($nid);
 if ($comment->uid == $node->uid){
    //do something
 }
}

```

---
Tags: 7, nodes, hooks, comments
---


# Question
Title: How to hide a field in a comment in hook_comment_view programatically?
My comments have a field called 'Extra'. I'm trying to hide it when the user who's viewing the comment wrote it. This is my custom module:

```
function mymodule_comment_view($comment) {
  global $user;
  if ($comment->uid == $user->uid){
    unset ($comment->field_extra);
  }
}

```

Why isn't this working and what's the correct way to achieve my goal?

# Answer
> 1 votes
Looking at the same kind of functionality in the user.module function user\_comment\_view() I would expect your code to work.

If your function is really called `hook_comment_view` then it won't work though. Either this is just a typo, or rename your function to `MYMODULE_comment_view` where `MYMODULE` is the name of your custom module.

**Edit:** After a little discussion with MPD it turns out, that this actually works:

```
$comment->content['field_extra']['#access'] = FALSE;

```

Respect to MPD for explanations and an inside for why that could work and especially for why the other solution doesn't work!

This is the phrase from MPD that lead to the solution:

> If you read the source for `comment_build_comment()`, $comment-\>content\[\] has already been built up by the time the view hook gets invoked. So, messing with the field directly has no effect at this point.

Which means, that the field output has already been built and stored in `$comment->content`, which implies that this follows the same rules as in `hook_node_view()`. So accessing `$comment->content[FIELD_NAME]` should work.

# Answer
> 4 votes
`hook_comment_view()`, along with most of the other entity view hooks, are typically used to *add* properties onto the entity object.

If you read the source for `comment_build_comment()`, `$comment->content[]` has already been built up by the time the view hook gets invoked. So, messing with the field directly has no effect at this point.

You want to implement a `template_process_comment()` in your theme, or you can implement a module (which technically makes it an instance of `hook_preprocess_comment()`.

Implement this, and then `dpm($variables)` inside it. Figure out what you don't want, and then `unset()` it. If the variable is printed directly from the comments template, this is is directly in `$variables`. If it is in the content section, then unset the proper key in `$variables['content']`, which is a render tree.

---
Tags: 7, hooks, comments
---


title: Upgrading Drush from 4.4 to 7.1

text:
# Question
Title: Upgrading Drush from 4.4 to 7.1
Following instructions here, I used the command `drush dl drush` to install the newer version of Drush. Then, when I attempted `drush omega-export` (the reason I was upgrading was to have access to these newer omega commands) I received a message indicating that drush was still pointing to the older version of drush.

If the server was based in my home computer environment (win7) I would change the PATH variable to point to the newer version. However, since the server I am working on is remote (onyxServers, typical LAMP stack) I am unsure how to make the `drush CLI` point to the new version.

Can anyone point me to a resource? If it was my own linux machine I would be able to figure it out but being hosted confuses things a bit.

UPDATE: I have examined the output of the 'env' command, and noticed that the location of drush, new or old version, is not listed in the PATH variable:

> PATH=/usr/local/jdk/bin:/home/dukkha/perl5/bin:/usr/kerberos/bin:/usr/lib/courier-imap/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/home/dukkha/bin

Is it possible that the path to drush is stored within the drush shell or something?

# Answer
> 0 votes
Aha! I guess I posted this question a little too quickly! The path to the drush command can be altered through editing the .bash\_profile file.

---
Tags: drush, theming
---


title: How to scale uploaded image in ckeditor

text:
# Question
Title: How to scale uploaded image in ckeditor
I am using CKEditor, and am having a problem with the scaling of the images during edit. When I upload and insert them into my editor, if the image is very large, it displays that way in the editor, making it very hard on the user.

I have formats defined for these image styles, which set the class attribute to a CSS class.

Is there a way to get images in the editor to adhere to the CSS of their format, so the page layout during edit resembles what it will look like after being saved?

# Answer
I was able to do this with the Picture module.
> -2 votes

# Answer
In the latest version of the ckeditor library there is the new Enhanced Image plugin. This plugin allows you to resize the inline image by dragging the image corner. Go to ckeditor building website ( http://ckeditor.com/builder) and select the Enhanced Image plugin (image2) and also deselect the standard Image plugin from the build.
> 4 votes

# Answer
You can solve this by creating a custom CSS file for CKEDITOR.

Upload the custom CSS file wherever you want to house it, such as your theme folder.

Add to the custom CSS file definitions for your image classes or data attributes which are used for your rendered pages.

Example: /sites/all/themes/THEMENAME/css/editor.css

```
img.class-small {
  width: 100px;
  height: auto;
}

[data-picture-align="right"] {
  float: right;
}

[data-picture-group="medium"] {
  max-width: 310px;
  height: auto;
}

```

Go to admin/config/content/ckeditor and edit the relevant profile.

Open the CSS area and select "Define CSS" and then enter the path to the CSS file you created. eg. "/sites/all/themes/THEMENAME/css/editor.css"

Now when you are in the editor itself the editor will reference that custom CSS file and draw the image as you have designated it. You can mimic all the same responsive styles by using responsive CSS for your editor the same as you use for your site.
> 2 votes

# Answer
Image Resize Filter is the easiest end-user solution for resizing inline images. Check out this video demo.

> Image Resize Filter makes it easy to resize images, especially when combined with a WYSIWYG editor such as tinyMCE or ***CKeditor***. Users never have to worry about scaling image sizes again, just insert an image and set it's height and width properties in HTML (this is done automatically by WYSIWYG editors) and the image is resized on output to match the HTML.

Features:

* Automatically resizes both local and (optionally) remote images.
* Optionally create a link to full size images from the resized inline versions.
* Prevents inline "hot linking" of images from other sites by storing them locally.
* Adds height and width attributes to inline images when your users are too lazy to add them.

**And**

For responsive image , use Adaptive Image Styles (ais) module

Integration with the WYSIWYG module, Ability to choose which images are adaptive on an image by image basis.
> 1 votes

---
Tags: 7, media, wysiwyg
---