title: How to add Views name to body class?

text:
# Question
Title: How to add Views name to body class?
At moment Drupal add css class `page-VIEWPATH` to the body tag. How can I add css class `page-VIEWNAME` to the body tag without third party module or JQuery?

Thank you in advance!

# Answer
It turns out, this can be done with a combination of `hook_preprocess_html` and `function views_get_page_view` to get a true `<body>` class for a given view and display (see the API page).

So wrapping it up within the `hook_preprocess_html` context, it would look something like this:

```
/**
 * Implements template_preprocess_html().
 *
 * Misc page preprocess functions.
 */
function mytheme_preprocess_html(&$vars) {

// Query the view and add a class
$view = views_get_page_view();
 if (
  isset($view) &&
  $view->name == 'actions' &&
  $view->current_display == "page"
) {
    $vars['classes_array'][] = 'views-actions-page';
  }
}

```

So above, I query the view name and display and the key is `$view = views_get_page_view();`. This works great for custom Views body classes per view and display.

The rendered HTML result is something like this:

```
<body class="html not-front logged-in no-sidebars
page-actions section-actions page-views flush-header views-actions-page">

```

\** `views-actions-page` is the class that we added with the function above.

It should be noted that the advantage of this vs. using views generated classes are that if the URL of the page changes, your custom Views class will not whereas `page-actions section-actions` would change based on the URL. So using those classes could be unreliable if they are used for theming as it would have a negative ripple effect.
> 6 votes

# Answer
Use the following function in `template.php` of your theme folder

```
function THEME_preprocess_views_view(&$variables){
    $view = $variables['view'];
    if($view->name == "YOUR_VIEW_NAME" && $view->current_display == "MACHINE_NAME_OF_VIEW"){
        $variables['classes_array'][]="page-".$view->name;
    }
}

```

you can also set some other conditions like `current_path` or anything else you want.
> 3 votes

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


# Question
Title: How to rearrange the user registration form fields
I want to **Rearrange** and **Rename** the default fields with added fields on user registration form in drupal7 site, I could rearrange only the fields which is added by me but i want to rearrange combining both the default and added one. can anyone help on this.!

# Answer
Fields can be rearrange by changing `'#weight'` attribute of field in `hook_form_alter()`. You will have to create a custom module and have to alter the form and its element. The associative array would be something like this

```
$form['account']['name']['#weight'] = 7;

```
> 4 votes

# Answer
Implement `hook_form_user_register_form_alter()`. You can rearrange the `$form` array that is passed to this hook by adjusting the weights and titles.
> 4 votes

# Answer
The easy way, without any editing of configuration files is to just change the order of the fields in /admin/config/people/accounts/fields

Clear your caches and it's done.
> 1 votes

---
Tags: users
---


# Question
Title: Accessing the cell phone camera to populate the profile picture field
I have a mobile website, and I thought it would be cool if there were a way for the user to take a picture with their phones camera to populate the field rather than have them go and upload a picture they have on their phone, similarly to the way used from some websites to access the computer's webcam to let you take pictures.

I'm not sure if this is even possible to do from within a web browser on a phone. I've seen Flash soultions that access the webcam of a computer via the browser, would any of those solutions work for Drupal?

# Answer
> 2 votes
Agreed this is not purely a Drupal question but not unrelated, a little searching got me a really good answer on HTML5 Rocks taking you through the history and methods.

Specifically go to the section on getUserMedia(), there are even examples on the page that let you test it on your browser.

To my knowledge and from my searching I have not seen any Drupal module making use of this, but there is a discussion thread on drupal.org looking into this.

