# Question
Title: In Drupal Commerce, how can I decrease stock of product B when buying product A with rules?
I'm having some issues writing some rules for my site.

Let's say I have two products. B and C, as well as a combined product called A. Buying product A should decrease the stock of B and C by 1, but the stock of product A should also always be the lowest stock of B or C.

I can't, for the life of me, find out how to do this, and googling has turned up zero results.

# Answer
> 0 votes
Are you using the Entity Reference module? You will somehow need to set up the relationships between A + B + C in Drupal, and Entity Reference is one Rules-module compatible way to do this.

Another more flexible but more complicated way would be to use the Relation module.

---
Tags: commerce
---


title: Add content type to body class

text:
# Question
Title: Add content type to body class
I want to add a body class for the content type of each node. Drupal already provides this, but it isn't always consistent between the Node view, the Node/Add view and the Node/Edit view. This makes theming difficult.

Here is my code in template.php

```
function MYTHEME_preprocess_html(&$variables) {

    // Add Content type name to classes
    $content_type = $variables['page']['content']['system_main']['type']['#value'];
    $content_type_class = 'content-type-'.drupal_html_class($content_type);
    $variables['classes_array'][] = $content_type_class;

}

```

It works but I get this error message:

> Notice: Undefined index: type in wintheme\_preprocess\_html()

On Stack Exchange, it says the best approach is to use Isset().

If I do this, the error message goes away, but so does the class.

How can I keep my class working without the error message.

# Answer
The problem is you're trying to use the same system\_main content type variable that's not always defined. Try this instead:

```
$node = menu_get_object();
$type = isset($node->type) ? $node->type : 'none';
$type = ($type == 'none' && arg(0) == 'node' && arg(1) == 'add') ? arg(2) : $type;
$content_type_class = 'content-type-'.$type;
$variables['classes_array'][] = $content_type_class;

```

That should give you a `$classes_array` var with either "content-type-TYPE" or "content-type-none" for pages that aren't associated with nodes.
> 1 votes

# Answer
Here's the solution for your problem.

@Shawn Conn : menu\_get\_object is return none on index/home page because menu\_get\_object work as route page requests to code based on URLs. See : function menu\_get\_object

So finally:

Put below code line into your template.php file in before closing bracket of wintheme\_preprocess\_html.

```
//Get current exist nodes content type and append into array
$nodType = node_type_get_types();
if(is_array($nodType)) {
   foreach ($nodType as $types) {
      $vars['classes_array'][] = "content-type-".strtolower(drupal_clean_css_identifier($types->type));
   }
}

```

Hope this would solve your problem. Further, if you have used theme like Bootstrap, Omega, etc. then we need to work out differently.

Let me know if you face any query/concern regarding this.

Thanks!
> 1 votes

---
Tags: theming
---


# Question
Title: Allow users to >only< upload images to existing nodes?
I want to allow users to upload images for exsits content, for example for article, but i will not allow they to delete already exist images.

How modules i can use? How to create this submit form for they?

I use drupal 7.

Thank you!

EDIT: Hi Vincent, thanks for reply.

On example: I have article about Rome with title "Rome". I create description for that beautiful city and i want to allow users to upload images to this exist article about Rome and create gallery of users pictures under descripton.

User can submit photo, but can't remove own or anyone images. Admin must accept every image before it's publish.

Greetings.

# Answer
# Hints for your updated, clarified question (from NOT an expert)

Considering your updated question, there exists a documentation-page on Drupal.org on attaching images to nodes:

But, perhaps easier to start off, is to read some answers posted to identical / very similar questions, here on StackExchange:

Having referred to these, I would like to add that I would intuitively enable pictures in comments, and let people post the pictures in to the comments; but I don't know if that's what you're looking for.

If you would choose them to use the comments: after having enabled comments to include pictures, one can disable unneeded fields, similarly to the method described below, via

* Structure \>\> Content Type \>\> ***Content type*** \>\> Comment fields.
* Structure \>\> Content Type \>\> ***Content type*** \>\> Comment display.

For further fine-tuning of the display of the comments, the module Views is advised, which will allow you to first select a lay-out in the "Comment display" referred to above, via:

* Structure \>\> Content Type \>\> ***Content type*** \>\> Comment display \>\> Layout for comment node ***content type***

& will then allow fine-tuning of the fields in the comments.

The approving of the content by the admin; considering comments; can be tweaked via the row:

* People \>\> Permissions \>\> Comment \>\> Skip comment approval

Alternative modules for admin approval of general content can be found in the following StackExchange-post:

Just a final extra remark (more of an alternative easy work-around really): if the text format (cf. *Configuration » Content authoring \>\> Text formats*) to be used for your users allows for the HTML -tag, one can of course tell your users how to "post" (but not upload technically) images as a comment, by explaining that they could use `<img src="`***URL***`">`, like you can find explained e.g. @ the W3C-wiki or @ W3-schools.

---

*P.S.: You are a funny guy to re-use Rome.*

---

I will leave my original answer below, which is more applicable to letting people upload pictures as separate nodes; but (as described below) is not a good method for letting people upload multiple pictures to already existing nodes (as you have now updated your question).

# Answer to your original question

What you can do is to create a new content type.

To do this, use the administrative overlay & go to:

* Structure \>\> Content Type \>\> Add content type.

Perhaps you could name the content type "**Add a photo**", or something.

Then, I would manage & display the fields such that all fields are hidden, except a field for a photo. This can usually be done after creating the content type, by going to:

* Structure \>\> Content Type \>\> **Add a photo** \>\> Manage fields.
* Structure \>\> Content Type \>\> **Add a photo** \>\> Manage display.