# Answer
> 2 votes
It's possible - I just did it! I used this sandbox module https://www.drupal.org/sandbox/cafuego/1980210 and Drupal core's image selector (didn't work with Media browser) and was able to:

1. click the button to add a file - and my phone gave me three options, one being to take a new photo
2. take the picture with my phone's camera
3. upload it and save.

It worked!

Using a new Samsung Galaxy Note 4 and whatever version of Android came installed on it.

# Answer
> 1 votes
I think this is only possible via native applications. Only then you can request for permission to use camera. Although PhoneGap might be solution for this, I would not recommend it, and user will still have to download the application first.

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


# Question
Title: Get an Error with rendered page content in custom template file
The code below works, but when I try to add the line in my MYMODULE-page.tpl.php the content is rendered twice with some errors. For example the $title is printed, but i get an error message that the $title is not set and when I add some test text in the template file i get it also twice. I didn\`t find any solution for this.

\**** EDIT \****

```
function MYMODULE_theme() {
  return array(
    'page-MYMODULE' => array (
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
      'template' => 'page-MYMODULE',
      'render element' => 'page',
    ),
    'content-MYMODULE' => array (
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
      'template' => 'content-MYMODULE',
      'render element' => 'page',
      'variables' => array (
        'title' => NULL,
        'path' => NULL,
      ),
    ),
  );
}

function MYMODULE_preprocess_page(&$variables, $hook) {
  if (arg(0) == 'MYMODULE') {
    $variables['theme_hook_suggestions'][] = 'page-MYMODULE'; //underscores doesn't work for me
  };
}

function MYMODULE_menu() {
  $items = array(
    'MYMODULE' => array(
      'title' => 'Page Title',   // -> page-MYMODULE.tpl.php
      'page callback' => 'MYMODULE_page_main',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    ),
  );
  return $items;
}

function MYMODULE_page_main() {
  $path = drupal_get_path("module", "MYMODULE");
  $page = array();

  $page['MYMODULE'] array(
    '#theme' => 'page-MYMODULE',
    '#path' => '$path',
    '#title' => 'Content Title',  // -> content-MYMODULE.tpl.php
    '#attached' => array (
      'css' => array (
      'type' => 'file',
      'data' => $module_path.'/css/layout.css', //works only if layout.css was disable by hook_css_alter()
      'weight' => 'CSS_THEME',
     ),
  );
  return $page;
}

function MYMODULE_css_alter(&$css){
  if (arg(0) == 'MYMODULE') {
    foreach($css as $key => $val){
      if ($val['group'] == '100') {
        unset($css[$key]);
      };
    };
  }
}

```

page-MYMODULE.tpl.php

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

<div id="content">
  <?php print render($page['content']); ?>
</div>

```

content-MYMODULE.tpl.php

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

```

# Answer
I believe that what gets returned in `_page_MYMODULE()` ends up being the contents of `$page['content']`. What you want to do is have a completely separate template for `_page_MYMODULE()` to return that outputs what you want to have in the area of where `$page['content']` is output. Does that make sense?

Edit:

```
<?php print render($page['content']);?>

```

will render everything in whatever file the theme function in the array that you return in `_page_MYMODULE()` uses. This means that you want to have a different theme function and different file than you used for the page template. Something like `MYMODULE-results.tpl.php`.

So, to do that, you need to add a second theme in `hook_theme()`, so that the function looks something like this:

```
function MYMODULE_theme() {
  return array(
    'MYMODULE-page' => array(
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
      'template' => 'MYMODULE-page',
      'render element' => 'page',
    ),
    'MYMODULE-results' => array(
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
      'template' => 'MYMODULE-results',
      'variables' => array(
        'results' => array(),
      ),
    ),
  );
}

```

You'll notice that, instead of having a `render element`, you have `variables`. This is an array of variables that you're going to pass when you call `theme()` that you can then use in the template by using `$results`. It is currently set to default to an empty array, so if you don't pass anything as the results variable, you'll still have an empty array in your template to use, so things won't error out.

Next, you'll need to use this new theme in your `_page_MYMODULE()` function. That would look something like this:

```
function _page_MYMODULE() {
  // Some sort of DB query that returns results, such as:
  $results = db_query("SELECT * FROM node")->fetchAll();

  return theme('MYMODULE-results', array('results' => $results));
}

```

Then, in your MYMODULE-results.tpl.php file, you can loop through the $results array and add whatever HTML you want to surround each result.

Does this make sense?
> 1 votes

# Answer
You haven't passed a variable named `$title` to the template, so one won't be available.

To do so, add `variables` to your `hook_theme` implementation:

```
function MYMODULE_theme() {
  return array(
    'MYMODULE-page' => array(
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
      'template' => 'MYMODULE-page',
      'render element' => 'page',
      'variables' => array('title' => ''),
      ),
    ),
  );
}

```

and in your page callback:

```
return array(
  '#theme' => 'MYMODULE-page',
  '#title' => 'Title here',
);

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Commerce - adding a product to a cart programmatically with custom price
I've got a line item type called 'Donation' which has a Product reference field.

Additionally, I have an instance of a Product type called 'Donation' with the SKU of DONATION\_ONEOFF (pid=1), which has a price field set to $0.

*What I want to do is decide at form submit time what the value of the line item is before I add it to the cart.*

I have a test form, that when submitted, runs the following

```
function jam_test_donation_form_submit($form, &$form_state) {
    global $user;

    // Load the product with SKU DONATION_ONEOFF
    $product = commerce_product_load(1);

    // Try and set the price of the product before passing it.
    $product->commerce_price['und'][0]['amount'] = 22;

    // Create the line item from the product.
    $line_item = commerce_product_line_item_new($product, 1, 0, array());

    // Add the line item to the cart.
    $line_item_added = commerce_cart_product_add($user->uid, $line_item);
}

```

I was hoping that the new value (22) would display in the Cart, but it's still at 0 - even though the $line\_item and $line\_item\_added objects show the correct field values of 22 and even a calculated total if I add more.

I assume this could be because the cart is referencing the product node directly rather than using the value it was given at `commerce_cart_product_add` time - is there something I need to call to update this?

I could create a series of products at fixed amounts but I need the ability to specify an arbitrary amount for donation as well.

# Answer
> 1 votes
This is covered at length in a variety of other places. Your price is being lost due to the shopping cart refresh system and your avoidance of the core product pricing API.

You need a custom price field or something to store the price on the line item and then a pricing rule that swaps that custom price in for the unit price during the price calculation process.

---
Tags: 7, commerce
---


# Question
Title: How to let administrators AND anonymous users create new accounts?
I need to let anonymous users create his/her own accounts. But also I wish to create accounts when logged in as administrator. Is it possible such configuration? In admin/config/people/accounts is not possible, it just let you choose between exclusive options...

# Answer
> 1 votes
You can always create users as an administrator by going to *admin/people/create*.

So, in *admin/config/people/accounts*, in the **Who can register accounts?** you can choose *Visitors* and you will be good to go.

---
Tags: users
---


# Question
Title: Login Destination behaving differently on two instances of Drupal
I'm seeing some inconsistent behaviour from the Login Destination module on my "UAT" site as compared to my "Dev" site. Both sites (AFAIK) have the same module configuration:

* Neither of the global settings is enabled
* There is only one Rule, as follows:
    + **Redirect to Page** *foo-bar*
    + **Redirect upon Triggers** *Login, registration, one-time link*
    + **Redirect from listed pages** : *Only the listed pages* \- `<front>`

The problem is with the one-time link sent out on account activation.

The one-time link references a URL of `user/reset/[snipped]`. At this location there is a "Log in" button.

Clicking this button on my Dev site, users are redirected to `user/NNN/edit?pass-reset-token=[snipped]`, from where they can edit their account details.

**BUT** clicking this button on my UAT site, users don't redirect to the edit profile page, but are logged in and redirected to `/foo-bar`, which is useless, because they can never set their passwords.

The only difference I can see between the Dev and UAT sites is that the UAT site is HTTPS while my Dev site is HTTP. Is it possible that could be a cause of this issue? If not, how can I go about debugging this?

Best regards,

MB

**UPDATE**

Problem resolved - I'm just recording the outcome in case someone Googles this page in future.

It was of course nothing to do with HTTPS.

Someone had previously enabled the Trigger module on my UAT site, and there was a Trigger defined on user login to redirect to *foo-bar*. This was causing the one-time link to be redirected.

Due to the large number of modules on our UAT site, I didn't find this for a while. Disabling the Trigger module restored the desired behaviour.

# Answer
> 0 votes
See UPDATE above in main question for the solution.

FYI the problem was diagnosed by attempting to step-by-step trace through the Login Destination module, and then discovering that at one point I found myself in the `trigger` module code. PHPStorm for the win every time!

---
Tags: users
---


title: Scroll to links for articles on page

text:
# Question
Title: Scroll to links for articles on page
I would like to create a block and place that on the right hand side of my site.

Within the block I would like to have a list of links.

The links would scroll the viewport down to that article.

The page will be the homepage of the site.

I will use `Views` to create a page. I will select 10 full articles to be displayed on the page.

How can I go about creating a block to add to the right hand side which will contain links.

* I will need to have an id hook on the h1 of the article titles for the links to work.
* I have to loop through articles which show up in the view to get titles
* I need to create a block using the titles to create links such as `a href="#example-article"`

Day to day I code in Ruby on Rails, I am working on a Drupal project for a client and I am not well versed in PHP, never mind Drupal. I wouldn't be surprised if someone had wanted this same feature in the past - however - I don't work with 'blog style' sites often and I have not found any examples when searching online.

Any tips would be much appreciated. A link to a guide on how to achieve this would be amazing. Merely explaining how to get the articles object and loop through it for the titles and then put this in a block would get me 90% there.

# Answer
The good thing for you is this is completely doable within the Views UI alone. No PHP is needed here. A full explanation is too lengthy here (and asking for tutorials is off topic). If you're a novice to Drupal, watching some tutorials on Views would be a good time investment since it's a core part of Drupal now.

Here's some additional info to navigate you 90% there. See the image of the Views UI to yourself started with your page & block view:

If you have a view of full content nodes, Drupal, by default, wraps a node display in a `div` with an `id` of `node-<NID>`. (if you have a custom theme it might differ, but it should be pretty easy check that out). As such, a default Views page of full blog posts should already be linkable with a `#node-nid` anchor.

As for the block, Views allows you to have multiple displays based off the same query. When you create your view, you can also create a block. You'll just to make a few alterations to the block so that links are presented as anchor links for the page they'll appear on:

* Add a *Content: Nid* **field** to the **Block** display, making sure to set **For** selectbox to *This block (override)* (i.e. only add it to the block display).
* Tick the **Exclude from Display** checkbox so that the Nid field doesn't appear on the block.
* Rearrange the *Content: Nid* field (via the down triangle next to the **Fields** **Add** button) so that appears first.
* Click on *Content: Title* to reconfigure its display, you'll want to untick **Link this field to the original piece of content** to remove the hyperlink to the blog and tick **Output this field as a link** under **Rewrite Results**, you'll be placing *#node-\[nid\]* in **Link Path**, which if you did all the above correctly, should rewrite the block links to an anchor link for each post display.

That should get you most of the way there. Views UI is pretty complex so it's going to take a bit of experimentation to understand it all. The above should navigate you mostly through it.
> 1 votes

---
Tags: views, navigation
---


# Question
Title: force webform to reload or start from page1 with rules
If for example a field 'start over' is selected, I would like to reload the webform from page 1. Wondering the best way to do this. I already have rules and webform validation enabled. Do I create a custom rule? Standard rules do not have a redirect url that I can see. Or is there a function to call to start over.

# Answer
> 0 votes
While adding rule action you can select `System > page redirect`

This is how you can choose:

Thanks!

---
Tags: rules, webforms, forms
---


title: Multi select files in media browser

text:
# Question
Title: Multi select files in media browser
I would like to multi-select files in media browser. I came across this sandbox module: Media Multiselect but it has bugs that render it not usable. Does anyone know of a solution to multi-selecting files in media browser?

# Answer
> 0 votes
People are using this patch on latest media to multi-select media files on fields: https://www.drupal.org/node/951004#comment-9681531

Personally I had some problems to make it work at first, but finally I got it working (Had to disable admin\_language module).

---
Tags: media
---


title: Modal forms dropping # in the address

text:
# Question
Title: Modal forms dropping # in the address
I have made neat comment link for anonymous users http://example.com/modal\_forms/nojs/login?destination=http://example.com/comment/reply/NID#comment-form
However when I click it then the `#comment-form` is missing and it's very inconvenient because have to scroll to the comment form, how to fix it?

Here's the code responsible for opening login links in modal window:

`Drupal.behaviors.initModalFormsLogin = function (context) {
 $("a[href*='/user/login'], a[href*='?q=user/login']", context).each(function () {
 this.href = this.href.replace(/user\/login/, 'modal_forms/nojs/login');
 }).addClass('init-modal-forms-login ctools-use-modal ctools-modal-modal-popup-small');
};`

# Answer
Unless you URL encode, the fragment (what you have after the `#` sign) is not sent to the server.

If you want to include the hash in the `destination` parameter, it has to be URL encoded.

> http://example.com/modal\_forms/nojs/login?destination=comment/reply/NID%23comment-form

Note the `%23` above. It makes the browser think that the fragment is part of the `destination` parameter.
> 1 votes

---
Tags: javascript
---


# Question
Title: How do you force Drupal to re-render images?
I have an image style. It's defined as requiring images which are 60x60, however all of the images it's created are 500x500.

This is a screenshot of the image style definition: https://monosnap.com/file/GEIcrx6kRjeHg1b9VoDnRSAFNLgXmJ

I would think that this image would be a tad smaller (pixelation is intentional):
https://monosnap.com/file/E6oUIF3rxZ3qtLRTcbgJPGwZUg0j1e

I was able to disable and re-enable the responsive images in `borealis` on one of the environments, and that re-generated the same image, but that did not work on this environment.

# Answer
> 0 votes
You can try to flush your image style cache, eg. with this module: https://www.drupal.org/project/imagestyleflush

See also this answer: Rebuild images from image style

---
Tags: media, theming
---


title: Translated dates in Views

text:
# Question
Title: Translated dates in Views
I have a View which outputs the node creation date. But the site is multilingual. The problem is that I cannot choose a custom date format, as the Views just accepts one of a list. If I use a custom PHP format like j F Y (day month year in friendly format), I have prepositions, for example, in Spanish, that I cannot use: it should read "18 de Enero de 2015" instead of "18 Enero 2015" and if I put "j \d\e F Y", this will show a "de" which should not be present in other languages, like English.

Is there some module to just translate dates to multilanguage human friendly dates ? As I said, trying with Regions, Date Formats, Custom Date Format, etc., I cannot achieve what I need. If I use other formats, I have the extra time displayed, which I don't want, etc. etc.

# Answer
> 0 votes
You can create as many alternate date formats as you like. See this page for help: https://www.drupal.org/node/1600786

---
Tags: datetime, i18n-l10n
---


# Question
Title: Revert a Feature Component programmatically
I have a Feature installed using an Installation Profile. But I always have to go and Revert a particular Component so that it's no longer Overridden (so that, for example, the Feature's Blocks appear). I just wanted to know if I can take this step programmatically using code itself in the Installation Profile.

In the screenshot below, I've shown the component that has to be reverted programmatically (in the screenshot, it's already reverted back so check box is not available).

# Answer
I could solve the issue by using the hook function `fe_block_settings_features_revert('basic_site')` where fe\_block\_settings is the hook i.e. the component here and basic\_site is the feature/module name.
> 4 votes

# Answer
Here are a few thoughts though on resetting your features programmatically or as add-on install scripts.

You could use Drush to reset the Feature:

`drush features-revert [feature name]`

Another thought would be to use features\_revert() during the install process:

`features_revert(array('module' => array('component')));`

The Strongarm module could be useful as well to force your Feature to retain its default state I think.

*I have to agree with @Letharion in his comment on your OP. I would want to know that other important things aren't being mistakenly modified during the install process.*
> 20 votes

# Answer
You can revert a single features module with features\_revert\_module().

```
features_revert_module('my_feature');

```
> 18 votes

# Answer
Revert ALL components in feature

```
$feature = features_get_features('my_feature_machine_name');
$components = array_keys($feature->info['features']);
features_revert(array('my_feature_machine_name' => $components));

```
> 16 votes

# Answer
```
features_revert(array('module' => array('component')));

```

Where 'module' is the name of the specific features module (i.e. the the module generated when you download the feature) and 'component' are the components of those features. So if you just want to revert the fields defined in the feature you can use 'field' for component.
> 5 votes

# Answer
Use `features_revert()` to revert specific components only where the syntax is:

```
features_revert(array($module => $components));

```

for example:

```
features_revert(array('module_name' => array('taxonomy', 'node')));

```

To revert the whole module (with all its components), then use `features_revert_module()` instead, for example:

```
features_revert_module('module_name');

```

---

### Rules

For rules, this method is much quicker (to revert single rule):

```
$rule_name = 'my_custom_rule';
if ($rule = rules_config_load($rule_name)) {
  $rule->delete();
}

```

To revert all rules, it's:

```
if ($rules = rules_config_load_multiple(FALSE)) {
  foreach($rules as $rule) {
    if ($rule->hasStatus(ENTITY_OVERRIDDEN) && !$rule->hasStatus(ENTITY_FIXED)) {
      $rule->delete();
    }
  }
}

```

See: Add drush rules-revert \[#2474577\] | Drupal.org
> 5 votes

# Answer
To revert all overridden components of all Features in your Installation Profile, add the following to your .profile file's hook\_profile\_tasks():

```
/**
 * Rebuild & Revert all enabled features.
 */
features_rebuild();
features_revert();

```
> 2 votes

# Answer
```
    /**
     * Reverts all components of a feature.
     */
    function YOURMODULE_helpers_install_features_revert($module, $component = NULL) {
      module_load_include('inc', 'features', 'features.export');
      features_include();
      if (($feature = feature_load($module, TRUE)) && module_exists($module)) {
        $components = array();
        if (is_null($component)) {
          // Forcefully revert all components of a feature.
          foreach (array_keys($feature->info['features']) as $component) {
            if (features_hook($component, 'features_revert')) {
              $components[] = $component;
            }
          }
        }
        else {
          // Use the $component argument of this function.
          $components[] = $component;
        }
        foreach ($components as $component) {
          features_revert(array($module => array($component)));
        }

        drush_print(format_string('Reverted "!module" feature components !components.', array(
          '!module' => $module,
          '!components' => implode(', ', $components),
        )));
      }
      else {
        drush_print(format_string('Unable to revert "!module" feature.', array('!module' => $module)));
      }
    }

```
> 0 votes

---
Tags: 7, features
---


# Question
Title: How to edit Commerce to display more than 3 products in a row
I'm using **Commerce Kickstart**, I am not able to figure out how to display more than 3 **products** in a row. Even if I created a new View mode using **Entity View Mode** it still behaves the same.

How shall I go about changing this? Is there a setting somewhere in the View UI that's controlling this?

Thanks very much!

# Answer
Think I found a way to resolve this simply via CSS.

There is this styles in global.css:

> .page-products .view-display-products li:nth-child(3n+4) {
> clear: left; /\* LTR \*/ float: left; /\** LTR \*/
> }

so we can overwrite it with a sub-theme CSS with "**clear:none**".

By re-sizing browser window, looks like it still works well when window get smaller.

Earlier on didn't quite look close enough into this, partly due to meddling too much in Views Format settings. So assuming reverting to default Views setting, the above CSS change should work fine. Will update again if otherwise.

BK :)
> 1 votes

---
Tags: views, commerce
---


# Question
Title: New measures to prevent spam in comments of nodes?
I have a website with a node and comments which are moderated. I have installed Cache module, Image captcha (light distorsion). There was no spam till a few months ago. I installed Honeypot module and the few messages (probably automated) stopped being entered into the moderation list.

This week the site suffered a **massive** amount of flood spam. This coincides with the attack which is explained in Drupal.org. Is it possible that the attackers have learned how to override Honeypot and Image Captcha countermeasures?

How can I improve the security so the spam is reduced? My client will not allow more than a very small human input to delete a few spam messages.

# Answer
Maybe this module will help you: BOTCHA

There are more protection methods than just honeypot.
> 1 votes

# Answer
The Anti Spam by CleanTalk module might be another anti-spam module that could fit in your case. Some more details from its project page:

> Invisible antispam without CAPTCHA, questions, puzzles, counting animals, math and etc. Just install and forget.
>
> CleanTalk is a SaaS spam protection service for Web-sites.
>
> CleanTalk uses protection methods which are invisible for site visitors. Using CleanTalk eliminates needs in CAPTCHA, questions and answers, and other methods of protection, complicating the exchange of information on the site.

Optionally you may also want to look at the Comment Trust module. Here are some details about it (from its project page):

> ... auto-approves comments by users with previously-approved comments. It rewards trusted commenters with immediate approvals, while requiring you to approve the comments by new visitors. Works for both anonymous and authenticated users.
>
> You can configure the threshold of approved comments an email address has to first achieve before gaining auto-approval. You can also provide a list of email addresses (or patterns of email addresses) to always exclude from auto-approval.
> 0 votes

---
Tags: media, captcha, advertising
---


# Question
Title: Manage display at entity reference field Drupal
I have created two content types **A** and **B**.I have a date field in **A** which is referred in **B**. But in **B** I want to display the date field separately.

i.e 3 Different select list for month, year and day.

# Answer
It sounds like you want to create different display modes to be used in the different contexts that this entity's date field is being displayed.

Create a display mode for each different way you want it displayed with either of these possible methods:

The entity\_view\_mode module is the simplest approach, as display suite (ds) has many more features and options.

Once you create the view modes, then you can select the mode to be used for the entityreference field when the entity is being rendered there.
> 0 votes

---
Tags: datetime
---


# Question
Title: Is there a better way to create an alternative URL Alias Pattern?
Say for example my alias pattern for one node is set up as:

```
style-[node:field_style]/[node:title]

```

There may be a case that node:field\_style is blank so I would like to use another field and a slightly different url alias pattern:

```
type-[node:field_type]/[node:title]

```

I am thinking about just using hook\_pathauto\_pattern\_alter() but wondering if there is a better way?

# Answer
I'd create a token for that specific data; I'm not sure it's necessarily better (or worse) than using the alter hook, but it has the advantage of being reusable elsewhere in the site.

A simple (untested) example:

```
function MYMODULE_token_info_alter(&$data) {
  $data['tokens']['node']['field_type_or_title'] = array(
    'name' => t('Field type or title'),
    'description' => t('Value from field_type if available, node title otherwise.'),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    if (isset($tokens['field_type_or_title'])) {
      if ($items = field_get_items('node', $node, 'field_type')) {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($items[0]['value']) : $items[0]['value'];
      }
      else {
        $replacements[$tokens['field_type_or_title']] = $sanitize ? filter_xss($node->title) : $node->title;
      }

    }
  }
  return $replacements;
}

```
> 7 votes

---
Tags: 7, path-aliases
---


title: Theme styles and scripts not printing

text:
# Question
Title: Theme styles and scripts not printing
I'm having a problem in my `html.html.twig` file where the styles and scripts variables are not printing anything, and when I debug with dump:

```
{{ dump(styles) }}
{{ dump(scripts) }}

```

Both variables are empty and **'NULL'** is returned.

Any suggestions on how to debug this further?

# Answer
Those variables have been changed in beta16/RC1.

See HTML template head, scripts, styles and scripts\_bottom replaced with placeholder\_token:

### Before

```
{{ head }}
{{ styles }}
{{ scripts }}
{{ scripts_bottom }}

```

### After

```
<head-placeholder token="{{ placeholder_token|raw }}">
<css-placeholder token="{{ placeholder_token|raw }}">
<js-placeholder token="{{ placeholder_token|raw }}">
<js-bottom-placeholder token="{{ placeholder_token|raw }}">

```

The markup should be stable now with RC1, but when you're having trouble with a custom template, always compare it with the core default markup in the module providing it and/or the classy theme.
> 4 votes

---
Tags: 8, theming
---


title: How do I create a custom search block?

text:
# Question
Title: How do I create a custom search block?
I want to add in my D7 installation a search field inside a special part of the page, and I don´t want to use the default search block (as it will be harder to theme, this box I have already worked on it).

Naturally, if I just type:

```
<form><input type="text" placeholder="Search"></form>

```

it won´t work.

What else does this need to actually act like the default search form in the search block? I know there´s this Custom Search module, but I think that I shouldn´t install yet another module for this simple functionality.

Thanks!!

# Answer
> 8 votes
You could simply call drupal\_get\_form() on the search form\_id, which I think is - either search\_block\_form or search\_form

And use drupal\_render() on the returned array.

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

```

Though I might be wrong about the drupal\_render() part, yet it seems to me since the drupal\_get\_form() returns an array drupal\_render should be used on it.

Also this page might be helpful too - http://data.agaric.com/print-form-such-search-form-anywhere-drupal

Hope that helps.

# Answer
> 4 votes
I'm not sure why you said the default search box is harder to theme. Drupal can do theme override or form override as you like. If you google, you will see many solutions for this purpose.

Check this Q/A : how to overwrite the search box? and you could also override search-block-form.tpl.php. Then, you can define which pages the search block to be appeared at the block configuration page **admin/structure/block/manage/search/form/configure**

OR remove the search block from any region and then you can print the block programmatically where you want. See Placing the contents of a block in any location.

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

```

# Answer
> 4 votes
```
/*
 * create search block
 */

function mymodule_block_info() {
$blocks['my_search'] = array(

'info' => t('My Search Block'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
function mymodule_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'my_search':
  $block['title'] = 'MyCustom Search';
  $srchblk = drupal_get_form('mymodule_search_block_form');
  $block['content'] = drupal_render($srchblk);
  break;
  }
  return $block;
}

/* create search form */

function mymodule_search_block_form($form, &$form_state) {
$form['keys'] = array(
'#type' => 'textfield',
'#size' => 15,
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Search',
);
return $form;
}

/*
 * create search result menu callback
 */

function mymodule_menu() {
$items['custom/node/search/%'] = array(
'page callback' => 'mymodule_do_search',
'page arguments' => array(3),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}

/*
 * create form handler
 */

function mymodule_search_block_form_submit($form, &$form_state) {
drupal_goto('custom/node/search/' . $form_state['values']['keys']);
}
 /*
  * create search result callback function
  */

function mymodule_do_search($keys) {
  // set the page title

drupal_set_title('MY search results');
  // get the search results

 $results = module_invoke('node', 'search_execute', $keys );
 return theme('search_results', array('results' => $results));
 }

```