Then, I would restrict access to authenticated users (all of them / or some authenticated users; as you'd like) to create &/or edit certain content types only. This can be done (again, using the administrative overlay) by going to:

* People \>\> Permissions \>\> **Add a photo**: Create new content
* People \>\> Permissions \>\> **Add a photo**: Edit own content

The two boxes of these row can be checked at the column "AUTHENTICATED USER". (That is, if you'd like only authenticated users to be able to post pictures). Then, Creating & Editing of all the other content types should be disabled; if I understand you well. This can be done on the same page, by disabling the checkmarks for "AUTHENTICATED USER"s in e.g. the default content type "Article", via:

* People \>\> Permissions \>\> **Article**: Create new content
* People \>\> Permissions \>\> **Article**: Edit own content

This is just only what first comes to my mind. You'll see that Drupal is very flexible, and multiple roads lead to Rome.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Multiple buttons to link to different page and different query
I have a page in my site (from a custom module) with a hook\_menu (red boxes).

The code for the menu is as follows:

```
$items['upcoming_games/' . date('Y-m-d')] = array(
  'menu_name' => 'main-menu',
  'title' => 'Upcoming Games',
  'page callback' => 'my_page',
  'access callback' => TRUE
);

```

The page callback calls a function where I insert the date as an argument for a query. When clicking the menu, it defaults to TODAY.

What I need is to query for a different date depending on the click of the coloured buttons. I get "page not found"...

In the function where I have my query I get the date with the follwing code:

```
$date_to_show = arg(1);

```

What am I missing here?

# Answer
Use the following code:

```
function sample_menu() {
  // This is a default option, without argument.
  $items['upcoming_games'] = array(
    'title' => 'Upcoming Games',
    'page callback' => 'my_page',
    'page arguments' => array(),
    'access callback' => TRUE,
  );
  // This is for any other date.
  $items['upcoming_games/%'] = array(
    'title' => 'Upcoming Games',
    'page callback' => 'my_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
  );

  return $items;
}

function my_page($date = NULL) {
  // If the $date has not been defined, it means that the user is trying to see
  // today's games.
  if (!$date) {
    // Redirect to today's date.
    drupal_goto('upcoming_games/' . format_date(REQUEST_TIME, 'custom', 'Y-m-d'));
  }
  // Otherwise, check the date. The strtotime() function is just as an example.
  else {
    $date = strtotime($date);
  }
  // Continue the operation.
  // ...
  return 'Upcoming games for ' . format_date($date, 'custom', 'Y-m-d');
}

```
> 0 votes

---
Tags: navigation, routes, theming
---


# Question
Title: Additional fields for my entity from another table in views
I have table of my entity with structure:

```
=====================================
eid | myfield1 | myfield2 | myfield3
=====================================

```

And also an additional table with primary key being foreign key to my entity id:

```
==========================
eid | myfield4 | myfield5
==========================

```

I would like to expose values in my second table to view of fields, of my entity, but I don't want to join second table with first, every time, but only if I will use one of its fields.

I believe it should be doable with views\_join class modifying a query at handler level, but is it possible on hook\_views\_data\_alter() level?

Is it possible to do this transparently - so I wouldn't need to add any relationship to view (just like the field values are pulled from fields tables - yes, you can think a bit about it as about creating fields alternative ;) ) ?

# Answer
Technically it's possible, using *hook\_views\_query\_alter()*, you can adapt the view query to add or change conditions. So you could add a join with something like this:

```
function modulename_views_query_alter(&$view, &$query) {
  $join = new views_join();
  $join->table = 'mytable';
  $join->field = 'eid';
  $join->left_table = 'entity_table';
  $join->left_field = 'eid';
  $join->type = 'left';
  $query->add_relationship('relationship_name', $join, 'entity_table');
}

```

But a better approach would be to use *hook\_views\_data()* to expose your table to views, and then add the relevant fields when needed (with a relationship though), but in practical terms is no different than altering the query.
> 0 votes

---
Tags: views, entities
---


title: Create a view with user selected fields

text:
# Question
Title: Create a view with user selected fields
I need to create a view with user selected fields. My basic requirement is *data export*. My site contains around 1500 nodes and each node has around 25 fields. I have a view for *data export* with 5 fields.

My specific need is to create a control panel for selecting the fields i want – and in a following step I have to create a view with the selected fields.

# Answer
> 1 votes
Sounds as you need Views Dynamic Fields. From the project page:

> The Views Dynamic Fields module provides a filter for use with Views module. This filter allows the user to pick and choose which fields to display for a rendered instance of a view for that user. This provides a customized view instance for each user.
>
> This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.

---
Tags: views, entities, importing-exporting
---


# Question
Title: Is there way to display thumbnail gallery using external links to images?
Drupal 7, is there way to display thumbnail gallery using external links to images?(instead of uploading pictures) Something like

https://wordpress.org/plugins/wp-gallery-custom-links/screenshots

I have Views, Imagecache External, Views Responsive Grid modules installed, but no one of them helps me to achieve this simple task. I want create responsive thumbnail gallery with external images.

# Answer
> 2 votes
It might be it is the Link Image Formatter module that you are after.

It is a image formatter for a Link field. The modules you mentioned can then be used to construct your gallery (Views, Imagecache External, Views Responsive Grid).

You could also rewrite the field output in Views by using the "token" and wrapping it in the needed HTML to display it as an image, something like:

```
<img src="[link]">

```

Make sure you get a plain version of the image URL, so you better check without rewriting first.

Note that using Imagecache External will result in images being stored on your own server. It doesn't free you from copyright issues as with embedded external images (hotlinking). That means you could alternatively use FileField Sources.

An extension module of the last one, Remote File Source, might avoid transfer of the image file on your server. I haven't tested that. You are likely to miss out on Image Styles in that case (e.g. to resize or cache images locally).

# Answer
> 0 votes
You can use the Flickr module. The only problem would be that all the images would be hosted at Flickr.

---
Tags: 7, nodes, views, media
---


title: Adding help text to drupal comment form

text:
# Question
Title: Adding help text to drupal comment form
using Drupal 7, I'd like to add some help text underneath each field for the user who is filling out the comment for a node.

For example, under 'your name' I'd like it to say, possibly in smaller font, "only give your name if you want it published with your comment".

Anyone know how to do this (maybe with hook\_form\_alter)?

# Answer
> 2 votes
I think in hook\_form\_alter, you need to check the $form\_id first, so that you can target comment form. If it is a comment form, then you need to add description for the field you want. Just like this

```
function hook_form_alter(&$form, &$form_state, $form_id) {

$form['name']['#description'] = t('Me help text'),

```

`}`

# Answer
> 2 votes
Or just edit comment.tpl.php in your template files. Copy comment.tpl.php to your template folder and if not present in the code, add $author name and desired text.

---
Tags: comments
---


# Question
Title: How do I use '#attached' to attach a style sheet?
I know that `drupal_add_css` is depreciated, and that we should use `#attached` instead to attach a css style sheet to a module.

I am trying to replace the following (which works):

```
drupal_add_css(drupal_get_path('module', 'mymodule') .'/mymodule.css');

```

with `#attached`. But haven't found exactly where and how to add it.

Here is my second attempt (it still does not work):

```
/**
 * Implementation of hook_block_view()
 */
function mymodule_block_view($delta = '') {
  if ('mymodule' == $delta) {
    $render = array();
    $list = mymodule_fetch_from_info();
    foreach ($list as $element) {
      $render[] = array(
        '#type' => 'markup',
        '#markup' => $element[0],
        '#weight' => $element[1],
      );
    }
    $blocks['subject'] = t('Mymodule');
    $blocks['content'] = $render;
    $blocks['#attached'] = array (
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/mymodule.css',
       ),
    );
    return $blocks;
  }
}

```

# Answer
> 4 votes
You cannot use #attached inside your hook\_theme implementation. Instead, you should add it when you're building a render array:

```
$blocks['content'] = $render;
$blocks['content']['#attached'] = array (
  'css' => array(
    drupal_get_path('module', 'mymodule') . '/mymodule.css',
  ),
);

```

As kiamlaluno already pointed out in the comments, in your code example `$blocks['content']` is the render array, so the `#attached` element must be part of that array.

---
Tags: 7, theming
---


# Question
Title: CKeditor adding an extra
 tag when a
 tag is encountered
I am experiencing a very annoying problem with ckeditor 4.4.7.3. Everytime a `<br/>` is entered into the editor, it displays the next line right below the existing line as one would expect. However, when you view the page, an extra `<br/>` tag appears along side the original `<br/>` tag. You can see this when looking at the source for the page.

```
Rendered output
<p>
  <strong>Age</strong>
  <br>
  <br>
  24
</p>

```

Looking at the source html while in ckeditor reveals that there is only one `<br/>` there.

```
Source as seen in ckeditor
<p>
  <strong>Age</strong>
  <br>
  24
</p>

```

This would seem to indicate to me that Drupal is adding line breaks while rendering the output. I have tried disabling the option: Convert line breaks into HTML (i.e. `<br>` and `<p>`) in the text format, but that doesn't change anything. I have also disabled JavaScript to see if some JavaScript file is doing this - but that makes no difference either.

I have googled this issue and have not found a solution yet (other people have been experiencing as well but no solution given). I would appreciate any suggestions in fixing this problem.

# Answer
> 3 votes
As it turns out, disabling the option: Convert line breaks into HTML (i.e. `<br>` and `<p>`) in the text format does make a difference. I needed to flush the cache to see the results. Hopefully this will help other people who experience this problem.

---
Tags: 7, wysiwyg
---


# Question
Title: Users have access to add Commerce Products into the Store and publish it. How to display to user only allowed firms in the product addition form?
My webshop has lot of users with role Seller. They can add SKU and publish goods. Product display content type has field "**Firm**" that is taxonomy term reference.

Now **every Seller can see all the firms** (all the terms) when he add a product and he can check anyone. This is very uncomfortable because Seller work with only a few firms and he want to see only his firms to check one of it.

I want to display only user referenced firms in this field when user add a product.

How do I do this?

1. I've added to user profile field "Seller Firms" that is the term reference to the Firms. Using module Field Permissions I've made this field accessible to edit only by administrator.
2. I've checked for each user his firms that he can have access to publish goods of these firms (seller will can to check only those firms that I've checked in profile)
3. **So how to alter product addition form to show only user allowed firms?** I have few product displays machine names: product, product\_with\_attributes

I think this will be hook\_alter\_form or Rule that will limit the selection to only a few firms that are allowed.

I've made the first part this way: 1. I add Entity Reference field "Seller" to taxonomy Firms that link to users profiles. 2. I'd fill this field for all terms with users that must have access 3. I start to write my module that will display only user referenced terms in node add form. I do not know how to write this. The field name in node Product Display: field\_firm. Field Entity Reference in terms: field\_seller. Help me to finish my module:

```
function user_referenced_taxonomy_terms_form_node_form_alter(&$form, &$form_state, $form_id) {
  //$form ['field_firm']
}

```

# Answer
It is possible using `hook_alter_form` but hook\_form\_FORM\_ID\_alter would be better so you only target the correct form.

You will need code to retrieve only the firms the user has from their profile field and then using `array_diff` to remove the others from the select options.
> 0 votes

# Answer
I've made this code without forming new array of allowed firms. Finish it please.

```
function user_referenced_taxonomy_terms_form_node_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }

  $query = new EntityFieldQuery();
  $term_entities = $query
    ->entityCondition('bundle', 'firms')
    ->entityCondition('entity_type', 'taxonomy_term', '=')
    ->fieldCondition('field_seller','target_id',$user->uid) // if user has access
    ->execute();
  if ($term_entities) {
      //forming array of firms using $term_entities array
      //HOW?
      //$form['field_firm']['und'] = drupal_map_assoc( $term_entities );//not correct
  }else {
      //hide field firm if user has no access to any term
      $form['field_firm']['#access'] = FALSE;
  }

}

```
> 0 votes

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


title: Which module can hide or show text?

text:
# Question
Title: Which module can hide or show text?
I have a site with puzzle and I need to hide or show some answer. It can be some photo or some text. It can't be block, I need a module that will be able to hide or show fields as is it done in the photo modules When I add some photo in any article. How can I hide or show it?

# Answer
There is a Quiz module, that looks awesome: https://www.drupal.org/project/quiz

> The Quiz module lets you create graded assessments in Drupal. A Quiz is given as a series of questions. Answers are then stored in the database. Scores and results are displayed during or after the quiz.

A simpler option might be the Peekaboo module: https://www.drupal.org/project/peekaboo

> Use cases: ... Fields that reveal more information
>
> Peekaboo can also be used purely for the Ajax functionality as a gimmick to reveal more information.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Drupal Commerce AJAX HTTP Error 200 while adding product display
has anyone else come across this? I'm getting an error when I'm trying to create a product display. It happens when I'm trying to put in the product SKU.

> An AJAX HTTP error occurred.
>
> HTTP Result Code: 200
>
> Debugging information follows.
>
> Path: http://hayfield.com:8082/commerce\_product/autocomplete/node/field\_product/product\_display
>
> StatusText: OK
>
> ResponseText: `{"glorious_dream":"\u003Cdiv class=\u0022reference-autocomplete\u0022\u003Eglorious_dream: Glorious Dream\u003C\u002Fdiv\u003E", "Hayfield_Elegance":"\u003Cdiv class=\u0022reference-autocomplete\u0022\u003EHayfield_Elegance: Hayfield Elegance\u003C\u002Fdiv\u003E"}jQuery.extend(Drupal.settings, {"thmr_1":{"id":"thmr_1", "name":"link", "used":"theme_link", "type":"func", "duration":2.78, "candidates":[ "hayfield_link" ], "preprocessors":[ ], "processors":[ ]}, "request_id":"1852760308506e2eabeea31", "devel_themer_uri":"\u002Fdevel_themer\u002Fvariables\u002F1852760308506e2eabeea31"});`

Thanks in advance!!

# Answer
Theme, library, preprocess code. Check what you've modified. – Bojan Zivanovic

Thanks to Bojan I downloaded and copied over the original zen preprocess file and it works!! I must have edited that preprocess file by accident instead of the one in my subtheme.
> 0 votes

# Answer
I've seen this error before, you should start from scratch with the latest release candidate for Drupal Commerce, located here: http://drupal.org/node/1786764. This fixes the AJAX bug.
> 0 votes

# Answer
I think this error occurs when some of your modules are outdated. Have a look at your modules, also the Ajax is sometimes having problem with devel modules. Disable devel module and then check it. Good luck.
> 0 votes

---
Tags: 7, ajax, commerce
---


# Question
Title: How to get Product name instead of sku in email to admin in authorize.net?
My client has a drupal site where the admin gets a SKU in the confirmation email. He wants to replace that with product name. How can I do that and where do I have to change it?

I found this patch, but I don't see the file in authorize.net module to patch the code.

Can anyone help me out.

Thank You.

# Answer
> 0 votes
You might want to modify **uc-order--admin.tpl.php** under **sites\all\modules\ubercart\uc\_order\templates**
look for: `$product->model` (SKU) and comment it out or replace it directly with `$product->title` , modify the template to your liking but always keep a copy of the original template.

---
Tags: ubercart, payment-gateways
---


# Question
Title: Difference between DRUPAL_CACHE_PER_PAGE and DRUPAL_NO_CACHE
What is the difference between **DRUPAL\_CACHE\_PER\_PAGE** and **DRUPAL\_NO\_CACHE**?

I'm developing a module that will generate 2 blocks for menu and it's sub-menu in different blocks and can't decide between those two options for the blocks.

**links:** https://api.drupal.org/api/drupal/includes%21common.inc/constant/DRUPAL\_NO\_CACHE/7 https://api.drupal.org/api/drupal/includes%21common.inc/constant/DRUPAL\_CACHE\_PER\_PAGE/7

# Answer
> 2 votes
* `DRUPAL_NO_CACHE` doesn't cache the item, ever.
* `DRUPAL_CACHE_PER_PAGE` caches the item per page url -- this is useful for example if the block changes with a url context.

---
Tags: routes, caching, blocks
---


# Question
Title: Adding Search Block to Bootstrap 3 Navbar
The search block using the twitter bootstrap 3 theme doesn't show inline with the rest of the navbar. What is the trick to get this to show inline?

I have tried to add it to the page.tpl.php without success.

Any ideas?

EDIT:::

I've added this to the template:

```
 <div class="col-md-3 pull-right">
           <?php if (!empty($page['searchblock'])): ?>
            <?php print render($page['searchblock']); ?>
          <?php endif; ?>
          </div>

```

However, that doesn't seem exactly right for this bootstrap theme. In the bootstrap code one wraps the search like so:

```
<form class="navbar-form navbar-right" role="search">
  <div class="form-group">
    <input type="text" class="form-control" placeholder="Search">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

```

Do I need to modify the default search block template? Thanks for any help to my ignorance as i learn this system. Really digging Drupal 7 right now!

# Answer
> 1 votes
I had the same feature request. In `mytheme/template.php` I've added

```
/*
 *  Preprocess page.tpl.php to inject the $search_box variable.
 */
function mytheme_preprocess_page(&$variables){
  $search_form = drupal_get_form('search_form');
  $search_box = drupal_render($search_form);
  $variables['search_box'] = $search_box;
}

/*
 *  Form alter to add missing bootstrap classes and role to search form.
 */
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#attributes']['class'][] = 'navbar-form';
    $form['#attributes']['role'][] = 'search';
  }
}

```

In `mytheme/templates/page.tpl.php` I've added

```
<div class="col-md-3 nav nabvar-nav navbar-right">
  <?php print $search_box; ?>
</div>

```

After the

```
<div class="navbar-header"> div.

```

There still was a problem with a float:left applied to secondary links menu (instead of the proper boostrap navbar-right. So, for a quick workaround, in `mytheme/css/style.css` I've added:

```
@media(max-width:768px){
  ul.secondary{
    float:none!important;
  }
}

```

# Answer
> 0 votes
I'd do something along these lines:

```
<form class="navbar-form" role="search">
  <div class="input-group">
    <input type="text" class="form-control" placeholder="Search"/>
    <div class="input-group-btn">
      <button class="btn btn-default" type="submit">
        <span class="sr-only">Search</span>
        <span class="glyphicon glyphicon-search"aria-hidden="true"></span>
      </button>
    </div>
  </div>
</form>

```

# Answer
> 0 votes
According to your tag, you're looking for a D7 solution. The Drupal 7 page.tpl.php doesn't have the $search\_box variable anymore. However you can add it in a preprocess function in your template.php:

```
<?php
/*
 *  Preprocess page.tpl.php to inject the $search_box variable back into D7.
 */
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

```

Then you just need to print the variable in your page.tpl.php:

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

```

You could also use module\_invoke, but you shouldn't have php logic in template files:

```
<?php
  $block = module_invoke('search', 'block_view', 'search');
  print render($block);
?>

```

Answer originally posted https://drupal.stackexchange.com/a/10288

# Answer
> 0 votes
According to the bootstrap module page about this issue ( search block in navbar strange behaviour ), the best solution to date is the following css rule :

```
#search-block-form .input-group-btn {
  width: auto;
}

```

# Answer
> 0 votes
Here's how I did it following the comment of Chris Godwin in page.tpl.php:

> ```
> <?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>
>   <div class="navbar-collapse collapse">
>     <nav role="navigation">
>       <?php if (!empty($primary_nav)): ?>
>         <?php print render($primary_nav); ?>
>       <?php endif; ?>
>         <div class="col-md-3 nav nabvar-nav navbar-right">
>             <?php print $search_box; ?>
>         </div>
>       <?php if (!empty($page['navigation'])): ?>
>         <?php print render($page['navigation']); ?>
>       <?php endif; ?>
>     </nav>
>   </div>
> <?php endif; ?>
>
> ```

---
Tags: theming, blocks, search
---


title: How PHPTemplate works and what it do?

text:
# Question
Title: How PHPTemplate works and what it do?
There is a default templating system PHPTemplate in Drupal, they say.

But where can I see it? I don't see anything more than pure php in template files .tpl.php. Once I've seen template system Smarty in non-drupal webpage files and there was tempalting syntax with `{ }` braces in .php files with HTML. I also have seen Blade templating syntax in Laravel framework's files.

So where is the PHPTemplate in Drupal (or how it works and what it do?)

# Answer
PHPTemplate:

> A theme engine that allows you to use template files written in pure php. These template files do not need to be processed by the theme engine, and as such execute a lot faster than most other template engines. Another major advantage to using PHP as your template language, is flexibility, as the advanced user can access any information / functionality available in the Drupal API, and is not restricted to what the template engine / language allows him to do.
>
> This is the default theme engine starting in Drupal 4.7. If you are using Drupal 4.7 and above, you don't need to download PHPTemplate here.

A Template system does not need to use special code or markup to be called a template. PHPTemplate refers the system of implementing pure php code template files, how those files are accessed and referenced by the system and how other parts of the system (such as template.php) can modify the results of those files
> 1 votes

---
Tags: theming
---


# Question
Title: Annoying general behavior: the width of the text-input-fields, when editing a node, can be up to 2X your screen's width / decentered
I was just wondering whether anyone else is annoyed by the curious & sporadic behavior of Drupal of making the widths of the text-input-fields very large, when starting to edit a node.

The widths of the **text-input-fields** (by default: "**Body**" & "**Summary**") get as much as 2 times the width of my computer screen.

Would anyone know how to get under the hood, to try and come up with a fix?

I am also not sure about the origin of the behavior, which sometimes does show up; and at other times don't.

Thanks.

# Answer
With the help of the adept question by @J.Reynolds

Might solve this issue: (did so for me)

# Just change the administration theme a couple of times

This can be changed at **Appearance \>\> Administration**

* To which you can navigate manually using the administrative overlay
* Or to which you can arrive directly, by default, via **www.Your-Website-Domain**`/#overlay=admin/appearance`
> 0 votes

---
Tags: nodes
---


# Question
Title: Scald: themable atom reference – where to find image path etc.?
I can't find a way how to get an atom reference's values (image path etc.) into my theme template. When printing the node array I do get the SID for the referenced image, but I just don't know how to load the actual details.

Or is it possible by simply using `node_load` or `entity_load` or the like? Any pointers gladly appreciated.

# Answer
Found the answer to my question one of scald's issue pages – and it's not really complicated. Either it's just not well documented, or I just didn't see it:

This gets the `SID` from the node's array:

```
$img = $vars['node']->field_teaser_image['und'][0]['sid'];

```

And this fetches the atom reference's object:

```
$atom = scald_atom_load($img);

```

This is how I then load the title of the atom reference image inside `template.php`:

```
$vars['img_title'] = $atom->title;

```

And the actual filename is inside another object `base_entity`:

```
$vars['img_filename'] = $atom->base_entity->filename;

```

Hope this may help somebody some day.
> 1 votes

---
Tags: entities, nodes, scald
---


title: Perform Row Functions in a View

text:
# Question
Title: Perform Row Functions in a View
Trying to get a calculation at the end of an Aggregated Table or even Pivot Table in Views, but as it seems to be a bit of a two step process, I can't figure it out for the life of me...

I have the following table of user skills, pulled together using aggregation (for a number of reasons the way the data has to be gathered). I can also use a pivot to the same result.

I want to then be able to evaluate overall skill of each user by counting the Lows, Mediums and Highs for each user, multiplying them by 1, 2 and 3 respectively, and then add them together to a Total Skill value, per below:

Any ideas on how to do this, or an appropriate module that would give me this result?

# Answer
Why don't you use `THEME_preprocess_views_view_fields(&$var)` function? In this function you may get every field of the view, and do any processing you want just before loading the view. just install devel module, and use `kpr` to see what variables are available.
> 0 votes

---
Tags: views
---


# Question
Title: What is the difference between base tables and data tables for content entities?
Recently, Views was updated to use data tables (the `data_table` annotation on `@ContentEntityType`) by default. See the change record at https://www.drupal.org/node/2433153.

This caught me out since I had both defined on my entity. I hadn't thought much about it, and I don't even know which example got me to do that. I think I may have based mine off `\Drupal\comment\Entity\Comment`.

Anyway, what's the difference in terms of when they get used? It seems that, despite having defined `data_table`, all my data was being saved in the `base_table` anyway, and this caused Views not to work until I removed the `data_table` property from my `@ContentEntityType` definition altogether.

It seems my fields ought to be using `data_table`. What did I do wrong in my entity? I'm porting a module and thus using `8.0.0-beta9`.

# Answer
My guess is that you didn't actually set the translatable flag to TRUE. The data\_table is only used then, but I guess views gets confused if you have it set but the entity type is not translatable, sounds like a bug in views but it also doesn't make sense to define the table and not have your entity type translatable.

The difference of those two tables is that it contains a row for each translation of your entity type. For example, `{ńode}` has just the nid, vid (which is the current revision), type and uuid. All the other fields are in the data table, like the node title, status, changed date, and so on.
> 7 votes

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


# Question
Title: User login link is always visible in menu
I have created user login link in the user account menu but the link is visible all the time(even for logged users). The user profile menu link and the user logout links are displayed properly(they are added by the user module).

My link definition doesn't differ from the user's module link definitions in any way but still this happens. Also the user.login route has proper requirements so this should just not happen but it does.

This is how user module defines menu links:

```
user.page:
  title: 'My account'
  weight: -10
  route_name: user.page
  menu_name: account
user.logout:
  title: 'Log out'
  route_name: user.logout
  weight: 10
  menu_name: account

```

This is how I define my login link:

```
user.login:
  title: 'Log in'
  weight: -10
  route_name: user.login
  menu_name: account

```

# Answer
This seems to be a bug, /user/login should not be accessible as an authenticated user, but it redirects to user/1.

Edit: Discussed this with @dawehner and we figured it out together. This is egression: Do not bypass route access with 'link to any page' permissions for menu links

Open a bug report. This might actually a be a pretty serious security issue, looking at AccessManager, I don't understand why that starts with an allowed() state,LoginStatusCheck returns neutral, that is merged together to an allowed().
> 2 votes

---
Tags: routes, navigation, 8
---


# Question
Title: Node content not available to anonymous users
I'm having some trouble with viewing my nodes as an anonymous user. When not logged in as admin, I am still able to access the URL of the node, but the content (other than the title) is blank. I've spent a lot of time looking around the permissions, but I can't seem to resolve this issue. The problem exists when accessing the node directly or through a view.

The below example uses nodes with the Link field type, but I'm also having the same problem with my text and file fieldtypes.

This is what displays in a particular view as anonymous:

The same view, logged in as admin:

Hopefully an easy fix, any recommendations would be great!

# Answer
Try rebuilding site content permissions. Every now again that has tripped me. In D7 you can find it @ **/admin/reports/status/rebuild**.
> 0 votes

# Answer
In this case, it was the Organic Groups Field Access module causing the problems. Disabling the module allowed anonymous users to view the full node properly.
> 0 votes

---
Tags: nodes, users
---


title: Project structure

text:
# Question
Title: Project structure
I was wondering what would be the best way to setup a Drupal 8 website that has about 15 mostly static pages in three languages? Static pages are somewhat similar but do contain different content.

Since it's multilanguage site and has different static and some dynamic content am i supposed to put everything in blocks to be translatable or is there a better way? Views maybe? I'm a little bit confused and don't even know if Drupal way is the good way to do it.

I know that my question is broad and not so specific but any help is much appreciated!

# Answer
> 1 votes
This is an extremely broad question, so I can only give you a broad answer.

You don't create pages in Drupal like you might be used to from other CMS. You create *content*.

You need to change how you think about content to work efficiently with Drupal. First off, create your content, and then think about how to display it.

The closest to creating pages is creating nodes/content. Go to /node/add (or Manage \> Content \> Add content) and create a few pieces of content, for example of type Page. Make sure you enable the content translation module and add your languages so that you can translate it.

Each node (technical term)/piece of content is by default visible at node/ID or an alias that you define. That's your "page". But you can also create a view to create a list of content somewhere, based on some conditions.

Blocks are used when you want to place a certain piece of content into one of the block regions on all/many pages.

Do that, and then come back and ask more specific questions.

---
Tags: views, blocks, 8
---


title: How to deploy translations in code?

text:
# Question
Title: How to deploy translations in code?
As the title states, I want to export the translations in code and deploy it with a version control system like GIT.

We have a multi-language Drupal system (English and German) and we have Localization Update module installed.

While some modules doesn't even have a German translations, some are insufficient and some translations are not how we like to have them.

So I add/edit the translations using the UI under `admin/config/regional/translate/translate` and I can export them into a `de.po` file under `admin/config/regional/translate/export`.

I don't know really where to put this file and commit/push so that I can update the languages on other development and production environments.

We have a 3 stage development environment. Local - Dev - Pro. I do all things in local and push to Dev.

But with translations I couldn't get this workflow. Everytime I update a string's translation, I do it on every environment manually and this is not a perfect way. There must be something I'm missing.

# Answer
You could use Features Translations:

> **Features Translations** adds a new Features component called Translations that allows to import/export sets of translated strings. String sets can be chosen per language and per text group.
> 3 votes

# Answer
Your best bet is to use the Potx Exportables module. Here is a quote about it (from the module's project page):

> ... aims to ease the deployment of translation .PO files that the great Potx module generates. No longer will you have to manually upload these files to keep your site translations up to date. You can manually batch import all PO files defined in custom modules or alternatively, you can use the always useful Drush command to make things easier for you.
> 2 votes

---
Tags: 7, version-control, i18n-l10n
---


# Question
Title: EntityStructureWrapper for file field is not being inflated properly while iterating
While trying to interate over file filed values, EMW cannot being created properly. using `isset()` for not iniated fields and then trying to set them is not helping.

I get the error:

> EntityMetadataWrapperException: Unknown data property field\_discipline. in EntityStructureWrapper-\>getPropertyInfo() (line 335 of /var/www/siradisisporlar.com/sites/all/modules/ssbasic/entity/includes/entity.wrapper.inc).

Note that file wrapper here is EntityStructureWrapper and node wrapper is EntityDrupalWrapper.

All properties of other entity reference fields, etc are being reached properly.

`$filew::data` is array and it has fid where `$nodew::data` is a proper node object.

```
mymodule_node_insert($node) {
  //.... ..... $nodew is node wrapper
  foreach ($nodew->field_media as $delta => $filew) {
    $a = $filew->field_taxonomy_entity_reference->value(); //error here
    $b = $nodew->field_taxonomy_entity_reference->value();
    $c = array_unique(array_merge($a, $b));
    $filew->field_taxonomy_entity_reference = $c; //error here
    $filew->save();
  }
}

```

# Answer
> 1 votes
Sadly, I am posting a very bad workaround for future reference. Anybody who can improve this is welcome:

```
function mymodule_node_insert($node) {
  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //@todo this is not cool, figure it out
  foreach ($nodew->field_media->value() as $delta => $files) {
    $filew = entity_metadata_wrapper('file', $files['fid']);
    $filew->field_taxonomy_entity_reference = array_unique(array_merge($filew->field_taxonomy_entity_reference, $nodew->field_taxonomy_entity_reference));
    $filew->save();

  }
}

```

---
Tags: 7, entities, files
---


# Question
Title: how can I hide ShareThis icons from teasers
I installed the ShareThis module which works great for me, except I would like to hide the share icons from appearing in teasers. How can I do this?

Thanks

# Answer
Go to content type's manage display section and select `Teaser` tab on top right. There you can change the `display settings` of the `teaser`.
> 5 votes

---
Tags: 7, nodes, social-network
---


title: How do I merge this code?

text:
# Question
Title: How do I merge this code?
In Drupal 7. I have the following code in my template.php file:

```
function mytheme_theme($existing, $type, $theme, $path) {
   return array(
   'comment_form' => array(
   'render element' => 'form',
   ),
 );
}

```

I also would like to use the following code to theme the Register page:

```
function mytheme_theme() {
  $items = array();
    $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
       'mytheme_preprocess_user_register_form'
    ),
   );
 return $items;
}

```

How do I merge the two snippets of code?

Any help on this is greatly appreciated. :)

# Answer
> 2 votes
@duru's answer will work, but is needlessly complex and makes it difficult to see the structure of the returned array. This is equivalent:

```
function mytheme_theme($existing, $type, $theme, $path) {
  return array(
    'user_register_form' => array(
      'render element' => 'form',
      'path' => drupal_get_path('theme', 'mytheme') . '/templates',
      'template' => 'user-register-form',
      'preprocess functions' => array(
        'mytheme_preprocess_user_register_form'
      )
    ),
    'comment_form' => array(
      'render element' => 'form',
    )
  );
}

```

# Answer
> 3 votes
Just merge like:

```
function mytheme_theme($existing, $type, $theme, $path) {
  $items = array();
    $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
       'mytheme_preprocess_user_register_form'
    ),
   );
   $items['comment_form'] = array(
    'render element' => 'form',
    ),
   );
 return $items;
}

```

---
Tags: theming
---


# Question
Title: using sass to generate RTL & LTR css files in Omega 4
is there any convenient way of using Omega 4 to compile rtl and ltr css files automatically. I mean something like this or this, but for drupal.

# Answer
I guess it depends on what you define as being convenient.

The SASS part is easy, since sass support is already setup in Omega. You just need to setup some sort of a sass structure to write the CSS.

To change the language settings, you'll want to invoke the template\_preprocess\_html() function to override the html that's rendered. function template\_preprocess\_html
> 1 votes

# Answer
found the answer! no need to do any sass related work. I was working with layouts, and all I did was adding a file named `mylayoutname.layout-rtl.scss` under `sass/layouts/mylayoutname/` solved my problem :) it compile automatically to appropriate css file without any hassle.
> 0 votes