# Answer
> 0 votes
This is what I needed:

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

```

---
Tags: 7, blocks, search
---


title: How to delete "In code" views?

text:
# Question
Title: How to delete "In code" views?
Some Drupal views I have are "In code" (while some others are "In database"); I understand that some are hard-coded in some PHP files and some are coded in the SQL.

Generally, what are the PHP files in which the "In code" views are stored?

# Answer
> 0 votes
The file name convention for default views provided by a module uses the extension **.views\_default.inc**.

Alternatively, if a module isn't using standard naming conventions, you can search the code base for `hook_views_default_views_alter()` implementations (e.g. `grep -r '_views_default_views_alter' .` ) to find these views.

---
Tags: views
---


# Question
Title: Access Drupal7 Database Nodes without actually having anything installed (simple php + mysql)
The last days I got some trouble with the drupal database schema. I don't know anything about Drupal7 except that database entries are saved in several fields.

I need to read out all the different nodes and their attributes of a mysql server in Drupal Scheme (in the best case without actually using the Drupal environment) with a simple .php page. Is there any chance to do so?

Example: Car Entries - what I need are

field\_data\_field\_speed

field\_data\_field\_weight

and more.

Would be grateful for help!

**UPDATE:** Database Drupal relationship between tables, to get a node schema and node data.

# Answer
If I'm not wrong you want a 'query' that connect a content type with all its fields.

Each field has it own table.

But you can connect the dots using a few queries (\[content\_type\_name\] could be article, car\_entry or whatever the name of your content type is):

\*Getting all the entries for a content type

> SELECT * FROM node WHERE type = '\[content\_type\_name\]'
>
> *column id would be the \[entity\_id\]*

\*Getting all fields from a content type

> SELECT * FROM field\_config\_instance WHERE entity\_type = 'node' AND bundle = '\[content\_type\_name\]'
>
> *this table contains column field\_id \[field\_id\] and column field\_name \[field\_name\]*

Now that you have the fields:

\*Get the field info using field\_id and/or field\_name

> SELECT * FROM field\_config WHERE id=\[field\_id\] AND field\_name='\[field\_name\]'

\*Get the field data by node

> SELECT * FROM field\_data\_\[field\_name\] WHERE entity\_id = \[entity\_id\]

Play around with those queries, so you get a better idea of the columns that each one of those tables contains. Then you can create mysql joins to create the queries that you need.
> 0 votes

---
Tags: views, database
---


# Question
Title: Display Content with Taxonomy on User and content matching with Multiple Vocabularies
I am trying to create a view to show content that is tagged with taxonomy terms from the users profile (*each vocabulary has its own field in the users profile where the user can select via check boxes what they are interested in.*)

I read and watched multiple tutorials and articles on this, and the closest I can get is described here by Triskelion:

> create a user view, add relationships: **Content: Tags (my Vocab)** and **Taxonomy term: Content with term** with a contextual filter on the **User:UID**, then display the **content:title**. This works perfectly given one vocabulary, but I cannot for the life of me get it to work correctly with multiple vocabs.

I added multiples of the above relationships for each of the vocabs, and display multiple **content:titles** with each relationship, but the problem is that *each row in the view will contain only one different title. Aggregation and Querey distinct settings don't seem to help!!*

Can anyone point me in the right direction. I know there is a solution to scrap my multiple vocabularies and just put all terms into one but this is not really desirable, as id lose the structure of my taxonomy.

# Answer
If I understood correctly you are trying to eliminate duplicates from your view. Display only one title by content.

When I'm in a case when even Aggregation or Query Distinct settings don't seem to work (most of the time this is caused because the query left/inner joins), I use a small script that does the trick to do an easy group by using the query comment field. In your case you could group by node.id

```
/**
 *  Found this trick on theoleschool.com.
 *
 *  Description: Allows the view developer to specify the query
 *  group by action in the query comments. Great way to force the
 *  removal of duplicates.
 *
 *  Just go into your query comments and type in "groupby:" with
 *  that colon followed by the field you want to group by.
 *
 *  Examples...
 *  groupby:node.nid
 *  groupby:file_managed_file_usage.fid
 *
 *  Ref-Comment: http://theoleschool.com/comment/496#comment-496
 *  Ref-Article: http://theoleschool.com/blog/using-hookviewsalter-add-group-statement
 */
function mymodule_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('views')) {
    static $count;
    $view =& $query->getMetaData('view');

    if (strstr($groupby = $view->query->options['query_comment'], 'groupby')) {
      list($action, $field) = explode(':', $groupby);

      if (strlen($field) > 0) {
        $query->groupBy($field);
      }
    }
  }
}

```
> 1 votes

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


# Question
Title: Is it possible to use standard tokens in a views field?
I am using Drupal 7.38 and Views (7.x-3.11) to show fields. I can't seem to get standard token replacement working for text fields, e.g. `[node:created]` is not replaced with the relevant value.

This seems to work fine if I set views to show content rather than fields. Am I missing something obvious?

# Answer
> 3 votes
The solution I found for this was the Advanced Text Formatter module, which allows you to set a new text format for text fields within Views, including an option to replace Tokens.

# Answer
> 3 votes
If you want to display the date the node was posted or created when showing fields, you don't need to use a token. Simply add the field `Content: Post date` to the fields of the view.

If you want to include this date in a `Global: Custom text` field in your View, be sure to have the field `Content: Post date` **above** the `Global: Custom text` field. The replacement pattern for the post date will appear by clicking on `Replacement Patterns` inside the custom text field (usually named `[created]`). You can also select `Exclude from display` in the post date field if you don't want it to show.

**EDIT:** Re-read your question, and I guess you are using Token Filter to insert tokens like `[node:created]` in a `Long text` field in your node, right? If this is the case, I'm afraid Views will not do a token replacement when rendering the field. There may be a way to modify the Views formatter to do this, but that's beyond my skills. See this post for a similar situation - you are able to use token replacements in your Views Header or Footer custom text, but not in a Field.

---
Tags: views, tokens
---


# Question
Title: AJAX event and disable select form element
I have a little problem:

```
/**
 * Form callback
 */
function ajax_disable_test_form($form, &$form_state) {
  $form['select'] = array(
    '#type' => 'select',
    '#required' => FALSE,
    '#title' => t('Change me!'),
    '#empty_option' => t('- Select -'),
    '#options' => drupal_map_assoc(range(1, 3)),
    '#prefix' => '<div id="select_box_wrapper">',
    '#suffix' => '</div>',
  );
  $form['change'] = array(
    '#type' => 'submit',
    '#value' => t('Change!'),
    '#ajax' => array(
      'callback' => 'ajax_disable_test_form_submit_ajax',
      'wrapper' => 'select_box_wrapper',
    ),
  );
  return $form;
}

/**
 * Ajax callback
 */
function ajax_disable_test_form_submit_ajax($form, $form_state) {
  $form['select']['#title'] = t('Changed!'); // It's work!
  $form['select']['#disabled'] = TRUE; // It's not work!
  return $form['select'];
}

```

Link: https://gist.github.com/nevergone/23f0a50bee01acc34ed2

If clicked the button, select box title changed, but select box not disabled. Why? Version: Drupal 7.41

# Answer
try:

```
$form['select']['#attributes']['disabled'] = 'disabled';

```

Ok, a detailed explanation can be found on this article https://www.drupal.org/node/357328

But pretty much resumes to:

> we cannot simple set the $element\['#disabled'\] attribute of the element. The reason is this attribute is transformed into $element\['#attributes'\]\['disabled'\] by \_form\_builder\_handle\_input\_element executes()...
> 1 votes

# Answer
You will need to rebuild your form. Have a look at the Ajax Framework docs for further information.

```
<?php

/**
 * Form callback
 *
 * Implements hook_form().
 */
function ajax_disable_test_form($form, &$form_state) {
  $form['select'] = array(
    '#type' => 'select',
    '#required' => FALSE,
    '#title' => t('Change me!'),
    '#empty_option' => t('- Select -'),
    '#options' => drupal_map_assoc(range(1, 3)),
    '#prefix' => '<div id="select_box_wrapper">',
    '#suffix' => '</div>',
  );
  if (!empty($form_state['values']['change'])) {
    $form['select']['#disabled'] = TRUE;
    $form['select']['#title'] = t('Changed');
  }

  $form['change'] = array(
    '#type' => 'submit',
    '#value' => t('Change!'),
    '#submit' => array('ajax_disable_test_change_submit'),
    '#ajax' => array(
      'callback' => 'ajax_disable_test_ajax_callback',
      'wrapper' => 'select_box_wrapper',
    ),
  );
  return $form;
}

/**
 * Submit handler to disable the select input, and then rebuild the form.
 * If the button was click with JS enabled, then ajax_form_callback() calls
 * ajax_disable_test_submit_ajax() to return just the changed part of the form.
 */