---
Tags: drush, theming
---


# Question
Title: Custom validation rules for content entity fields
So I want to store an `entity_type` in a string field in my content entity.

Since the list of entities can change over time, I can't use a `list_string` field with allowed options. I don't know if calling out to `entity_manager` would even work properly in that context.

So my current plan just to use a `string` field and somehow validate that the values the system attempts to save are valid entity type machine names.

How can I perform this validation at the field level? At the entity form level, I will obviously have to add a custom `select` field and interpret/set the value in the `(entity form class)::save()` method.

# Answer
> 1 votes
list\_string can have an allowed\_values\_callback instead of a list of allowed values, that allows you to return a dynamic list from that callback.

See callback\_allowed\_values\_function(), which has pretty good documentation, that we've refined over multiple issues.

Make sure you're aware of the rules and limitations of what you can return.. for example that not passing an entity should always return all allowed values and passing one it can only limit those and not add more. And that returning new allowed values is not a problem, but not returning them anymore can be problematic as you might end up with data in your database that is no longer valid. The UI doesn't allow you to do that, for example.

---
Tags: 8, entities
---


# Question
Title: WYSIWYG module w/CKEditor not working drupal 7
I am unable to get WYSIWYG working with my Drupal 7 installation.

I watched a screencast to ensure I installed the module and library correctly, and everything appears to be properly installed. My host has PHP4 by default, but I am able to enable PHP5 and have done so.

* The module is installed at: /www/drupal/sites/all/modules
* The CKEditor library is installed at: /www/drupal/sites/all/libraries

I have enabled WYSIWYG as the screencast demonstrated and receive no error message at all. I enable and configure the module exactly as it's done in the screencast, yet when I go to edit the plain text version is still there.

I've tried CKEditor on it's own but kept running into a tmp file issue that I could not resolve so abandoned the idea.

At no point is there error text. It just doesn't work.

I have tested this in Chrome and IE9. I have also tried various other libraries and there is no luck. I tried TinyMCE and FCKEditor too.

# Answer
In order for the CKEditor menu to appear you must select your preferences. After you have assigned an editor to the input format (full HMTL, filtered HTML, etc.) click the edit button to the right. Then select buttons and plugins and tick the items you want to use. Then the editor toolbar will show above the summary. Drove me insane for a month until I figured this out!
> 5 votes

# Answer
Did you allow users to access the text format (e.g. filtered) at admin/config/content/formats?

Configure the Wysiwyg profile for that format at admin/config/content/wysiwyg.

If yes and yes, the only other thing I can think of is to check your settings in the "basic settings" section at: admin/config/content/wysiwyg/profile/filtered\_html/edit (this is for the "filtered html" format as you can see in the URL).
> 4 votes