function ajax_disable_test_change_submit($form, &$form_state) {
  if ($form_state['values']['change']) {
    $form_state['select_is_disabled'] = true;
  }
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback
 *
 * @see ajax_disable_test_change_submit().
 */
function ajax_disable_test_ajax_callback($form, $form_state) {
  return $form['select'];
}

```
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: Removing all unapproved comments from database dump file
I got thousends of spam comments on my drupal 7 site. The mysql database file is grown to 1.9GB and the site is broken. How can i delete all comments (or even better: all unapproved comments) from the database dump file?

# Answer
> 1 votes
From your dump file, I would cut the part that insert the data to the comment table. Note: Leave the part that create the table.

In another file paste the part that you cut from the original dump file, using a text editor that can handle to search using regular expressions (as Sublime Text 2). Create the regular expression that would give you as a result the complete row insert if that row has the status column value set to one. Once that the regular expression is working, now use the search an replace. Search all the matches and replace them with ''

When the search and replace is done, you can copy and paste to the sql tab if you are using phpMyAdmin, or even save the resulting file as .sql and import it.

Pretty much the laborious part would be to find the regular expression to use.

Hope this help!

---
Tags: comments, database, advertising
---


title: Multiple files with different language

text:
# Question
Title: Multiple files with different language
I want to make a field with type file and this field with multiple values, so far I know that its simply possible but I want also to some thing like bundle field with each file uploaded and this field is representing language.

**Example**: Suppose I upload 3 files in same field for the same node & each file with different language (file\_1 =\> English , file\_2 =\> French , file\_3 =\> German) and so on.

So is there any module can accomplish that, or its something I should do custom?

I want a solution like the attached image

# Answer
> 0 votes
I think multifield is the most close solution to what i need

# Answer
> 1 votes
Are you looking for field\_collection?

1. Install and enable the module.
2. Add a field of type "Field Collection" to your entity type.
3. Go to admin-\>structure-\>Field COllection
4. Add 2 fields 1 field is of file type 2 field is either select box with countries or can be taxonomy reference field

Now while creating the content, you will have option to upload a file and select a language for it.

# Answer
> 0 votes
The Entity translation module should allow you to accomplish this.

A brief series of steps to are listed below but I would encourage you to look at this page on drupal.org

1. Install and enable the module
2. Add additional languages to your site
3. Enable multilingual support for the content type
4. Make the file field translatable

# Answer
> 0 votes
You could make custom solution by using **delta** as the field will have more than one value

> 0 =\> English , 1 =\> French , 3 =\> German

So when you are viewing that node based on language you could just render each file based on mapping delta with languages.

Also making custom ***field--\[type|name\[--content-type\]|content-type\].tpl.php*** take a look at to control field display

even with views you could alter the views\_query

At the end you have to handle edit and if the user deleted one file you must make the delta be in its original order.

# Answer
> 0 votes
with file\_entity module you can attach more fields to file widget. So when user uploads something he/she can select language. In your case I think you would need also languagefield or create field inside file entity and populate list of enabled languages.

# Answer
> 0 votes
What about **Inline Entity Form** module (https://www.drupal.org/project/inline\_entity\_form)

follow the next steps:

1. Create one content type with the file field. You didn't mention if your site uses multiple languages, if it does most probably the language field would show up in the form (with the languages that the site is using). If there is not a default language field you can add a language taxonomy containing the desired languages.
2. On your current form add an entity reference field pointing to the form with the file file, and select inline entity form(multiple values) widget.

Then you can use **Views** to display your info. Or if you don't want to use views then you can use **Inline Entity Display** module (https://www.drupal.org/project/inline\_entity\_display)

---
Tags: nodes, files, i18n-l10n
---


# Question
Title: Download a node (and its associated files as a zip archive)
Looking to create a system whereby users can upload print quality images, have them resized for web, but allow admin users to download the contents of a particular node and download the highres images and field texts as a zip archive... what would be a good starting point for this? A particular module? Build a custom module?

# Answer
> 3 votes
I put together a proof of concept module real quick, which exports files based on assumptions about `field_type` (image, file and media).

To test it out, put the following code in a custom module, then go to */export-entity/node/`nid`* to export a node.

```
<?php

/**
 * Implements hook_menu().
 */
function export_entity_menu() {
  $items['export-entity/%/%entity_object'] = array(
    'page callback' => 'export_entity_page_callback',
    'page arguments' => array(2, 1),
    'load arguments' => array(1),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

/**
 * Export entity page callback.
 *
 * @param object $entity
 * @param string $entity_type
 *
 * @throws EntityMalformedException
 * @throws EntityMetadataWrapperException
 * @throws Exception
 */
function export_entity_page_callback($entity, $entity_type) {

  $wrapper = entity_metadata_wrapper($entity_type, $entity);
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

  $file_fields = field_read_fields(array(
    'entity_type' => $entity_type,
    'bundle' => $bundle,
    'type' => array('image', 'file', 'media'),
  ));

  $field_files = array();
  foreach ($file_fields as $field_name => $field_config) {
    $files = $wrapper->{$field_name}->value();
    if ((int) $field_config['cardinality'] === 1) {
      $files = array($files);
    }
    foreach ($files as $file) {
      $field_files[$file['fid']][] = $field_name;
    }
  }

  $export_filename = drupal_tempnam(file_directory_temp(), 'entityexport_');

  $zip = new ZipArchive();
  if (!($zip->open($export_filename, ZipArchive::CREATE))) {
    throw new Exception(t('Unable to create zip archive'));
  }

  $entity_data = entity_var_json_export($wrapper->raw());
  $zip->addFromString(sprintf('%s_%d.json', $entity_type, $id), entity_var_json_export($entity_data));

  // Load and attach all files/file entities
  $files = file_load_multiple(array_keys($field_files));
  foreach ($files as $file) {
    $folder = reset($field_files[$file->fid]);
    $file_path = drupal_realpath($file->uri);
    $zip->addFile($file_path, $folder . '/' . $file->filename);
    $zip->addFromString($folder . '/' . $file->filename . '_entity.json', entity_var_json_export($file));
  }
  $zip->close();

  // Copy archive to public storage and redirect to its URL.
  $public_uri = file_default_scheme() . '://entity-export/' . $entity_type;
  file_prepare_directory($public_uri, FILE_CREATE_DIRECTORY);
  $public_uri .= '/' . basename($export_filename) . '.zip';

  $public_path = file_unmanaged_move($export_filename, $public_uri);
  $public_url = file_create_url($public_path);

  drupal_goto($public_url);
}

```

Note that this should be done using a batch callback and/or a cron-job, especially if you expect to get alot of data - which may cause the script to time out and/or run out of memory (although it really shouldn't).

# Answer
> 0 votes
pclzip might be a good place to start. It's only in dev for 7, but you could always take a look at the back end and see what they're doing, then use that to write a custom module off of it if it doesn't suit your needs.

---
Tags: files
---


# Question
Title: Notify user if they are about to delete a node that is referenced by another node
Is there a way to notify a user when they are about to delete a node that is linked to by another node?

I'm working on a site where many of the pages reference another and I would like to put some mechanism in place where the user is notified before taking action.

# Answer
> 0 votes
If the node has an entity reference you can use the Rules module.

# Answer
> 0 votes
Assuming you are referring to entity references, you could create a custom module (see tutorial), something like this. In this example, the custom module is called "prevent\_del." It uses `hook_form_ID_alter()` The referenced node is of type `special_node_type` and the referencing nodes are of type `page`.

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

 if ($form['#node']->type = 'special_node_type') {

    // Get the node id of this special_node_type.
    $nid = $form['nid']['#value'];

    // Get array of nodes of type page referencing this $nid

    $query = new EntityFieldQuery();

    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'page')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->fieldCondition('field_reference', 'target_id', $nid, '=');

    $result = $query->execute();

    // Create a comma-separated string with all nids of referencing nodes
    if (count($result)) {
      $nodes = $result['node'];
      $node_string = array_shift($nodes)->nid;
      foreach ($nodes as $node) {
        $node_string .= ', ' . $node->nid;
      }

      $markup = t('This node is referenced by nodes with ids: @node_string. Please remove the the other nodes before trying to delete this one.', array('@node_string' => $node_string));

      // Use the markup key to display message.
      $form['description']['#markup'] = $markup;

      // Remove the 'delete' button from the form.
      $form['actions']['submit']['#access'] = FALSE;
    }
}}

```

---
Tags: nodes
---


# Question
Title: How add a css id selector to a views row
I need to add a css id selector to a views row. Of course this is straight forward with a class selector such as `.my-class` but how do I insert something like `#my-class` at the individual row level?

I realize that this probably invalid CSS; however, the ID appears to be needed to trigger some JavaScript.

Some background: I want to use a component from the Bourbon Refills CSS framework for a 'fade in' effect and apply this to all the rows in a views. See http://refills.bourbon.io/components/#fade-in.

In order the make this work I need to add a CSS ID `#js-fadeInElement` to each row.

### Note

After a bit more digging, it seems I may need a custom `row.tpl` file in my theme. Is this correct?

# Answer
> 2 votes
**Solution 1:**

No need to add ID for each row, you can achieve it by each row CSS class it self. Instead of `document.getElementById("js-fadeInElement");` you can use `document.getElementsByClassName("js-fadeInElement");`

**Solution 2:**

1. You can use Views theme templates to modify the HTML output and add your id attribute.
2. Under the Advanced section, you will find Theme: information.

> This link will show you possible file name for templates and a sample content of that file.

3. You probably want to copy and modify the "Style output". You can put your custom template in your own theme directory. You probably want a name like `views-view-list--your-view--page.tpl.php`

Please follow this link to override the template.

---
Tags: views, theming
---


# Question
Title: How to add tables relations into custom entities content type?
I have a custom content entities in my Shop module.

I want 2 tables :

* Orders
* Order line

I create a custom content entity for orders, but I ask about the way to do the order line.

Do I need to create a second custom entity content and make a field reference orders table inside?

Or there is a way to declare subTable into the main entitie (orders for me)?

# Answer
First, forget about tables. Drupal 8 mostly takes care of that for entities.

Think about data structures instead: entities and fields.

What do you want?

* Two separate entities, both possibly extensible with additional fields, maybe different bundles (e.g. product and shipping line items). Then make two entity types, with a reference field from line items to the order.
* Simpler, non-extensible line items. Then you can design them as a custom field type and add that as a base field with unlimited cardinality. (In this case, they will be stored in a separate table, but you don't need to know about that for the most part).
> 2 votes

---
Tags: entities, 8
---


title: Strict case in content URL alias

text:
# Question
Title: Strict case in content URL alias
(Pathauto: Leave case the same as source token values)

When I create a node with "Nullam vehicula pharetra" as title, the Pathauto module will create `/content/Nullam-vehicula-pharetra` as URL alias. But we can browse the same content with a different URL case, such as `/content/NULLam-vehicula-pharetra`.

How do I make Drupal strict on the URL alias case?

Wikipedia is good example about what I need. Two different case request return different contents:

# Answer
> 0 votes
Even if you don't use pathauto, Drupal7 can not differentiate case sensitive urls. This 'issue' is not code related, but it has to be with the database collation. non-binary string comparison are case-insensitive by default.

A solution could be to set the 'alias' columns (menu\_router.path, url\_alias.alias) to binary (case-sensitive).

Be aware that changing the structure of those two columns in existing sites could result in broken links because paths/alias would have to match base on case.

# Answer
> 0 votes
I agree with Blanca.

Wikipedia, and wikis in general, use a completely different system of creating and linking pages.

The following doesn't answer your question but it might help with your approach.

To avoid search engine ranking issues I always select "Change to lower case" in /admin/config/search/path/settings, as well as use Global Redirect with "Case Sensitive URL Checking".

So if a you visited domain.com/Page you'd be redirected to domain.com/page.

This seems like a more logical approach to me. I don't think any user would expect to see different content according to case sensitivity. i.e. to take this a step further StackExchange.com is no different to stackexchange.com.

Of course, in your case, this might not make any sense.

---
Tags: 7, path-aliases
---


# Question
Title: How do I add a term reference name to the Pathauto pattern for a content type?
I'm trying to create a website with 2 sections, Home and Business. For this I have created a vocabulary called '**Page Type**' and added those section names to it.

I've added a term reference field to my content type to relate nodes to my vocabulary.

What I need to do is automatically set the titles of the nodes to include the section name they are related to, using the Pathauto module.

I'm at the settings page (`/admin/config/search/path/patterns`) but I don't know what pattern to use - '**Page Type**' is a vocabulary, not a content type, so I don't know how to use it as part of a pattern.

How do I add the name of the referred taxonomy term to the node path? For example, I'm expecting URLs like this:

* example.com/home/page-title
* example.com/business/page-title

So I want the node page to have a vocabulary in its path, the vocabulary of a term it is tagged with.

# Answer
> 0 votes
It should be something like \[node:field-yourfieldname\].

On that page underneath each conten-type field, do you not see a "Replacement patterns" title?

If not, install the token module.

---
Tags: 7, taxonomy-terms, path-aliases
---


# Question
Title: How do I add a taxonomy vocabulary to more than one menus with the taxonomy menu module?
I'd like to have two different menus based on the same taxonomy vocabulary, but the taxonomy menu module only lets me choose one menu to add the terms to.

Can I somehow add the same terms to more than one menu?

# Answer
> 0 votes
Try this: https://www.drupal.org/project/taxonomy\_menu\_block

Otherwise, you can use views to create blocks with links from a taxonomy vocabulary.

---
Tags: taxonomy-terms
---


# Question
Title: Which hook for code after a node has been deleted from the DB?
I'm running Drupal 7 and I want to re-save the user account of the node author after deleting a node of content type **picture**. I want to do this because I have some code called in `hook_user_presave()` that counts the number of pictures a user has added and saves it in an integer field in the user.

I looked at `hook_node_delete()` and `hook_entity_delete()` as suggested in this question, but when then are invoked, the node is not yet deleted, so if I save the user at that point, the int value is one more than it should be (because the deleted file has not actually been deleted yet).

Is there a hook for responding to node deletion after it has taken place?

Related question: Hook for reacting after adding node

# Answer
There isn't one. If you look at `node_delete_multiple()`, which `node_delete` is a wrapper function for, you can see that the only hook invocations (the above hooks) are triggered before the DB delete statements.

If your Drupal site only allows deleting through the **node/$nid/delete** form, one alternative to a post-delete hook is appending a submission handler to the node deletion confirmation form:

```
function MYMODULE_form_node_delete_confirm_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_node_delete_confirm_submit';
}

function MYMODULE_node_delete_confirm_submit($form, &$form_state) {
  //@TODO: Post-node-delete code here
}

```
> 5 votes

---
Tags: hooks
---


# Question
Title: Extending existing menu/route in module_menu_alter
Trying to extend Rooms (`rooms_booking_manager`):

Originally, there is an enquiry-page which takes arguments

```
"enquiry/[startDate]/[endDate]/[roomNumber]"

```

I want to write a more specific handler IF arguments persons and children are given as in enquiry/startDate/endDate/roomNumber/numberOfPersons/numberOfChildren; in that case my own handler should take precedence.

This is the code used by the module.

```
function rooms_booking_manager_menu() {
  $items = array();

  $items['enquiry/%start_date/%end_date'] = array(
    'title' => 'Ask about availability',
    'page callback' => 'rooms_booking_manager_enquiry_page',
    'page arguments' => array(1, 2),
    'access arguments' => array('book units'),
    'type' => MENU_CALLBACK,
  );

  // …

  return $items;
}

```

This is the code I use in my module.

```
function netfactory_rooms_menu_alter(&$items) {
  $items['enquiry/%start_date/%end_date/%persons/%children'] = array(
    'title' => 'Ask about availability',
    'page callback' => 'netfactory_rooms_enquiry_page',
    'page arguments' => array(1, 2, 3, 4),
    'access arguments' => array('book units'),
    'type' => MENU_CALLBACK,
  );
}

```

Nevertheless, if I call enquiry/startDate/endDate/roomNumber/numberOfPersons/numberOfChildren `rooms_booking_manager_enquiry_page()` is called instead of `netfactory_rooms_enquiry_page()`.

Coming from a .NET MVC background, I was thinking that the order (most specific first) is important; so I also tried setting `weight=-1000` on my own route, but that did not help either.

How can I hook into a module to add a route which is MORE SPECIFIC than an existing route?

# Answer
For Drupal, enquiry/%start\_date/%end\_date/%persons/%children and enquiry/%start\_date/%end\_date are different; so you aren't overriding an old one, but defining a new one, for which you should use `hook_menu()`, not `hook_menu_alter()`.

You just need to use code similar to the following one.

```
function netfactory_rooms_menu_alter(&$items) {
  $items['enquiry/%start_date/%end_date'] = array(
    'title' => 'Ask about availability',
    'page callback' => 'netfactory_rooms_enquiry_page',
    'page arguments' => array(1, 2),
    'access arguments' => array('book units'),
    'type' => MENU_CALLBACK,
  );
}

function netfactory_rooms_enquiry_page($start_date, $end_date, $persons = DEFAULT_VALUE_FOR_PERSONS, $children = DEFAULT_VALUE_FOR_CHILDREN) {
  // …
}

```

(Replace the constants with the values you wish.)

As you read in the first example on `hook_menu()`, if the page callback is called for abc/def, its parameters will get their default value, while called for abc/def/123/foo, `$ghi` will be `'123'` and `$jkl` will be `'foo'`.

```
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
  }

```

Keep in mind that wildcard parameters like %start\_date are used if there is a function named `start_date_load()` used to return an array or an object that is then passed to the page callback; if you don't have such function, you should use the generic wildcard %. Then, when the parameter is at the end of the path, and you don't use a load function, then there isn't any need to use wildcard parameters.
> 1 votes

# Answer
I would try `netfactory_rooms_menu()` (i.e. `hook_menu()` instead of `hook_menu_alter()`). You are effectively creating a new menu callback, not extending an existing one.

Also, **CLEAR THE CACHE** before trying the new path.
> 1 votes

---
Tags: routes
---


title: Oauth and Facebook

text:
# Question
Title: Oauth and Facebook
Is there a way to make users auto register to a Drupal site if they are logged in to Facebook? I know Drupal for Facebook and Facebook - Auth but they are using tables, and not user profiles.

# Answer
> 2 votes
Suggest you look at the Facebook Connect module instead

# Answer
> 2 votes
http://drupal.org/project/fboauth

One of the better FB integration modules I've seen; I poked quicksketch to take this thing from sandbox to module, and he's done a great job of porting the module and responding to maintenance queries. The code is simple and easy to work with. I did a rough port to D7, which you can find in the issues queue. I'm sure you could rig it to automatically register visitors, although they will still have to grant permission for whatever data you desire through FB. I'm sure you've already checked it out, but the FB documentation will fill you in on the general concepts related to Facebook authorization.

# Answer
> 2 votes
The OAuth Connector module for Drupal 7 claims to be supporting signing up and logging in through OAuth 2 API:s in general and also to support Facebook specifically.

# Answer
> 0 votes
As stated on a previous post the OAuth Connector may do the job.

You have a nice tutorial here http://fuseinteractive.ca/blog/how-allow-facebook-logins-your-drupal-site

# Answer
> 0 votes
Try Janrain Engage (formerly RPX) module.

> Using Janrain Engage, **Drupal sites can authenticate new and existing users with popular social networks**, map user profile data from these websites to Drupal fields, and share Drupal content with a user's friends on their social networks.
>
> Here's a quick summary of some notable features:
>
> **LOGIN AND REGISTRATION**: **Allow site visitors to register and login with one of their existing accounts at popular social networks such as Facebook**, Google, Yahoo!, Twitter and LinkedIn. Support is included for both the Drupal user login block and the user login page. Quickly and easily converting anonymous site visitors into active registered users.
>
> **DATA MAPPING**: With permission of the user, you can map a user's social profile data to specific Drupal fields. A variety of fields are supported, including User fields, old-style core Profile fields (for those upgrading from Drupal 6), and **Profile2 contributed module fields**.
>
> IMPORT PROFILE PICTURE: Import profile photos from a user's social network account and use it as the Drupal profile picture.
>
> SOCIAL SHARING: Make it easy for users to share their Drupal content and comments with friends and followers on other social networks. A "Share" button or link may be included on specific content types, which triggers the Janrain Engage social sharing widget. When a user submits a comment, this widget can be automatically triggered (suggesting to the user that he/she should share the comment).
>
> LINKED ACCOUNT MANAGEMENT: A "Linked accounts" tab is provided to the end user (who has the appropriate module permission). Using this tab, a user can add, remove, or otherwise manage the social network accounts connected to his/her Drupal site account.
> RULES
>
> INTEGRATION: For those using the popular Rules module, you can configure the full range of Rules-based actions to occur (change a role, send an e-mail, etc.) whenever a user adds or removes a linked account via Janrain Engage. You can also configure the Janrain Engage social sharing widget to launch on various Rule-based events.
>
> VIEWS INTEGRATION: If you use the Views module, you can easily create various views that include such data as linked account ID's, provider information and icon, as well as a link to delete the account. These can be used, for example, to create site-wide analytics about the number of linked accounts of a given type that have been created.
>
> CAPTCHA INTEGRATION: Now you can use any of the popular captcha modules (Mollom, Captcha and its submodules) alongside Janrain Engage. While regular sign-ups will still be required to go through captcha verification, sign-ups via Engage will be automatic.

# Answer
> 0 votes
I tried the Oauth Connector Module but could not get it to work. At the time of this comment, the Oauth Connector module had no commits since Oct 2013 (2 years ago). So, I went with the HybridAuth Social Login module which is currently very actively maintained and it just worked without any hassle.

Taken from the project page:

> HybridAuth Social Login integrates HybridAuth library into Drupal and allows your users to login and register using:
>
> * Facebook
> * Twitter
> * LinkedIn
> * Google
> * Yahoo
> * Windows Live
> * Foursquare
> * AOL
> * OpenID
> * Github, LastFM, PayPal, Vimeo, Disqus, Instagram, Tumblr, Vkontakte, Mail.ru, Yandex, Odnoklassniki, Twitch.tv, Steam and more

---
Tags: 7, users, authentication-authorization
---


# Question
Title: How to clone a entity with its attached fields?
I am trying to create a entity with few bundles. I have used **EntityDefaultUIController** as admin UI callback. This provides me with few default functions such as clone, import and export. The problem is when I try to clone or export the entity. It does not export or clone the fields attached to it. Has anyone faced similar issues. I traced back the issue to **entity\_ui\_get\_form** function which does not have any function related to getting the field information. How could I clone entity with its fields attached to it?

Kindly help me figure this out.

# Answer
A recent module called Replicate provides an API to easily clone any entity, including of course its fields and references.
> 1 votes

# Answer
There is an issue open on drupal.org for cloning fields along with the entity. There's also an RTBC patch - see https://www.drupal.org/node/1513812. The patch to use is number 23 (https://www.drupal.org/node/1513812#comment-7800593).
> 0 votes

---
Tags: entities
---


# Question
Title: File uploads: Warning: session_start(): Cannot send session cookie - headers already sent
When I check watchdog, I have lots of PHP warnings like this:

> Warning: session\_start(): Cannot send session cookie - headers already sent by (output started at /srv/bindings/9c42927e5316467d82a6fb1be50ed34e/code/includes/file.inc:1972) in drupal\_session\_start() (line 287 of /srv/bindings/9c42927e5316467d82a6fb1be50ed34e/code/includes/session.inc).

There are a lot of reports of errors like this, apparently most of which are caused by having spaces at the beginning or ends of PHP files. But in this case, I think the problem is related to file uploads for the following reason. The **Location** of these warnings are paths like this:

> https://example.com/sites/default/files/styles/profile\_pic/public/pics/41207/image.jpg?itok=cdQrU8Rv

The *Referrer* is my "manage pictures" page, which allows users to add a **Picture** content type which includes an **Image** field.

So, it looks like session\_start() is having trouble during uploads. Is there a standard fix fox this kind of problem?

# Answer
> 0 votes
I'm also getting the exact same issue on a Pantheon hosted site. This is on a more complex content type (number of fields) with the image field using the multiupload\_imagefield\_widget module so we can upload multiple images. The error can also appear on removing an image, where the image field is updated via AJAX. Occasionally, a WSOD will occur.

Location or Path always relates to files/styles/....

Tried to duplicate this on a basic content type but it was not occurring. The issue appears on the main content type 80% of the time.

---
Tags: files, media
---


# Question
Title: How to add an ascending row number (using some token) in front of each row in Views?
I can't figure out how to make a soccer league table that would look like this: http://prntscr.com/8va7h7

This is how the table looks now: http://prntscr.com/8va8eu

Everything works but I don't know how to show the team position on the table. Is there a way to make this work using tokens so they count the number of rows?

# Answer
> 2 votes
In your View add a new Field, Filter by Global and select:

> **Global: View result counter**
>
> *Displays the actual position of the view result*

Click the *Apply* button and if you want change the output select *Rewrite the output of this field* in the *Rewrite results* section, and in the *Replacement patterns* section you will see the `[counter]` token as:

> \[counter\] == Global: View result counter

---
Tags: views, tokens
---


title: Use a Token in Minimum Field

text:
# Question
Title: Use a Token in Minimum Field
I am new to rather new to Drupal (coming from Django/Python), and was wondering if there was anyway I could use a token in the minimum field of my registration.

What I basically have is a registration from, which is then a field in one of my content types. In this content type I also have a field called **minimum deposit**. So I wondering if I could somehow link the value in the minimum deposit field to the minimum in my registration? Like for the minimum value have: `[node:minimum_deposit]`.

# Answer
In a nutshell, there is no way that I know to do this with a token. You need to create a custom module that implements `hook_form_alter()` to set the default value of your minimum deposit field before the form is rendered. You'll set this default value using the value of the field in the pre-existing node (you'll need to load the node programmatically within the hook function and get the value of the field).

I could give you more details if you let me know what type of form you are using: are you creating a form programmatically with Form API? Using Entityform module to create the form? Using Webform module? Using the "Add to Cart" form provided by the module Drupal Commerce? Post a comment below and I'll edit this answer.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to share saved data from 2 different input fields
This is hard to explain...but i will try.

I want users to be able to input their age in 2 different ways:

1. Date of birth field (this will display age with computed field)
2. Age with drop down integer (age from 18-99)

I want the age to be displayed on the same field in the User View Display.

Please ask for clarification if not clear.

# Answer
You can use this code to compute age from *date field*:

```
    //compute age
    $bdayunix = strtotime($data->node_data_field_role_field_birthdate_value);
    $nowunix = time();
    $unixage = $nowunix - $bdayunix;
    $age = floor($unixage/ (365 * 24 * 60 * 60));

    print $age;

```

I hope these links will also help you solving your problem:
> 0 votes

---
Tags: entities
---


title: How to disable profile2 types?

text:
# Question
Title: How to disable profile2 types?
I have some types provided by the Profile 2 module that I want to disable, but not delete.

How can I accomplish this?

# Answer
As far as I know the only way would be to disable permissions for viewing or editing the profiles for specific user roles. Those roles won't be able to see them.

There are a few "things" that can be disabled (without deleting them) in Drupal - Views and Panels are some of them.
> 0 votes

# Answer
May it can help you

Profile2 Privacy

> This module extends Profile 2 by allowing administrators to create privacy levels as predefined groups or sets of profile fields on a per role basis. Users can then select from among the privacy levels to apply access control to their profile.
> 0 votes

---
Tags: users
---


# Question
Title: Workbench Moderation - intermittent save / autosave without new revision
I'm stuck with a problem while using **workbench moderation**. while working on a node, my client wants to save / auto save his work but if he hits the default save button then it is creating a **revision** (which is unwanted, since his work is not finished yet).

how is it possible for admin to save their content while they are still working on it, something like "**save as draft**", which they can continue later?

is there a way in **workbench moderation** to have it create a revision only when the moderation state is changed? If not, is there any other module which works with workbench to **auto save / save** the work without creating a new revision.

I also need the admin to stay on the same edit page when he hits this save button. I tested "**save & edit**" module, which does what I need but it also creates a new revision, which is not required.

please help!

# Answer
> 0 votes
You can do it by using these modules :

Save Draft

> Save Draft adds a 'Save as Draft' Button to the node\_form for content types, allowing the user to click the 'Save as Draft' button to save the node as a draft.

Draft

> The Draft module provides the ability too create drafts of existing nodes as well as new nodes before you have saved them.
>
> The module utilizes the jquery.fields plugin to serialize all of the information and then the information is stored in a database row serialized.
>
> The module provides the ability to **autosave** the content without the user having to hit the Save as Draft button on the form.

---
Tags: workbench
---


title: Admin theme creation in Drupal

text:
# Question
Title: Admin theme creation in Drupal
I am new to drupal and I have a task to create a custom admin theme. I read a lot of tutorial to how to create a theme in drupal and I am familiarize with that. But never see how to create a new admin theme. I also wanted to customize the default `<input type ="text"....>` fields with custom css. Thank you in advance.. :)

# Answer
For **Admin Theme**

1. Create a custom drupal theme (its already answered).
2. Bring it to your drupal site.
3. Go to **Home » Administration » Appearance**, Select your theme in **Administration theme** select box and save
> 1 votes

# Answer
**Create A Custom Theme/New theme (Drupal Tutorial)**

This one shows how to create a **Custom Theme** for your drupal site.

1. Create custom.info file
2. Enable the theme
3. Create page.tpl.php and style.css file
4. Bring in the Drupal
5. Some refining
6. The final files

**1. Create custom.info file**

* Create a folder custom in your **sites/all/themes** folder
* Inside it create a file `custom.info` with these lines:

\**name = Custom Theme

core = 7.x

engine = phptemplate\**

**2. Enable the theme**

* Go to **Appearance** and click '**Enable and set default**' for the **Custom Theme**

**3. Create page.tpl.php and style.css files**

* Create a folder templates in your **sites/all/themes/custom** folder
* Inside it create a file `page.tpl.php`
* Inside the `page.tpl.php` we create our html document for the layout.

**4. Bring in the Drupal**

* Let's do the **navigation** first.
* Go to **Structure | Menus** and add our **navigation links** in Main menu

for more details
> 0 votes

---
Tags: theming
---


# Question
Title: SQL injection and lot of database updates are visible
My Drupal Website is possibly compromised through a SQL injection and lot of database updates are visible. How to avoid further SQL injection?

# Answer
Install Security Review for maintaining security of your website. Or if you have custom modules, make sure form handling is done only via drupal forms.
> 1 votes

---
Tags: security, database
---


# Question
Title: Webform: How to prevent rendering of private fields
I'm using Webform. Because I wanted to add custom flag for submitted data, so I used this approach with **private fields** https://drupal.stackexchange.com/a/137847/24385

Is it possible to render such form without private field only on my web? In admin section is everything ok and don't want to change nothing here. Private fields are shown only to users with results access. But what can I do if I want to display the same form for all users. On the web it doesn't matter for me whether user is anonymous and logged in. I need to display form without private fields here. Private fields are important to see only in admin section.

Thanks a lot :)

# Answer
I've found that best solution is to use `hook_form_alter` to remove element from rendering. It can be achieved by this workaround: `$form['submitted']['my_field']['#access'] = FALSE;`
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: How to retrieve profile2 form fields using rest services?
We've created a registration form using the Profile 2 module. I want to render this form on an Android app and because of that I want to retrieve the form fields using the rest services.

My question: is there a way to retrieve form fields with their type so that I can write a module on android side to display the form based on the fields type?

For example: If the field type is textfield on the drupal side, I'll be creating a TextView on the android side.

I want to retrieve data in **JSON format** because

1. I want to parse the **form-data**
2. I want to create a list of field. Each field should have a type.
3. Once I have the list of fields, I'll be creating similar fields on the mobile side according the android form interface.

# Answer
No, the Services module only returns a **JSON/XML** representation of the data. It doesn't render an HTML form or associated fields (nor Android views/elements). It also doesn't provide metadata about the fields, just data values.

**Services** can be extended though (see the included `.api.php` files), so it would be possible, if a bit long-winded, for you to implement this yourself. You could expose a resource which queries the `field_info` and `field_info_instance` tables for metadata about the fields, for example.
> 1 votes

---
Tags: users, services
---


# Question
Title: How to give default today date value in exposed filter?
I am using exposed filter condition for **date field in views**.

I want to see the **data in view by current date** as default ..for that i am trying to give date field should be default by today date and when i click on date filter and select on previous date i should see the previous data..

Is this possible by filters.

# Answer
Yes it is possible.

1. Choose the date field in Filter Criteria section in Views
2. On the RHS of your date filter settings, you will see a section to enter a default relative date (*refer screenshot*)
3. Choose 'Enter a relative date' & enter the relative date as 'today'
4. Apply the filter & Save the view
> 2 votes

---
Tags: 7, views, datetime
---


# Question
Title: Taxonomy as exposed Filter -> showing extra Field
I have a taxonomy with german umlauts in terms. This taxonomy I use as exposed filter in a view (with better exposed filters). To work with views arguments I named the terms WITHOUT umlauts (Oesterreich for Österreich). And I have an extra field where I have the names WITH umlauts.

Now I want to get the values of these fields shown in exposed filters to have the correct spelling.

Does anyone know how I can get this done?

# Answer
I found my solution:

With views reference filter I created a view with taxonomy terms. I added the field WITH umlauts and added this view as filter in my actual view: taxonomy term (referenced). In the next step I selected the refernce filter view.
> 0 votes

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


# Question
Title: How to fix my String Translation error in my selection list value?
I am using the String Translation module (part of i18n) and I have added new string in Italian language.

Example: Data d'inizio

Output:

So instead of translated text Data d'inizio its shows me the drop-down text.

How to fix this issue?

# Answer
> 0 votes
This can be fixed via a `hook_form_alter`, in which you loop through all select list options and run the option text through `decode_entities()`.

Refer to HTML Encoding in Drupal Entity References for more details, which also includes this code sample:

```
function misc_form_alter(&$form, &$form_state, $form_id) {
 $to_fix = array('field_reference');
 foreach($to_fix as $fix) {
   if (isset($form[$fix]) && isset($form[$fix][$form[$fix]['#language']]['#options'])) {
     foreach($form[$fix][$form[$fix]['#language']]['#options'] as &$text) {
       $text = decode_entities($text);
     }
   }
 }

```

}

---
Tags: i18n-l10n
---


# Question
Title: It is safe to store custom information in the data field of a commerce_order or commerce_line_item entity?
I have this

```
 line_item = commerce_line_item_load($form_state['line_item']->line_item_id);
            dpm($line_item);
            $line_item->data['data_custom']['name'] = $form_state['values']['name'];
            $line_item->data['data_custom']['phone'] = $form_state['values']['phone'];
entity_save('commerce_line_item', $line_item);

```

It is save? In theory I'm only the only one to work with this data, other modules should not even care about that being there, right?

# Answer
> 1 votes
Yes, you can do that.

That information is commonly used to store context or other information. For instance, you can use the `$order->data` to store transaction IDs or other relevant information that you might want to use later on in the lifecycle of the order. In some cases, `$line_item->data` might store remote keys or other information related to that line item specifically.

Just be very careful that you don't store something in there that you wouldn't want to otherwise store in your database: credit card numbers or other things that you wouldn't want if your security were ever compromised or a database backup fell into the wrong hands.

---
Tags: commerce
---


# Question
Title: How do I programmatically create a view whose structure is defined at runtime?
I know I am able to create a view programatically here: "How do I programatically create a view?" \- only this requires knowing the structure of the view (e.g. which fields / filters / relationships to use) already.