# Answer
Be sure to download the *regular* CKEditor release from http://ckeditor.com/download to install in your sites/all/libraries folder. The "CKEditor for Drupal" release is a separate Drupal project (actually, a module, not a library). The "CKEditor for Drupal" release is not the release that works with the WYSIWYG module.
> 3 votes

# Answer
If you have previously enabled another wysiwyg editor for the input format: fckeditor, for example, make sure you remove the profile before attempting to add the ckeditor. Basically, you will not get a dropdown asking what wysiwyg editor you want to use, unless you remove it via the drupal interface first.
> 2 votes

# Answer
Make sure that CKEditor is chosen on /admin/config/content/wysiwyg with the input format you're using. Do you see any Javascript errors?
> 1 votes

# Answer
I had the same problem after I updated to 7.12. The editor did not appear on any textareas where it used to be.

In my case it was the Administration Menu module that was the culprit. It didn't work with the jQuery version that Drupal 7.12 ships with and needed a patch. After that all is fine again :)
> 1 votes

# Answer
I answered this question here

As another user stated, make sure you have enabled the appropriate tags and buttons for the plugin. I currently have mine running, and it works like a charm. If the buttons are not enabled, everything will appear like you just have a plain text box.
> 0 votes

# Answer
Clear the cache memory from admin/config/development/performance, then try again. Wysiwyg will appear as profile, and you can select your editor.
> 0 votes

# Answer
When I installed the module WYSIWYG Media Embed it kept my WYSIWYG display from appearing. As soon as I disabled this module everything was back to normal.
> 0 votes

# Answer
When I had the same problem, the thing that got me up and running was fixing the file permissions on the server. When I had unzipped the ckeditor directory and moved it into the sites/all/libraries directory, the permissions were as follows:

* Directories: 771
* Files: 644

The above doesn't allow the web server to actually serve the files. What they need to be set to in order to work (and for the CKEditor window to show up) is:

* Directories: 755
* Files: 655

To fix this, I went to the sites/all/libraries directory and ran the following two commands

```
find ckeditor/ -type d -exec chmod 755 {} \;
find ckeditor/ -type f -exec chmod 655 {} \;

```

The first recursively sets all the directories to 755, and the second sets the files to 644. At this point, the file permissions were set right, but it still wasn't working in my browser, as I needed to clear the caches. If you use drush, that's:

```
drush cc all

```

or you can go to Configuration -\> Development -\> Performance -\> Clear All Caches from the admin interface. If it's not working at this point, your browser might still be the issue (it was for me), so this is how you make sure you're completely clearing the cache in Chrome, for example:

1. Hit F12 to open Developer tools (or Ctrl+Shift+i, or Menu -\> More tools -\> Developer tools)
2. Right-click the refresh button
3. Click Empty Cache and Hard Reload

At this point, if permissions were the issue, you should have CKEditor working.
> 0 votes

---
Tags: 7, input-formats, wysiwyg
---


# Question
Title: Using the Drupal 7's Block "description" field as a CSS class field
I need to add a css class to my blocks and I know I can install a module, but i rather not as it doesnt work with features. I was thinking of just using the block config's **description** field to hold my css classes and just output it in my block.tpl.php file or should i do a preprocess thing?

Now the question is what is the variable to output the block's "description"?

# Answer
> 1 votes
If I understood your question correctly, you have two options:

A) Use a `_preprocess_block()` function:

```
function THEME_preprocess_block(&$vars) {
  // Make sure that this is a custom block, and not a block that is provided by
  // a module.
  if ($vars['block']->module == 'block') {
    // Load the block information.
    $info = block_custom_block_get($vars['block']->delta);
    // Add block description to the list of classes.
    $vars['classes_array'][] = $info['info'];
  }
}

```

B) Use the Skinr module. Probably will require more work, but it's much more flexible and editors / non-tech staff will be able to define styles of blocks. From the project page:

> Skinr's main purpose is to allow the theme to define a set of reusable and modular CSS styles, and to make those styles available in Drupal's UI.

# Answer
> 1 votes
You could try the Block Class module, seems relatively popular and well maintained:

> Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent element of a block. Hooray for more powerful block theming!
>
> To add a class to a block, simply visit that block's configuration page at Administration \> Structure \> Blocks

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


# Question
Title: Using Entity metadata wrappers to change field value under hook_node_insert()
I am trying to change a field value inside both `hook_node_insert()` and `hook_node_update()` using EMW. It actually changes the original `$node` object that is passed to these hook functions but the change doesn't get saved at the end.

```
function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type = $nodew->field_hidden_type->value();//this actually works
  $messagew->save();
}

```

There are a few questions near to this one actually, but none of them addresses this precisely. This one for example is a very good explanation of the mechanism but its suggestion it not use.

Here, one should not use $nodew-\>save(), because it causes infinite loop. I also played a little with module weight, that does not help either.

I also tried to change another entity reference field. No use.

I don't want to go with `field_attach_update()` because it is old-fashioned.

# Answer
> 0 votes
The method you are using the save the field isn't *ideal*.
For setting the field values you should use the set() function provided by the `EntityMetadataWrapper` class.

```
function mymodule_node_insert($node) {
  if (!_is_dynamic_type($node->type))
    return;

  $messagew = entity_metadata_wrapper('message', message_create('post', array('uid' => $node->uid)));

  //copy terms
  $nodew = entity_metadata_wrapper('node', $node);
  //below loads a full taxonomy term
  $nodew->field_hidden_type = taxonomy_term_machine_name_load('event', 'hidden_type');

  $messagew->field_hidden_type->set($nodew->field_hidden_type->value());
  $messagew->save();
}

```

On a side note, I see that there is not check on the node type, or any other parameters in the implementation of `hook_node_insert`. Note that it will get triggered **every time a node of *any* content type is created**.

---
Tags: 7, entities, hooks
---


title: Problems with logging out users

text:
# Question
Title: Problems with logging out users
I was running through some tests on my site with a client, and I was logged in as a normal authenticated user. I then logged out with the intention of logging back in as the superadmin (uid -\> 1).

I navigated to a node page where there was a login form, and the site automatically logged me in as the authenticated user that I was logged in as previously.

Do you have any ideas of what could be causing this? The page that where this auto-login occurred reads off of a custom node.tpl file and I've got a few `user_load()` calls in that code.

# Answer
If you are also using the global $user object in your code, doing something like $user=user\_load($node-\>uid) can 'log you in'. This is a security issue and should be corrected.
> 1 votes

# Answer
It sounds like you have a global `$user` object that you are then overwriting.

The problem code would look something like:

```
global $user;
$user = user_load($new_user_id);

```

Search though all of your code for any occurrences of `user_load()` to locate the problem line.

For safety I usually use copy the global `$user` to an `$account` object so I can be user nothing will change the global `$user`.

For example:

```
global $user;
$account = $user;

// Do stuff with $account safe in the knowledge that even if I
// accidentally change it it won't effect the global $user object

```
> 1 votes

# Answer
I would advise to check caching settings. If you have multiple `user_load()` calls in page.tpl, and still get previous version of the page, that's a sign of page.tpl not being called at all. So, first of all, check that you don't have aggressive caching/wrong boost settings
> 0 votes

# Answer
Are you using some browser plugin to store login information like Lastpass? Maybe it automatically sign you in everytime you are trying to access the login page. Did you clear your browser cookies? I was in the same problem before but I found out that my plugin(Lastpass) was the root cause of my problem. Try to browse in incognito or use other browser.
> 0 votes

# Answer
Something like this has happened to me before. There was a case of checking whether the current user is the admin. Instead of checking of equality

```
if($user->uid==1){
    // put code here
}

```

I did assignement

```
if($user->uid==1){
    // put code here
}

```
> 0 votes

---
Tags: 6, users, sessions
---


# Question
Title: Add placeholder or default value to captcha text field
There is a webform in my website, I added the captcha to this webform using this code:

```
function THEME_form_alter(&$form, $form_state, $form_id) {
    if (strstr($form_id, 'webform_client_form')) {
        $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'image_captcha/Image',
        );
    }
}

```

This works fine. I need to insert a placeholder or default the text field of the image. I mean in the following picture :

the `What code is in the image?` should move inside the text field. How do I can do this?

Even though it is possible to make this done using javscript but I need to make this done using form alter.

Thanks

# Answer
> 2 votes
you can use this module too:

https://www.drupal.org/project/form\_placeholder

it worked for me very nice

# Answer
> 1 votes
Use an `#after_build` form element to drop the placeholder attribute into the form:

```
function THEME_form_alter(&$form, $form_state, $form_id) {
    if (strstr($form_id, 'webform_client_form')) {
        $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'image_captcha/Image',
        );
        $form['#after_build'][] = 'THEME_captcha_alter';
    }
}
function THEME_captcha_alter($form, &$form_state) {
  $form['my_captcha_element']['captcha_widgets']['captcha_response']['#attributes'] = array('placeholder' => 'My Placeholder');
  return $form;
}

```

---
Tags: 7, forms, webforms, captcha
---


# Question
Title: Access Denied when Menu CallBack Function is Called
I am trying to call a function after the user clicks on an ajaxified link below.