How can I dynamically create a view at runtime? Either the view would get stored in the same place as typical views (in the views database) - or it could exist 'In code' except the code is dynamically generated. E.g. is it possible just to create views ad hoc in `hook_views_default_views()`?

# Answer
> 1 votes
Ok - no answers and I've figured out two ways to do this.

**1. hook\_views\_default\_views()**

One way is to define the view in `hook_views_default_views()` and then to rest the cache for instance with `views_invalidate_cache()`. These views end up being 'in code' but not actually set. This didn't seem like the most desirable method for my use - but might be better for some applications.

**2. save the $view**

Create the view e.g. `$view = new view();` and fill all the fields, and then `$view->save()` saves it to the views database. Keeping a record of the name of the view allows you to delete it later if necessary etc.

---
Tags: 7, views
---


# Question
Title: Display image from Webform submission using views
I have created webform with title, description and upload file fields. And I have created views to display submission data in a grid view.

For images, it just giving me the image name with URL to image but it is not displaying as an image. I tried everything, but didn't find any solution. Please give me solution for displaying images in views.

# Answer
> 6 votes
**This can not be done with webform module alone.** All you need to do is get help of 2 extra modules.

1. File Entity
2. Views Field View

Further you need to do following things.

1. Download and enable both of the modules and clear the cache.
2. Webform is storing file, not only image. I am assuming here you are only uploading image files, you can further get idea to show any type of file there. So go to Image File Type Display: `admin/structure/file-types/manage/image/file-display` and set the preview/image style. Or if you do not want to change settings for default view mode of the file, download another module Entity View Mode. Go to it's configuration and create specific display and set image style accordingly in file display settings.
3. Create a view of files, it should be a block. and there add contextual filter for the fid and add field "`File: Rendered`". You can set file view mode by this field. For your convenience I'm exporting the view below, you just need to import this.

```
    $view = new view();
    $view->name = 'file_view';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'file_managed';
    $view->human_name = 'File view';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'File view';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Field: File: Name */
    $handler->display->display_options['fields']['filename']['id'] = 'filename';
    $handler->display->display_options['fields']['filename']['table'] = 'file_managed';
    $handler->display->display_options['fields']['filename']['field'] = 'filename';
    $handler->display->display_options['fields']['filename']['label'] = '';
    $handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
    $handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
    /* Field: File: Rendered */
    $handler->display->display_options['fields']['rendered']['id'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['table'] = 'file_managed';
    $handler->display->display_options['fields']['rendered']['field'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['label'] = '';
    $handler->display->display_options['fields']['rendered']['element_label_colon'] = FALSE;
    /* Contextual filter: File: File ID */
    $handler->display->display_options['arguments']['fid']['id'] = 'fid';
    $handler->display->display_options['arguments']['fid']['table'] = 'file_managed';
    $handler->display->display_options['arguments']['fid']['field'] = 'fid';
    $handler->display->display_options['arguments']['fid']['default_action'] = 'default';
    $handler->display->display_options['arguments']['fid']['default_argument_type'] = 'node';
    $handler->display->display_options['arguments']['fid']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['fid']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['fid']['summary_options']['items_per_page'] = '25';

    /* Display: Single File View */
    $handler = $view->new_display('block', 'Single File View', 'block');
```
4. Now in your main view (where you are showing submissions). Add a new relationship for `Webform submissions: Data`. You'll need to set the nid for the webform here and select the image component.
5. Add new field to the view `submission data: Value (raw)`. This will give you the file\_id for the associated file. Exclude it from display.
6. Add another field `Global: View`. Select the view you imported and the block display. In contextual filter set \[!data\] from replacement patterns. It was the raw value of the field which you excluded from the display. And Here you go, save the view and rock :). Thanks for asking such good question. Still if you face any problem during this tutorial, ask me.

---
Tags: webforms
---


# Question
Title: When using drupal_get_query_parameters(), should I still run values through filter_var() or check_plain()?
When absolutely needing to take in query string values, I'm using drupal\_get\_query\_parameters(). However, is it still a good idea to run values through `check_plain()` or `filter_var()`. Or does this drupal function automatically take care of data sanitization for me?

For example, is the `filter_var` with `FILTER_SANITIZE_NUMBER_INT` a good idea, necessary, or redundant?

```
<?php
$params = drupal_get_query_parameters();

// get dept name if exists in query string
if (array_key_exists('exposed_filter_a', $params['field_department_tid'] = filter_var($params['exposed_filter_a'], FILTER_SANITIZE_NUMBER_INT);
    $expfilter_value = taxonomy_term_load($params['exposed_filter_a'] )
}

```

# Answer
> 2 votes
`drupal_get_query_parameters()` doesn't perform any sanitisation of vars at all.

If you need to validate the incoming value, or filter it for XSS before it is outputted, etc., you'll need to do that as normal.

---
Tags: 7
---


title: Views Conditional Range

text:
# Question
Title: Views Conditional Range
I would like to be able to input a range in my views conditional ,

e:g:

```
If (age > 0 && age <= 10)
{
 ...
}

```

How can I achieve this using Views\_Conditional?

# Answer
> 1 votes
In Views, you can add multiple Filters for the same field/column, and configure each one separately. So you can add one filter for "age is greater than 0", and "age is less than or equal to 10". Filters use an AND operator by default, so you should be all set with that, but FYI you can also change the operator to OR (you can also mix operators).

The only limitation may run into is whether or not "is greater than" and "is less than or equal to" are available options in the filter handler for the particular field you're filtering on. Number fields can do that, as far as I know... but strings can't (for example).

---
Tags: views
---