```
$form['link'] = array(
  '#type' => 'item',
  '#markup' => l(t($record->studid),'myid_print/callback', array('attributes' => array('class' => 'use-ajax'))),
);

```

Below is my hook\_menu function:

```
function myid_print_menu()
{
    $items = array();
    $items['myid_print/callback'] = array(
        'page callback' => 'myid_print_user_page_callback',
        'access callback'    => 'myid_print_user_access',
        'file' => 'myid_print.pages.inc',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function myid_print_user_access()
{
    return TRUE;
}

```

myid\_print.pages.inc file:

```
function myid_print_user_page_callback()
{
    return 'Successful';
}

```

The above code throws the error below:

Where am I missing?

# Answer
I tried uninstalling my Jquery Update Module and suddenly the error disappears. I don't know why it works. Still thankful though.
> 0 votes

# Answer
Your AJAX request is calling the path **/drupal-7.34/myid\_print/callback** on the server. The path registered on your Drupal instance (assuming you're running under the drupal-7.34 directory) is **/drupal-7.34/print/callback**. Hence, the error you're seeing.

If you want to pass an argument to your print callback, you should do this.

```
$items['print/%/callback'] = array(
    'page callback' => 'print_user_page_callback',
    'page arguments' => array(1),
    'access callback'    => 'print_user_access',
    'file' => 'print.pages.inc',
    'type' => MENU_CALLBACK,
);

function print_user_page_callback($id)
{
    return 'Successful printing '.$id;
}

```

Read more on hook\_menu() if you'd like to understand more how module's can register paths.
> 0 votes

---
Tags: forms, users, ajax
---


# Question
Title: What is your way to add images into panels - simple and fast?
How can you upload images into panels simply and fast? That's all I need - images in panels, simple and fast. thanks.

# Answer
> 1 votes
Using CKEditor with CKFinder:

1. On pane gear menu click add content
2. Choose 'New custom content'
3. In the body field use the image button to either find an existing image on the server or upload a new one.

CKFinder requires a licence, it's pretty cheap.

# Answer
> 1 votes
You can also try to use CKEditor \+ Asset

---
Tags: media, panels, files
---


# Question
Title: How to pass multiple target_id/values field using entity reference prepopulate?
I read the documentation and saw that this is possible: `node/add/page?field_bar=1,2,3`

But how do you code this? I wanted to pass multiple target id, not just one.

I tried this code but this only passes 1 value which is the first field value.

```
<?php
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' =>$node->field_product_food['und'][0]['target_id'])  ));
echo $l;
?>

```

I also tried using an array loop like this:

```
<?php
$nids = array();
foreach ($node->field_product_food[$node->language] as $index => $item) {
$nids[] = $item['target_id'];
}
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' =>$nids)  ));
echo $l;
?>

```

but the result is not like the example from the documentation.

Can somebody help me?

Thank you very much!

# Answer
> 2 votes
So if you want to create this link: `node/add/page?field_bar=1,2,3`

You need to put a comma between each nid, so implode() is what you want.

E.g.

```
$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' => implode(',', $nids))  ));

```

---
Tags: entities
---


title: Removing Unwanted CSS

text:
# Question
Title: Removing Unwanted CSS
I have removed default css files using a code below, but still it is showing some unwanted css files

```
<?php
function _phptemplate_variables($hook, $vars)
{
 $css = drupal_add_css();
 unset($css['all']['module']['modules/system/system.css']);
 unset($css['all']['module']['modules/system/defaults.css']);
 $vars['styles'] = drupal_get_css($css);
 return $vars;
}
?>

```

In firebug GOw.css is appearing I dont know from where, can anybody please tell me how can I resolve this?

# Answer
> 0 votes
To find where a specific stylesheet is coming from, scan your Drupal directory for that file's name. This is the easiest way to find it.

To disable a stylesheet, you can either use preprocess hook, or add the following to your theme's `.info` file:

```
stylesheets[all][] = css/removed/GOw.css

```

Just make sure that the file does not exist, and Drupal won't include it.

Hope this helps.

---
Tags: 7, theming
---


# Question
Title: How to change the link in the view by content type?
I change my question. Content type: How to add link field?

# Answer
yes you can add the Link field by add a module called link module which will add a type called link in the add field drop down. for that you will need to install Link module

Hope this will help :)
> 1 votes

---
Tags: views, nodes
---


# Question
Title: Search API Attachments Facet returning part words
I’m using these modules for the search : Search API attachments; Search API Attachments Field Collections; Solr search; Search Facets

One of the Fields I’m searching is from attachments and I’m using type ‘Fulltext’ .

Then when setting up a Facet for this field it return a whole heap of the most common keywords. The only problem being that in some cases it's returning part words. For example in the attachments the words 'manage' 'management' 'manager' would exist, and the Facet is returning 'manag' as my keyword. Has anyone else come across this; and do you know how I can make it so that only whole words are returned.

Thanks

# Answer
Before I go into to how I solved this; its worth repeating what feed back of this from our hosts. 'This will happen if you attempt to create a facet for a Solr field of type "text" (which might be the case here), because Solr stems and further processes all words before storing them on the index. There is no direct way to get around this.

Also, faceting on text is not really recommended:

UX-wise, searchers get too much noise, because words come from all over the place--your top facets could be just common words like 'the', 'with', 'you', 'they', etc.

Performance-wise, calculating the facets to show for large fields takes a long time. '

I have got things looking like how I want them though and that was to use 'Facet API BONUS' module.

1. Install and Enable Module
2. Configuration \> Search and metadata \> Exclude specified items \> Add to Exclude items

> Save Configuration

You only get a limited amount of words with this module . If needed this can be changed by extending the Form in

Facetapi\>filter\_exclude\_specified\_items . class FacetapiFilterExcludeItems::settingsForm

And adding a '#maxlength'

This is a pretty good blog on adding how to other extended functionality changes to the Facet API module http://www.trellon.com/content/blog/apachesolr-and-facetapi
> 0 votes

---
Tags: search
---


# Question
Title: How can I add products to cart programmatically?
I have a form adding an item to the basket in the form of a table `n x m` where `n` and `m` are taxonomy terms of two different taxonomies ('*type of the insert*' and '*insert size*').

In each cell the user can enter the number of items, with the n-th '*type of the insert*' and m-th '*size*'.

Form I create myself in the template-based taxonomy vocabularies. How can I add products to cart programmatically?

# Answer
> 4 votes
To add particular product id you have your product id and current user id you can easily do. Send the Product id and user id to this function this will add your product to the user cart.

This is the custom function used. The main part here is the `commerce_product_line_item_new()` and `commerce_cart_product_add()` this will add the product to that particular user cart.

```
function add_product_to_cart($pid,$uid=0){
    global $user;
    $uid = isset($uid) && !empty($uid) ? $uid : $user->uid;
    $line_item = commerce_product_line_item_new(commerce_product_load($pid));
    commerce_cart_product_add($uid, $line_item);
}

```

Hope this will help :)

---
Tags: forms
---


# Question
Title: Need to add filter with more than one word in view filter criteria Drupal7
I need to add one filter that can take more than one word for searching. Right now i selected "contains" option in Operator for filter criteria. ie i need search string like this: title=word1 or word2…

So in this case what should be my search url: search-page?title=word1 word2

# Answer
I am not sure if this is what you want.
> 0 votes

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


# Question
Title: How to remove a value from URL parameter?
I'm using entity reference prepopulate and views. On the start of my node add form I'm using views to display some products and I have created a PHP button to pass the nid of those products to the URL. Here is the code:

```
<?php
$url = token_replace('[current-page:url]');
$l = l( t('SELECT THIS VENUE'), $url,  array('query' => array('field_product_venue' =>$row->nid )  ));
echo $l;
?>

```

And on the last part of my node add form the user can see the summary of all the products he or she has chosen but he or she must also have the ability to remove those items, since the form gets its selected products from the url I want to create a button that deletes that specific product (nid) from the URL.

Any help would be greatly appreciated.

# Answer
You need to get the value of the parameter, then check if the parameter contains the nid, then replace/remove the nid on your parameter from your url.

Use this code on your Views: PHP

```
<?php
$url = token_replace('[current-page:url]');
$venue =$_GET['field_product_venue'];
if (strpos($venue, $row->nid) !== false) {
$change= str_replace($row->nid .',', '', $venue);
$l = l( t('DELETE'), $url,  array('query' => array('field_product_venue'=>$change)  ));
echo $l;
}
?>

```
> 0 votes

---
Tags: entities
---


# Question
Title: How to add css classes to modal forms module
**My Problem**

I'm trying add CSS classes to help me style the modal forms created using the Modal Forms module.

I have a User Login and a User Register form at the moment, but they have no form specific CSS classes.

**Example 1**

To style the height of the input boxes:

I either have to use "form-text" in `<input>` which will edit all form inputs across all forms or "edit-name" which will become "edit-name--1" if the user fails to login and the break the css.

```
<div class="form-item form-type-textfield form-item-name">
    <input id="edit-name" class="form-text required"
    type="text" maxlength="60" size="25" value="" name="name">
</div>

```

**Example 2**

To alter the labels "username & password" the only tag I can work with is `edit-pass`

```
<div class="form-item form-type-password form-item-pass">
    <label for="edit-pass">
    ...
</div>

```

Which will change `edit-pass--x` every time they fail to complete the form correctly, resetting the css.

How would I insert CSS classes using hook form alter?

**What I've tried**

I printed out the array for the user login form (using print\_r, can't use dpm because have to be logged in and user login won't work if you're logged in), here's the first chunk of it.

```
Array ( [name] => Array ( [#type] => textfield
                          [#title] => Username
                          [#size] => 25
                          [#maxlength] => 60
                          [#required] => 1
                          [#description] => Enter your drupaltest2 username. )

        [pass] => Array ( [#type] => password
                          [#title] => Password
                          [#description] => Enter the password that accompanies your username.
                          [#required] => 1 [#size] => 25 )

        [#validate] => Array ( [0] => user_login_name_validate
                               [1] => user_login_authenticate_validate
                               [2] => user_login_final_validate )

        [actions] => Array ( [#type] => actions
                             [submit] => Array ( [#type] => submit
                                                 [#value] => Log in ) )

```

I tried inserting

```
[#class] => 'TEST';

```

into `[name]` and other slight variations but none of them work. I can give more examples if I've explained this badly.

**EDIT -- RajeevK Solution -- Not enough granularity**

I added the following lines into my alter form:

Name array:

```
$form['name'][#prefix] = '<div class = "usernamelogin">';
$form['name'][#sufix] = '</div>';

```

Pass array:

```
$form['name'][#prefix] = '<div class = "CAPTAINTEST">';
$form['name'][#sufix] = '</div>';

```

And the end results looks like this:

This is what the page looks like (I'm using firebug to show what the div contains).

Or if I select CAPTAINTEST it looks like:

Hopefully this will help some though and cheers to RajeevK for the suggestion. I was hoping to control individual elements of the forms, does anyone know whether it would be possible to get more granularity without having to hack the module?

(Here's my form alter:

```
function mytheme_form_user_login_alter(&$form, &$form_state, $form_id) {
  //override to change text in user sign in box
  drupal_set_title('');
  $form['name']['#title'] = 'Username/Email';
  $form['name']['#description'] = '';
  $form['name']['#prefix'] = '<div class = "usernamelogin">';
  $form['name']['#sufix'] = '</div>';
  $form['pass']['#description'] = '';
  $form['pass']['#prefix'] = '<div class = "CAPTAINTEST">';
  $form['pass']['#sufix'] = '</div>';
  $form['actions']['submit']['#value'] = 'Sign In.';

```

# Answer
> 1 votes
You can use #attributes to add some classes to the elements:

```
$form['name']['#attributes'] = array('class' => array('your-class'));

```

Will output something like this (class added to input element):

```
<div class="form-item form-type-textfield form-item-name">
  <label for="edit-name">Username <span title="This field is required." class="form-required">*</span></label>
  <input type="text" maxlength="60" size="60" value="" name="name" id="edit-name" class="your-class form-text required">
  ...
</div>

```

# Answer
> 0 votes
You can use `#prefix` and `#sufix` for a form field to add class or ID of your wish. You can try something like this if you are altering user login form --

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace MYMODULE with your module name
  if($form['#id'] == 'user-login'){
    $form['name'][#prefix] = '<div class = "my-class-login">';
    $form['name'][#sufix] = '</div>';
  }
}

```

Though I haven't tested this code but it should work. Inform me whether its working or not.

# Answer
> 0 votes
Maybe I am missing something here, considering all the preprocessing and all, but rarely drupal gives you not enough granularity for styling css as it creates so many elements to choose from. Consider this CSS without adding classes, pick some when going down the stairs of containing elements:

```
.popups-container #modal-content #user-login .form-item-name label {
  CSS
}
.popups-container #modal-content #user-login .form-item-name .form-text {
  CSS
}

```

I know this is not an answer to your specific question (adding classes), but I think it is a simpler solution for the problem you have here (styling individual elements).

# Answer
> 0 votes
You can use patch to add class containing the "modal style" to modal window.

> With several modals, we have the need for different styling of each. Currently, the CTools Modal does not add any CSS classes to the modal container.
> We have added this to modal.js and it works for us.

---
Tags: 7, forms, theming, javascript
---


# Question
Title: Adding a new column to users table: db_drop_field errror
I'm trying to add a column to the 'users' table. When I install my module, the column gets created and when I uninstall it gets deleted.

The issue is that after I uninstalled, I run a 'drush cc all' and I receive this error:

> WD php: PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown\[error\] column 'base.firstname' in 'field list': SELECT base.uid AS uid, base.name AS name, base.pass AS pass, base.mail AS mail, base.theme AS theme, base.signature AS signature, base.signature\_format AS signature\_format, base.created AS created, base.access AS access, base.login AS login, base.status AS status, base.timezone AS timezone, base.language AS language, base.picture AS picture, base.init AS init, base.data AS data, base.firstname AS firstname FROM {users} base WHERE (base.uid IN (:db\_condition\_placeholder\_0)) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 0 ) in DrupalDefaultEntityController-\>load() (line 193 of /var/www/includes/entity.inc).

Here is my code inside the .install:

```
function mymodule_schema_alter(&$schema) {
  $schema['users']['fields']['firstname'] = array(
    'type' => 'varchar',
    'length' => 60,
    'not null' => FALSE,
    'default' => '',
    'description' => 'Field added by profile common module',
  );
}

function  mymodule_install() {
  $schema = drupal_get_schema('users');
  db_add_field('users', 'firstname', $schema['fields']['firstname']);
}

function  mymodule_uninstall() {
  db_drop_field('users', 'firstname');
}

```

Thanks.

# Answer
> 0 votes
There is the difference between `hook_schema()` and `hook_schema_alter()`: The first is used to create a database table when a module is installed, but the second is not used to alter an existing database table when a module is installed. `hook_schema_alter()` is used to alter the values returned from `hook_schema()` to let other modules know an existing database table (created from a module) has been altered (from another module).

What you need to to is:

* Implement `hook_schema_alter()` to make public the changes you made to a database table created from another module
* Make the changes in that database table, in `hook_install()` or `hook_update_N()`

The reason you need to alter what returned from `hook_schema()` is that there are functions that write on the database which use the information returned from `hook_schema()`, in primis `drupal_write_record()`.

```
  $schema = drupal_get_schema($table);
  if (empty($schema)) {
    return FALSE;
  }

  $object = (object) $record;
  $fields = array();

  // Go through the schema to determine fields to write.
  foreach ($schema ['fields'] as $field => $info) {
    if ($info ['type'] == 'serial') {
      // Skip serial types if we are updating.
      if (!empty($primary_keys)) {
        continue;
      }
      // Track serial field so we can helpfully populate them after the query.
      // NOTE: Each table should come with one serial field only.
      $serial = $field;
    }

    // …
  }

```

Without `hook_schema_alter()`, which is invoked from `drupal_get_schema()`, such functions would not be able to correctly write on the database tables.

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


title: Right way to translate view Titles?

text:
# Question
Title: Right way to translate view Titles?
As far as I see the view titles are not translatable. As a quick fix I just created a new `views-view.tpl.php` file and changed the line 32 from:

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

```

to

```
<?php print t($title); ?>

```

What do you think? Is this a right method?

# Answer
> 3 votes
The proper way to use `t()` with a non-literal is to pass in the string as a replacement like so:

```
<?php print t('@title', array('@title' => $title)); ?>

```

The function comments on `t()` contain a very descriptive explanation of why this is necessary so I won't re-hash it here.

# Answer
> 16 votes
I find existing answers rather confusing.

Views (as we know) is extremely cool module. It supports localization plugins. Go to page `admin/structure/views/settings/advanced` to see for yourself:

1. Preferred way to translate Views is to use Internationalization Views module which depends on i18n\_string (i18n package) module.
**How to use?** Just enable Internationalization Views and go to translate page for your view.
You also may be interested in i18n\_string settings here: `admin/config/regional/i18n/strings`.
2. Core localization plugin just do `t()` for Views titles, headers, footers etc. It's not so flexible and secure, but as a developer you can choose this method in some cases.
**How to use?** Nothing special here. Your strings will appear in Drupal translate interface after the first request.

You can disable localisation at all or create your own plugin if you need.

# Answer
> 2 votes
Indeed that would not be the the right way to do it. You need to install "Entity Translation", "Internationalization" and "Internationalization Views" modules for doing this. Once you are through with the installation and configuration of these modules, then you can not only translate the title of the views but also the fields in your views as well. Though you will be required to specify the translated strings in the translation interface. Do let me know if you face issues in any of these modules.

# Answer
> 1 votes
There is another way to translate "Views" which makes sometimes sense. Have a look at the Viewfield Module. This allows you to embed a view on a node. So you could basically create a content type with some fields and this Viewfield.

Then create a node, choose a view (i recommend to create blocks) and save it. Then translate the node with the usual i18n tools and translate the title and all the other fields you created on this node.

# Answer
> 1 votes
I think the right, standard and easy way to translate view title is to install Internationalization views which use Entity type of translation which is newer type of translation in Drupal. I verified it worked well for this purpose. I hope it would be possible translate also view path in future.

# Answer
> 1 votes
I've been using entity translation and replaced the title field to0. In a view you need to change the title fields to "Entity translation: Title: translated"

# Answer
> 1 votes
May be a tricky way

What I'm doing is by going to Intarface translation (admin/config/regional/translate/translate)-\> searching the view title -\>Translating as I need Then I edit the view, I click for example on path option and then apply button to get the save's button one.

After saving , the translation will be shown.

---
Tags: views, theming
---


# Question
Title: Is there a non-WYSIWYG-module that lets me use Media ver. 2 images with multiple image styles?
I have a library of images that I access for reuse via the Media (ver. 2.0) Browser and attach to nodes using the file field. When I use an image inside a node, I want to indicate a specific Image Style (e.g. "Thumbnail", "Medium", etc.). The out of the box setup of D7 let me specify *one* (1) image style to be used for a field in each display mode (i.e. "Default" and "Teaser"). I want to be able to choose between image styles.

I may want to use the "Medium" style for the first image field in one node, and "Large" in for the first field in another.

After some googling, I've found some suggestions for doing this, but they're all based upon using WYSIWYG for image insertion, and I don't want WYSIWYG.

Looking at the answer to Multiple image styles, I see that I can do get access to different image cache versions of an image through either template file or hook\_preprocess\_node() - so I should probably be able to do this with a custom module that manipulates the image field render object during preprocessing.

However, before I embark upon writing such a custom module, I want to ask if this module (or something similar to it) already exists? I have searched for it, but so far found nothing that does not use WYSIWYG.

# Answer
> 0 votes
As I can see Entity Image Style can be used with the Field collection module to achieve this task. However the Entity Image Style module is not yet a stable module. As per the logic this should achieve your goal.

Other resources: Formatter Field module

---
Tags: 7, media
---


# Question
Title: Bulk Delete Custom Entities (Not Entity Types)
I have a 5000+ entries for custom Entities created by the RedHen module (https://drupal.org/project/redhen). I want to wipe them completely from the system (they are all test entries). How can I do this quickly? I tried to get Views Bulk Operations and the Delete All modules but neither seem to be picking up the custom entities.

# Answer
> 1 votes
You can delete multiple entities using below API functions

entity\_load

> Load entities from the database.
>
> The entities are stored in a static memory cache, and will not require database access if loaded again during the same page request.
>
> $entity\_type: The entity type to load, e.g. node or user.
>
> $ids: An array of entity IDs, or FALSE to load all entities.

entity\_delete\_multiple

> Permanently delete multiple entities.

For Example to delete all node entities

```
<?php
  $results = entity_load('node');
  $entity_ids = array_keys($results);
  entity_delete_multiple('node', $entity_ids);
  ?>

```

# Answer
> 1 votes
This simple module might help you: https://www.drupal.org/project/entity\_bulk\_delete

---
Tags: 7, entities, batch-operations
---


# Question
Title: Should user input be able to cause an unhandled exception?
Drupal 7's user login form (and I dare say others) can be tampered with client-side, to cause Drupal to throw an unhandled exception.

All you need to do is change the input fields, appending `[]` to the name of the name field, and Drupal will create invalid SQL and throw that at the database.

Is this considered a problem? Surely it's Drupal's job to ensure user input is sanitised to the point that it won't generate invalid SQL - is it a DOS risk/security issue?

e.g. Visit drupal.org's login page. Open firebug. Change the `<input name="name".../>` to `<input name="name[]" .../>` and add another one just like it. Put some values in both name fields and the password and submit. You get the "This website has encountered an error." page of death.

(I can vouch for this under Drupal 7.35, and on drupal.org which I presume is 7.36)

...

# Answer
> 2 votes
No, user input shoulnd't cause and unhandled exception. Not only because is a nasty reponse form server but it reveals an error condition not handled so it may head to security issues. A non-handled error means that developers are not aware of that error (or they are too lazy, what may be worst).

All error conditions should be handled to minimize problems related to that uncontrolled error.

I've tried to reproduce the bug (with two input name fields with `name="name[]"` as you have shown in your images) without getting reported error. So I think this particular case you mention seems to be a drupal.org bug or a module bug of a module used in the Drupal site. You can report the bug in the Drupal.org infrastructure issue queue

---
Tags: 7, security
---


# Question
Title: Drupal 7 Faceted Search: Always show Facets
I have a faceted search working that uses searchapi, facetapi, and entityapi. I was not the one who developed this, but I have some experience with Drupal. As of now the navigation uses links for selection and looks like below (first level of bullet points aren't links). When mixing is selected sound design and composition disappear as expected.

**What the client wants is for all items to still stay visible and selectable as the user drills down (even if it returns nothing). Only one item per category will be selectable at a time, but the user should be able to do it without having to 'go back'.**
Any advice is greatly appreciated.

* What We Do\_
    + Mixing (18)
    + Sound Design(11)
    + Composition (6)
* Who We Are\_
    + Joe Schmoe (17)
    + Jeff Bleck (14)
    + David Berry (4)
* Affiliated Composers\_
    + Jim Carey (3)
    + Tony Maroni (2)

# Answer
Under `admin/config/search/search_api` click “edit” on your search index and select “Facets”. Then for all facets that need the described behavior for their items, follow these steps:

1. Click “configure display”.
2. In the “Global settings” section, change the “Minimum facet count” to `0` (zero). Arguably this input field should rather be called “Minimum facet item count” …
3. “Save configuration”.

Now all non-matching facet items should remain in your facet list (with a zero count). As you have already mentioned, clicking such a facet item will return no search results anymore.
> 8 votes

# Answer
I think the solution in this comment is the solution to your problem. In your template.php, overwrite the `theme_facetapi_link_inactive`-function:

```
function theme_facetapi_link_inactive($variables) {
  // Builds accessible markup.
  $accessible_vars = array(
    'text' => $variables['text'],
    'active' => FALSE,
  );
  $accessible_markup = theme('facetapi_accessible_markup', $accessible_vars);

  // Sanitizes the link text if necessary.
  $sanitize = empty($variables['options']['html']);
  $variables['text'] = ($sanitize) ? check_plain($variables['text']) : $variables['text'];

  // Adds count to link if one was passed.
  if (isset($variables['count'])) {
    $variables['text'] .= ' ' . theme('facetapi_count', $variables);
  }

  // Add functionality requested in #1669600.
  if (!$variables['count'] && isset($variables['options']['query']['f'])) {
    // We should be getting this from the url processor plugin, however we are
    // making an assumption since this is in our custom theme.
    $params = &$variables['options']['query']['f'];

    // Capture the filter associated with this link and find the field alias.
    $filter = end($params);
    $field_alias = substr($filter, 0, strpos($filter, ':')) . ':';

    // Iterate over params and strip out items that are using the same field
    // alias as this filter. Do not strip out this filter.
    foreach ($params as $key => $param) {
      if (0 === strpos($param, $field_alias) && $param != $filter) {
        unset($params[$key]);
      }
    }
  }

  // Resets link text, sets to options to HTML since we already sanitized the
  // link text and are providing additional markup for accessibility.
  $variables['text'] .= $accessible_markup;
  $variables['options']['html'] = TRUE;
  return theme_link($variables);
}

```
> 1 votes

# Answer
Here is my work arround for this problem, no coding required!

* create a view based on your search index
* add a facets block to the view and configure it to use the facet field you want, if you have a taxonomy tree, you can use the all parents term field to only show the toplevel.
* configure the block so it is displayed on your site

now you have also the other facet blocks everwhere because the search is activated, if you want you can hide the created block with css.

grts

frederic wbase
> 0 votes

# Answer
To ensure that **all items** remain visible and selectable, make sure that the Global Settings search is set to "OR". From the admin menu, go to Configuration \> Search API \> \[name of index\] "edit" link \> Facets (tab) \> \[name of facet\] "configure display" link \> Under "Global Settings", select Operator "OR". (Keep "Minimum Facet Count" at 1)

To ensure that all **facet blocks** remain visible, make sure that on each facet block's configuration page that facets are shown on the specified pages. Go to Structure \> Blocks \> \[name of facet block\] "configure" link. For example:

services
services/\*

Users are able to drill down. Without going back, users would just need to deselect a facet item. The option " Limit to one active item" currently does not work well when configured, based on my experiences.
> 0 votes

---
Tags: 7, entities, search
---


title: Webmail Error due to Emoji

text:
# Question
Title: Webmail Error due to Emoji
A site I'm working on came across the following error in Drupal based on the addition of an emoji flex graphic put into the form field.

```
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: ‘\xF0\x9F\x92\xAA e…’ for column ‘data’ at row 1: INSERT INTO {webform_submitted_data} (mid, sid, cid, no, data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder3, :db_insert_placeholder_4);
     Array ([:db_insert_placeholder_0] => 64
    [:db_insert_placeholder_1] => 10
    [:db_insert_placeholder_2] => 11
    [:db_insert_placeholder_3] => 0
    [:db_insert_placeholder_4] => Need multiple 250 ton Jacks, force not strong [AndroidFlexEmoji] enough) in drupal_write_record() (line 7239 of E:\webserver\Inetpub\wwwroot\includes\common.inc).

```

After digging around for a while on this site and others, I came across the following suggestion:

\[mysqld\] character-set-server = utf8mb4 collation-server = utf8mb4\_unicode\_ci

I'm not 100% sure if this will fix the issue I'm having, however, I'm not sure where to alter this to test it. The link below states that in Drupal you can find it under /includes/database/mysql/database.inc around line 53 but no luck.

Reference link: How can I remove emoji from all user input? Any clarification would be great.

# Answer
While the other issues weren't able to resolve the issue, I was able to work around the problem by installing a module called, WebForm Validation to correct the issue. The way I did this was by creating a validation rule that was part of a "blacklist" of content that would be unacceptable in the form, then checked the box to reverse the rule so that it would be negated should the form contain anything not found in that previously created list. This list contained all my standard alphanumeric needs and punctuation. Not the ideal fix, however, it does do the job in a pinch.
> 0 votes

# Answer
1. *Do not* hack the core (change any of the files in the initial Drupal download) unless you are using a patch in the issues queue or making one for a registered issue, `/includes` is part of that core.

The reason for this is that you will not be able to reliably upgrade your Drupal site as new versions are released and it is very important to keep it updated for security reasons.

2. *Do* always test new things on a development copy of your site, never on your production site (at least not after launch).

That being said, the best part of the answer you referenced is:

> All in all, I would prefer to just switch my MySQL to utf8mb4 charset, that supports all utf8 as it ought to be supported. You need MySQL 5.5.3 or greater to do this.

To elaborate:

MySQL allows various different encodings in its storage engine. Latin1 (often the default) stores all of the data in one way and allows a limited set of characters. UTF8 is a much larger library of characters. Characters that exist in UTF8 that don't exist in Latin1 (for example) will make your database cry because it doesn't know how to read them.

The solution is to tell your database to use UTF8 instead of Latin1.

There are instructions online for doing this in-place but I personally prefer to do a mysqldump and import the database into a fresh database that has been specifically set to use UTF8, then tell Drupal where to find the new database.

As Molot said in his answer, you need MySQL 5.5.3 or higher to use UTF8, so you may need to upgrade your version of MySQL. If you're on shared hosting this could be difficult, you should be able to see your MySQL version in CPanel or Plesk, otherwise ask your hosting provider for support.
> 0 votes

---
Tags: webforms
---


title: Drupal custom tabular View

text:
# Question
Title: Drupal custom tabular View
Use Case: I have two differnent Content Types, A and B, each with a taxonomy fields 'State'.

Content Type A has two nodes, with `California` and `South Dakota` selected.

Content Type B has two nodes, with `Alabama` selected in both nodes.

The requirement is to created a tabular View that would look like this:

So within the Views interface, how do I create this?

http://filedb.experts-exchange.com/incoming/2015/04\_w17/909525/view.jpg

# Answer
I think the Views Aggregator Plus module can be of help. Among others it has possibilities to tally and enumerate views fields, so I think you can make the summary table you're asking for.

The module description is as follows:

> In addition to what Views and Views Calc do, this module:
>
> * enumerates group members
> * produces tallies, i.e. textual histograms
> * aggregates on Views PHP code-snippet evalutations
> * can filter out result rows on regexp patterns
> * gives you sorting on Views' Math expressions
> * can process Webform submissions
> * lets you add your own custom aggregation functions
>
> ... and it puts summary statistics at the bottom of your aggregated table as well!
> 0 votes

---
Tags: views
---