# Question
Title: Calling /user page with username instead of uid results in database exception due to failed string to int conversion
When I use a username as an url parameter like: 'www.example.com/user/adam' instead of 'www.example.com/user/27' I get a database exception:

> Error message PDOException: SQLSTATE\[22018\]: \[Microsoft\]\[SQL Server Native Client 11.0\]\[SQL Server\]Conversion failed when converting the nvarchar value 'adam' to data type int.: SELECT base.\[uid\] AS \[uid\], base.\[name\] AS \[name\], base.\[pass\] AS \[pass\], base.\[mail\] AS \[mail\], base.\[theme\] AS \[theme\], base.\[signature\] AS \[signature\], base.\[signature\_format\] AS \[signature\_format\], base.\[created\] AS \[created\], base.\[access\] AS \[access\], base.\[login\] AS \[login\], base.\[status\] AS \[status\], base.\[timezone\] AS \[timezone\], base.\[language\] AS \[language\], base.\[picture\] AS \[picture\], base.\[init\] AS \[init\], base.\[data\] AS \[data\] FROM {users} base WHERE ( (\[base\].\[uid\] IN (:db\_condition\_placeholder\_0)) ); Array ( \[:db\_condition\_placeholder\_0\] =\> adam) in DrupalDefaultEntityController-\>load() (line 196 of C:\inetpub\wwwroot\includes\entity.inc).

I use pathauto which uses the following pattern for user account page aliases: users/\[user:name\] and that works fine. I just stumbled upon this error when testing the site before deployment. I'd rather not have this error visible to users which might try to navigate to /user instead of /users.

Since it only seems to be legal to use actual uid's when calling the /user/ subpage (aside from the login and logout pages etc.), what can I do to prevent drupal from trying to parse a username as an int and producing this error? Is there some redirect I can perform?

# Answer
There are two sides to this question.

First, you should not get this error message. It should be good old 404 page or Drupal's error message about invalid argument. It's either a bug in database backend for MS SQL and belogs to their queue, or in your version of MS SQL RDBMS and belongs to Microsoft technical support. Or you simply need updates.

Second part is - out of the box only numerical URLs works.You neet to create aliases with username. It can be done automatically, Pathauto's default setting is exactly:

> Pattern for user account page paths
>
> `users/[user:name]`

Sadly, unless you get the first part fixed, it will only help with *valid* users, people will still get ugly message if they'll hit a name that does not exist, by typo in their address bar for example.
> 0 votes

---
Tags: redirection, path-aliases
---


# Question
Title: How do allow an exposed filter to override another filter in Views?
I have a view that display content on the site. I have the following hidden filters on it:

```
Published: Yes
Posted Date: Relative 'today'

```

Then I want to add a second `Posted Date` filter but expose it for a user to enter their own custom dates `Is between` `Start date` and `End date`. I then want the view to ignore the hidden exposed filter that is set to 'today' and use the user defined dates.

EDIT:

The default one is a relative date format and the exposed one is to be a jquery date popup.

Thoughts?

# Answer
> 1 votes
the question, 'allow an exposed filter to override another filter in Views?" is answered by using filter groups in which you are able to say this filter OR that filter quite easily with Views UI. Check out part 15 of Learn Views with NodeOne (5 min). You will need to great two groups, one for each filter, and then you can order them for OR.

The the two filters are pretty straight forward too. A single one with your relative "today" and a grouped one with your less than and greater than operators and fixed rather than relative time. The Views UI is slick for this too so I wont suck up space with step by step.

As for the jquery date selector, I believe an exposed filter with Date Views and Date Popup installed your "magically" taken care of.

# Answer
> 1 votes
You can modify the view paramteres implementing hooks\_views\_pre\_build. There you can examine received data (for example, checking $\_GET) and modify view filters, deleting the "Posted Date: Relative 'today'"filter.

```
function mymodule_views_pre_build(&$view) {
  if ($view->name == 'my-view') {
    if (must_delete_filter()) {
      unset($view->filter['posted_date_relative_filter_name']);
    }
  }
}

```

So Views is executed without that filter. In example code must\_delete\_filter is the function that decides if filter must be deleted or no.

# Answer
> 1 votes
How about not using a hidden filter for the date. If you you expose that filter and give it a default of 'Today', then the user can override the default or keep it as is. Thus, there is no need for multiple filters.

# Answer
> 0 votes
It is possible to create custom module which will add new filter to a view. Have a look a hook\_views\_api(), then use hook\_views\_handlers() to register custom view handler, use hook\_views\_data() - to create a filter and show it in views and finally create a class that extends views\_handler\_filter(). Looks complex but it isn't. I've implemented date ranges using this technique (for nodes created today, yesterday, last week, last month) but it will work for anything ;)

---
Tags: views
---


title: Include panel in view?

text:
# Question
Title: Include panel in view?
I have a view that is shown in the footer of a theme (Lucid & Nodestream Features?). Since my task and scope is small, I do not what to change up everything - just use what is there. I want to show panelized node or a panel page in the header and footer of the footer view. I have tried "Entity: Rendered entity", but I just get the node's fields and not the panel layout & content.

How do I include a panel (3.3) in a view (3.7)? (not view in a panel)

# Answer
> 1 votes
The views were supposed to be displayed in the panels not viceversa. Why not created a panel with header and footer for placing views instead?

# Answer
> 0 votes
Though you should load view in panel and loading a panel from theme is not at all good option Still you could try something like this : http://drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/panels\_load\_display/7

# Answer
> 0 votes
One can easily include mini-panels in a view but I can not find anything on displaying a panel layout in a view header. The settings suggest that one can do as much. But I also finally realized that the footer view was not coded in the theme but was content of a site template page. For now the question does not need answered.

---
Tags: views, panels
---


# Question
Title: Retrieve / call facet blocks from non search page
I am trying to load full facet blocks on non search page to put them in cache.

What I am doing is looping through items with taxonomy $tid, then

```
$params = array('fq' => 'tid:' . $tid);
$current_query = apachesolr_drupal_query('apachesolr', $params, '', 'search/site');
$response = apachesolr_do_query($current_query);
$facet_block = module_invoke('facetapi', 'block_view', $block_id);

```

When I dsm $response-\>request, on each iteration I always see the first $tid in the query string ("q.alt=tid..."). The result I get is the same block for every terms, on each apachesolr\_do\_query requests.

Anyone got a clue on what is going on there ? The purpose of this is to generate cached facet blocks from non search pages, for several tid as the apache solr search parameter.

# Answer
The problem is, apachesolr\_do\_query checks if a query has already been made:

apachesolr.module line 1470 :

```
  // Verify if this query was already executed in the same page load
  if ($response = apachesolr_static_response_cache($searcher)) {
    // Return cached query object
    return array($query, $response);
  }

```

So, all you have to do to process multiple ApacheSolr queries is to reset the Drupal static variable like so:

```
drupal_static_reset('apachesolr_static_response_cache');

```
> 1 votes

---
Tags: 7, caching, search
---


# Question
Title: How do I schedule a reminder email with Rules to users that have flagged an event?
* I have a content type: `event`
* It has a single date field: `date`
* It has a flag on it: `reminder`

When the user flags the node, I want to schedule a rule to send them an email the day of the event.

Can someone walk me through the steps on how to do this?

Edit: I have now gotten as far as being able to schedule the email

This is what I have so far.

Add new component \- Type: `Action set` \- Name: `Send reminder email` \- Data Type: `User` \- Data Type: `Node`

Add action \- Send reminder mail \- To: 'user:mail' \- Subject: `Don't forget about [node:title]` \- Body: \- Don't forget about \[node:title\] tomorrow!

Create new Rule \- Name: Schedule reminder email \- React on Event: A node has been flagged, under "Remind"

Condition: Entity has field Data Selector flagged-node Field: Date

Action: Schedule component evaluation Action set: Send reminder email

# Answer
Sounds like you know how to set up the Flag. Triggering a Rule with Flag is piece of cake and NodeOne has an create 15min tutorial covering all the details. They also have all the needed training on Rules if your fuzzy about Rules in general. Once your ready to set up your rule and you have the event to trigger it, you can set up the email action following a recipe similar to this other answer. In your case you have the future event. Lullabot has a tutorial specifically on the Rules Scheduler.
> 2 votes

# Answer
Problem with this kind of rules setup is finding event when the action will take place. Rules scheduler has been talked on drupal.org & there are some bit of documentation at https://drupal.org/node/517674. It may help you.

There are other option to do it by help of your own module by implementing hook\_cron to fire e-mail on such condition which will be met by DB query condition given by you.
> 0 votes

# Answer
You can add flag on your node called "reminder users" to send bulk emails. create rule on that flag so that rule will run once the flag update. in rules action. fetch users who flagged this node for attending this event. next create a loop to add users emails into your list and use send HTML e-mail into same loop to send email to all users who flagged this node.
> -1 votes

---
Tags: rules
---


# Question
Title: How do I get a block and its content commited to a Git repo?
Let's say I have created a block with some Full HTML (Facebook Feed) text inside. How can I commit the block and its text content into my Git repository, so my co-workers can pull it?

# Answer
Turn it into a Feature. Bad thing is, it does not work on built-in custom blocks, so you need to use Boxes to get it work.

That way, you can export block as a module, and modules are text files, so GIT accepts them with it's full support.

Then, there is Features to Git module. It claims:

> Features to Git allows trusted users to write features directly to disk, commit them to git and push them to a remote. This makes it possible for site builders to be able to manage features in git without having to get their hands dirty on the command line.
> 7 votes

# Answer
Create a module for that block using the Features module and then commit that module on to the GIT repository of yours.

For more information you could read the README.txt of feature module from.
> -1 votes

---
Tags: 7, blocks, version-control
---


title: 2nd block not showing up in D7

text:
# Question
Title: 2nd block not showing up in D7
I'm building a module with several blocks. But only one is showing up in blocks list. Calendar shows up in block list but could you see why I cant see my 'frontdoor' block ?

```
function businesshours_block_info() {
    $blocks['calendar'] = array (
        'info' => t('Little calendar'),
        'status' => true,
        'visibility' => 1,
        );
    $blocks['frontdoor'] = array (
        'info' => t('The Front Door'),
        'status' => FALSE,
        'visibility' => 0,
        );
    return $blocks;
}
function businesshours_block_view($delta) {
    $block = array();
    switch ($delta) {
        case 'calendar':
            $block['content'] = businesshours_block_contents($delta);
            $block['subject'] = t('toto');
            return $block;
            break;
        case 'frontdoor':
            $block['content'] = businesshours_block_contents($delta);
            $block['subject'] = t('front');
            break;
    }
    return $block;

}
function businesshours_block_contents($delta) {
    switch ($delta) {
        case 'calendar':
            return array('#markup' => '<div style="width:8.2em;margin:auto;">' . _build_calendar() . '</div>');
            break;
        case 'frontdoor':
            return array('#markup' => '<div style="width:8.2em;margin:auto;">' . _build_frontdoor() . '</div>');
            break;
    }
}

```

Thx in advance.

# Answer
> 0 votes
Remove the `return $block` in `case 'calendar'`

```
function businesshours_block_view($delta) {
$block = array();
switch ($delta) {
    case 'calendar':
        $block['content'] = businesshours_block_contents($delta);
        $block['subject'] = t('toto');
        break;
    case 'frontdoor':
        $block['content'] = businesshours_block_contents($delta);
        $block['subject'] = t('front');
        break;
}
return $block;
}

```

NOTE: Also check your visibility

Possible values are:

> BLOCK\_VISIBILITY\_NOTLISTED: Show on all pages except listed pages. 'pages' lists the paths where the block should not be shown.
>
> BLOCK\_VISIBILITY\_LISTED: Show only on listed pages. 'pages' lists the paths where the block should be shown.
>
> BLOCK\_VISIBILITY\_PHP: Use custom PHP code to determine visibility. 'pages' gives the PHP code to use. Most modules do not provide an initial value for 'visibility' or 'pages', and any value provided can be modified by a user on the block configuration screen.

# Answer
> 0 votes
Their is no hook for content in blocks.U cant use $delta in content of block type. U have to use different functions for each of the block type.

Eg:

```
function businesshours_block_view($delta) {
$block = array();
switch ($delta) {
    case 'calendar':
        $block['content'] = businesshours_block_content1();
        $block['subject'] = t('toto');
        return $block;
        break;
    case 'frontdoor':
        $block['content'] = businesshours_block_content2();
        $block['subject'] = t('front');
        break;
}
return $block;
}

function businesshours_block_content1(){

  return array('#markup' => '<div style="width:8.2em;margin:auto;">' . _build_calendar() . '</div>');

}
function businesshours_block_content2(){

  return array('#markup' => '<div style="width:8.2em;margin:auto;">' . _build_frontdoor() . '</div>');

 }

```

# Answer
> 0 votes
It is not clear if you cannot see the block in the region on your page or in the Manage Blocks administration page. I am assuming you can't see it on your site pages (not the Manage Blocks page).

The reason you would not see `frontdoors` block on your site is that you have set status to FALSE. Unless you move the block to one of the theme's regions, you will not see this block.

---
Tags: 7, blocks
---


title: E Newsletter sign up form

text:
# Question
Title: E Newsletter sign up form
I would like to create a sign up form for visitors to my site to receive an e newsletter. One of the stakeholders in the project has specified some additional functionality in that he wants an email to fire to the user after they have completed to form that asks them to validate their details and confirm they wish to receive the email prior to said details being stored on Drupal.

Is there an off the shelf solution anywhere in the community, or will I have to create something from scratch?

I have done a (very) quick search, which yielded no results - if someone has seen something/ heard of something that will give this functionality I would appreciate hearing about it.

Many thanks.

# Answer
There is Simplenews module

> Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.

Read documentation
> 2 votes

---
Tags: forms
---


# Question
Title: Running two Drupal sites off the same database: Is it possible?
Is it possible point a second Drupal site to an existing Drupal database, if that second site is only used to browse the content, no logins, registrations or content add/edit/deletes?

# Answer
> 5 votes
Is it possible? Yes. Should you do it? Probably not.

Using table prefixes, you can run two completely separate sites with table names like "site1\_node" and "site2\_node", so they don't collide. In your case, it sounds like maybe you also want to share data between the sites?

On solution to that, is to share tables between these two, but I strongly recommend *against* that. I've tried it on two different sites, and I've mostly gotten bit badly by it. Use Domain instead, to run two domains from a single Drupal install.

# Answer
> 2 votes
This is perfectly possible. Look for instructions about multisite installations combined with the domain module. Both sites can have common and separate settings, and both sites can have write access.

To set-up everything, you also need to configure your DNS settings and your server settings appropriately.

# Answer
> 1 votes
I have not tried it, but I think that you can use two different databases which replicate with each-other. I think that this may be a better option than using the same database for two different sites. Master-slave replication in MySQL is very easy and it can be managed from phpMyAdmin.

# Answer
> 1 votes
Yes, you are able to maintain multiple sites with single drupal installation. Please check this article: How to install multiple domains in a single Drupal installation.

---
Tags: 7
---


title: How to nest form into another form?

text:
# Question
Title: How to nest form into another form?
I have 2 modules. Let's call them Publisher and Publication for discussion's sake.

Publication module requires Publisher module. Publisher module provides form to edit publisher's data. Publication module provides list of publications with reordering and adding capability, and it can be limited to display only publications by one publisher.

Now, I want to nest publisher's publications form at the bottom of his data edit form. I would prefer to avoid writing same code again - I want to keep validation functions and submit functions as they are now, just have it on one screen, with one submit button.

Subform seems to be unmaintained and buggy at this point and Multiple forms seems to skip validations altogether, that makes both of them unusable for me.

# Answer
> 3 votes
You can use the admin/content page as a reference to combine forms. There, the filter form and overview form are passed as elements in a new $form array.
Coming from the content administration callback function in the node.admin.inc file:

```

/**
 * Menu callback: content administration.
 */
function node_admin_content($form, $form_state) {

  $form['filter'] = node_filter_form();
  $form['#submit'][] = 'node_filter_form_submit';
  $form['admin'] = node_admin_nodes();

  return $form;
}

```

---
Tags: 7, forms
---


# Question
Title: How should I include an image field from a taxonomy term in a node view?
I'm creating a site with just one content type sorted in three categories and posted by three different organizations (no matter in which of the categories). The front page has to be three columns displaying the content of each category.

The nodes has to be distinguished by the logo of the organization. I'm trying to solve it by managing the organization as a taxonomy and creating an image field for each organization/term; when I deal with the view, I find that I just can use as field the name of the taxonomy and not the image (creating a view of node type of course).

How can I achieve it?

# Answer
If you're using Drupal 7 then you will have to add a **"Content: Taxonomy terms on node"** relationship before attempting to add the term image field. When you add the relationship then in the Fields section you will be able to choose term fields (like the image field of your terms) to display them in your content view.
> 1 votes

---
Tags: views, media
---


title: Change drush language

text:
# Question
Title: Change drush language
Suddenly my drush has switched language and displays error messages in my native language, which is unfortunately not convenient if one tries to search for solutions on these errors.

Do you know how to switch the language of drush errors back to English?

# Answer
Adding the following string to `drushrc.php` worked for me with Drush 5.4:

```
$options['variables']['language_default']->language = 'en';

```

In my setup I placed `drushrc.php` into sites/default/drushrc.php, for other possible locations see documentation in `examples/example.drushrc.php` in Drush installation directory.
> 4 votes

# Answer
Create (or modify) your drushrc.php file and add an option for your default language:

```
$override = array(
  'language_default' => (object) array(
    'language' => 'en',
  ),
);

```
> 3 votes

---
Tags: drush, i18n-l10n
---


# Question
Title: The best way to debug a custom token module development
I'm building a custom module to build some tokens. I have added `hook_token_info()` and it works great. I haved added `hook_tokens()`, but I'm not able to debug with `var_dump()` or with `dpm()`.

```
function mymoduletoken_token_info() {
  $info['tokens']['node']['seccion'] = array(
    'name' => t('Seccion'),
    'description' => t('Custon token to add to the G.A. script more optoins in seccion'),
  );

  $info['tokens']['node']['subseccion'] = array(
    'name' => t('Subseccion'),
    'description' => t('Custon token to add to the G.A. script more options into subseccion'),
  );
  return $info;
}

function mymoduletoken_tokens($type, $tokens, array $data = array(), array $options = array()) {
  dpm($type);
  dpm($token);
  dpm($data);
  dpm($options);
}

```

I would like to debug the different options to build the token with the information I need.

# Answer
> 6 votes
I think I'm following you...you want a way to invoke the tokens you've created outside of their natural context, so you can debug easily? If so, you can use the `token_replace()` function. As you're defining tokens that need a node object, you'll have to load an appropriate one up for the job:

```
// Load the node.
$node = node_load($appropriate_nid);

// Prepare the text string.
$text = 'something involving [node:seccion]';

// Set up some options. Your mileage may vary here.
$options['sanitize'] = FALSE;

// Get the replacement text.
$replacement = token_replace($text, array('node' => $node), $options);

```

That will invoke your module's implementation of `hook_tokens()`, and the `dpm()` calls will fire.

If you're doing a lot of token development it might make sense to wrap that functionality in a simple form.

---
Tags: 7, tokens
---


# Question
Title: How to remove form elements before submitting the form?
All form items in Drupal must be created with Form API, otherwise form values in `$form_state` and in `$_POST` variables are empty after submitting the form.

But sometimes I need to have in form some other items, not created with Form API. For example I want to use external jquery plugin like Pickadate (similar like datepicker). This js plugin adds some HTML form elements into object. And many other js plugins creates their own form elements on client side.

But when I use these plugins, form sent empty values after submitting. So before submitting the form, I need to remove these custom elements from form. I don't need values from these elements, they just help to pick the value selected by user.

Is there any workaround, some event, that can help me remove these elements right before submitting the form?

# Answer
There are two ways, actually:

* Wrap them into a proper modules. You will avoid conflict with Form API by cooperating with it. See Datepicker's code to get idea how to do it.
* Create onsubmit javascript event and remove elements with jQuery.
> 0 votes

---
Tags: forms
---


title: How to add Google Analytics per theme?

text:
# Question
Title: How to add Google Analytics per theme?
Is there a way to add GA per theme. The reason for it is I am using themekey to switch the theme for mobile users.

I have read that it is possible to add more than one tracking code on a site but would like to split them between Main and Mobile.

# Answer
> 4 votes
To add google analytics to every theme,some manual work is required as:-

1. In your theme's folder ,
2. select a theme in which you want to add google analytics
3. open the theme folder and then create a folder for js files
4. create a js file and include the code provided to you by google for google analytics.
5. save the file and this way google analytics is installed in your theme.
6. follow the same procedure for rest all themes.

---
Tags: 7, google-analytics
---


# Question
Title: How to get values of delta field from "block" table in drupal 7 from the database for the activated theme in a custom module?
Can I get all the values of delta field from "block" table from the database in my custom module

I have tried with this code as clive has explained it here but it shows me an error:

```
 $query = db_select('module__block', 'b')
  ->condition('theme', $business)
  ->condition('status', 1)
  ->condition('region', -1, '<>');

    $query->addExpression("CONCAT('_', delta)", 'delta');
    $deltas = $query->execute()->fetchCol();
    print_r($deltas);

```

`module__block` : Is the name of the block table since I attached a prefix to it.

# Answer
> 0 votes
```
SELECT delta,
FROM  `module__block`
WHERE theme LIKE  'business'
LIMIT 0 , 30 ;

```

shows only blocks.

SELECT delta, theme FROM `module__block` WHERE theme LIKE 'business' LIMIT 0 , 30;

It will shows both the block names and theme name.

---
Tags: 7, database
---


# Question
Title: Setting $cookie_domain variable for specific folder structure
During configuration of Ckeditor I have to setup the cookie domain variable. I have added my site in subfolder like www.example.com/mynewsitefolder, where www.example.com is my current and running site.
First I tried something like `$cookie_domain = '.example.com/mynewsitefolder';` but that doesn't allow me to log in.

How can I set it, so it works on a sub-folder?

# Answer
> 6 votes
The short answer is that you cannot set cookie domain to such a value. See http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain

As a workaround, you can use this in settings.php (around where `$cookie_domain` is set:

```
$cookie_domain = ".example.com";
// Set cookie_path ourselves as Drupal doesn't.
ini_set('session.cookie_path', '/mynewsitefolder/');

```

`$cookie_domain` is eventually used to set `session.cookie_domain` but there is nothing in Drupal code base to set `session.cookie_path` and so we directly set that in settings.php itself.

---
Tags: cookies, configuration, subsites
---


# Question
Title: how to include globals.php in template.php file
I need the variables from the globals.php and I can't seem to call/register them in theme's template.php file. These variables are needed for my custom hook function for the template. Am i missing something (since it's been global and be called somewhere else during rendering)?

# Answer
> 0 votes
1.in order to include entire file into some other file,we have 2 functions in php:-

a) include('filename'):this function will include the file and if any error occurs during the importing of the file,then the script will not stop and will continue with its execution.

b) require('filename'):this function will include the file and if any error occurs during the importing of the file,then the script will stop.

include() function is recommended for including files.

---
Tags: theming
---


# Question
Title: See what database a site is connected to
Is there a page in Drupal 7 (or a module) that will show me what the name of the database is that the site is pointing to?

I know this can be done via settings.php, but I am setting up a build procedure that I can have lower level developers (or even non-developers) handle and a UI would be better. I recently had an issue with two sites pointing to the same database and it borked some things up. I want to add checking this setting to our build procedures.

# Answer
> 3 votes
I think this is what you are looking for:

https://drupal.org/project/show\_database\_name

> Display the host and database name of the default database on the status report, toolbar (Drupal 7) and/or on the admin\_menu bar if enabled (either Drupal 6 or 7) and/or in a block (to use with the admin module).

It is marked as dev but it looks like a simple use-case and I don't expect there should be any problems.

---
Tags: 7, configuration
---


# Question
Title: How to track site search with using Google Analytics without installing additional modules?
I need to enable the tracking of site searches in Drupal 7 using Google Analytics without installing the additional "google\_analytics" module.

So far, I find some info (some previous question in this site, in example) about performing this task using that module, I just want to know if I can do that without it?

(Edited to add.) I found some info regading the "query parameter" to set in the GA site. I found it is recommended (http://www.wesjones.net/home/2010/11/track-drupal-site-search-in-google-analytics) to use "search" as query parameter, but I was thinking that the parameters would be something like "search/node" and "search/user". Any ideas D7-related?

(Edited to add.) I select the first reply as it effectively solves my initial question. Later I added a second one but it is kind of a different one. And maybe it is valuable to not mix things up.

# Answer
> 2 votes
I think the module serves well, but if you don't want to use the module for some reason, you can always create a new block and copy/paste the code provided by Google Analytics in there. Make sure you select the **Text Format** as `Full HTML` or similar which doesn't strip out `<script>` tags.

And of course, enable the block and move it to a footer region.

# Answer
> 1 votes
The only way you can do that without installing the module is to copy the google analytics script into a block and place it at the footer of your site.

# Answer
> 0 votes
Or if you understand theming, you can copy the script below the footer of your page.tpl.php file. That's assuming every page on the front end of your site uses the same page temmplate file. You would need put this code in every page template file.

Or even better. Make a copy of the html.tpl.php file from the modules/system/ folder and copy that into your theme. Paste the anayltics code above the . Be sure you clear your cash once you are done.

---
Tags: 7, search, google-analytics
---


# Question
Title: Drupal 7 module for Password Complexity Rules
For a Drupal 7 site the customer would like to implement the following (see at bottom) Password Complexity Rules. Which of the below rules are possible to implement and what would be the best module to use for these rules?

---

* The password must be at least 12 characters (network enforced)
* The password must contain both upper and lower case characters: a-z, A-Z (network enforced.)
* The password must contain numbers and punctuation characters as well as letters: 0-9, !#$%^&\*()\_+|~=\`{}\[\]:";'\<\>?,./@ (network enforced.)
* The password should not be or contain a word in a dictionary
* The password should not be a common usage word, such as:

+ Names of family, pets, friends, co-workers, fantasy characters, or sport teams
    + Birthdays or other personal information, such as addresses and phone numbers.

# Answer
You can implement this bit of the rules

> The password must contain both upper and lower case characters: a-z, A-Z (network enforced.) · The password must contain numbers and punctuation characters as well as letters: 0-9, !#$%^&\*()\_+|~=\`{}\[\]:";'\<\>?,./@

anything extra is pushing it, plus it is difficult to enforce

You can use this module Password policy for implementing it

> This module provides a way to specify a certain level of password complexity (aka. "password hardening") for user passwords on a system by defining a password policy.
> 6 votes

---
Tags: users
---


# Question
Title: Run a boolean test function on form submit
Is there a way to run a function when a user submits a form in Drupal that returns a true or false. If it is true, run the submission handler. If false, return an error.

Application:

I am using Drupal to run a product booking system. If a product is reserved during a certain period of time, it is not available to others. The client wants the customer to be able to change the dates of the their order. This is fine. The order creates a reservation node and with permissions and `hook_form_alter`, I set it up so that they can edit the reservation dates.

However, I don't want them to be able to change the dates to whatever they want without first checking to see if it is already reserved. I have already written the code to run a query and return a boolean based on whether or not there is a booking conflict. Now I just need to be able to use that on the form submission handler.

# Answer
> 4 votes
You should do this in validation handler. In `hook_form_alter` (or in your form definition function), add `$form['#validation'][] = 'mymodule_form_validate';`. Then, add this code:

```
function mymodule_form_validate($form, &$form_state) {
  if (!mymodule_dates_valid($form_state)) { // Return boolean here.
    form_set_error('date_field', t('Invalid dates'));
  }
}

```

---
Tags: hooks, forms
---


title: Understanding ctools_modal_form_wrapper

text:
# Question
Title: Understanding ctools_modal_form_wrapper
I am trying to get a handle on Ctools ajax modals and I am reading a lot of tutorials. In one of the tutorials (on https://gist.github.com/mrconnerton/1979037), I see the following code:

```
// Create a blank node object here. You can also set values for your custom fields here as well.
$node = (object) array(
'uid' => $user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => 'mytype',
'language' => LANGUAGE_NONE,
);

$form_state = array(
'title' => t('Add my content type'),
'ajax' => TRUE,
);

$form_state['build_info']['args'] = array($node);
// change this to your type node form
$output = ctools_modal_form_wrapper('mytype_node_form', $form_state);

```

I don't understand the function `ctools_modal_wrapper`. What exactly are the two parameters?

On the ctools API, it says they are `$form_id`, `&$form_state` but I'm not sure what

a) the form id is and where it comes from and

b) what a form state means? This might be a question on the forms API itself, and if so, please guide me to understand how this all works.

# Answer
I found a better explanation here so I'm not going to explain much about the `$form_state` itself here.

To present a form, you have to use `drupal_get_form()` function that returns a render-able array of the form. To build the form, you need to give a form ID (to get the form API arrays) and the state of the form. Form State (`$form_state`) becomes handy when you need to store arguments, previous step values, and many more (see the linked post above).

Ctools modal forms has many basic features.

* Detecting whether JavaScript is available in the user's browser.
* Falling back to normal HTML forms if JS is not enabled in the browser.
* Keep form validation and submit functions working in the popup form.
* Executing certain functions when the form is submitted.

Here is an example of a full Modal form menu router item. Note that I'm not using `%ctools_js` menu loaders to make this simple:

```
function quotes_editform_ajax($form, &$form_state, $quote){
  ctools_include('ajax');
  ctools_include('modal');
  $form_state = array(
    'ajax' => true,
    'title' => t('Edit quote'),
    'is_ajax_update' => TRUE,
    'quote' => $quote,
  );

  $output = ctools_modal_form_wrapper('quotes_editform', $form_state);

  if (!empty($form_state['executed'])) {

    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $output = array();
    $output[] = ctools_modal_command_dismiss();
    $output[] = ctools_ajax_command_reload();
  }

  print ajax_render($output);
  exit();
}

```

**Explanation:**

```
  ctools_include('ajax');
  ctools_include('modal');

```

These functions will include specific ctools plugins for our use.

---

```
  $form_state = array(
    'ajax' => true,
    'title' => t('Edit quote'),
    'is_ajax_update' => TRUE,
    'quote' => $quote,
  );

```

Here we build the $form\_state to pass to the form builder function (`drupal_get_form()`. `ctools_modal_form_wrapper()` calls `drupal_get_form()`).

---

```
$output = ctools_modal_form_wrapper('quotes_editform', $form_state);

```

Here, we build renderable array of the form. But the difference between `drupal_get_form()` is that it's actually in Ajax response form. `quotes_editform` is a function that returns a form array.

```
function quotes_editform($form, &$form_state) {
  $form['name'] = array(
    '#title' => t('Name'),
    '#type' => 'textfield',
    '#default_value' => !empty($form_state['quote']->title)
       ? $form_state['quote']->title
       : '',
  );
  return $form;
}

```

In this $form\_state array, `ajax` and `title` keys are ctools-specific. The `title` will be the popup's title and `ajax` is required to Ajax-ify the form. Pay attention to the `#default_value` of the above snippet. If we are going to show an edit form, we need to know the existing values. So we send whatever we have to the form builder function.

Node forms are a little complex that there is a base form and child forms for each form. This form ID is same as what you receive as the third parameter in `hook_form_alter($form, $form_state, $form_id)` hooks.

You are free to store whatever in this `$form_state` array. `$form_state` array is passed to submit and validation functions so any of those functions can make use of those data.
> 4 votes

---
Tags: chaos-tool-suite
---


# Question
Title: How do I record hook_menu() access statistics
I have a standard menu hook function in a custom module which links to example.com/foo/bar, how do I record access statistics for this page?

# Answer
There is no build in stat counter for this. Here is a workaround:

```
<?php
function mymodule_menu() {
  $items = array();
  $items['foo/bar'] = array(
    'title' => 'example',
    'page callback' => 'mymodule_foo_bar',
    'access callback' => 'mymodule_foo_bar_access_with_stat_counter',
    'access arguments' => array('Something', 'Something else'),
  );
}

function mymodule_foo_bar_access_with_stat_counter($something, $something_else) {
  //Log your stats here!
  // goddess_logs_stats_here($something, $soemthing_else);
}

```
> 0 votes

---
Tags: routes, nodes
---


# Question
Title: How to change field values in a view programatically?
I'm working in a custom module that displays date fields. I want to be able to change the date's timezone programmatically.

I've tried implementing `hook_views_pre_render()`, but that doesn't allow me to format the field value. I'd really like to do the theming inside my module code since that's where the logic is regarding my timezone.

As a total hack, I could use `hook_views_post_render()`, but then I'd be doing search/replace on the text and that seems like a poor solution.

What other hooks inside my module are available?

# Answer
Okay, so after a little more googling I found my own answer on a thread on d.o that address this issue with sample code (which I'm condensing a bit):

```
<?php
/**
 * Implements HOOK_preprocess_views_view_fields().
 */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  //Replace 'VIEW_NAME' with the machine_name of your view.
  if($view->name == 'VIEW_NAME') {

    //This for loop iterates over all fields in this view.
    foreach ($vars['fields'] as $id => $field) {

      //Custom formatting logic goes here....

      //Set the field value (not the surrounding tags) here.
      $vars['fields'][$id]->content = 'my new value';
    }
  }
}
?>

```

**NOTE** Make sure you replace "MYTHEME" with the name of your theme or module in order for this work.
> 2 votes

---
Tags: views, theming, 6
---


# Question
Title: How do you render a View with arguments using a Computed Field?
I have a computed field and i want to output a View's - block display with arguments passed into it. Can someone provide me with an example code of how to output a view with arguments?

thanks!

# Answer
> 2 votes
**The long way:**

```
$args = array(ARGUMENTS);
$view = views_get_view('VIEWNAME');
print $view->preview('block_1', $args);

```

**The short way:**

```
print views_embed_view('my_view', 'block_1', $arg1, $arg2);

```

Also keep in mind since this is dynamic data, you will need to uncheck the checkbox on the field settings page or else it will try to store the data thats generated upon saving the node.

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


# Question
Title: How to format CCK fields printed in custom template
I have managed to print date and dollar amount CCK fields on a custom print.tpl.php template file (associated with the Printer, email and PDF versions module), but they are showing up in a different format than how I have them displayed in the CCK field itself.

The date is showing up like this: 2012-06-01 00:00:00
Instead of like this: June 1, 2012

And the dollar amount is showing up like this: 10000
Instead of like this: $10,000

Here are the code snippets:

```
    <?php if(isset($node->field_invoice_due_date['und'][0]['value'])) {
          print $node->field_invoice_due_date['und'][0]['value'];
   }
 ?>

    <?php if(isset($node->field_invoice_amount_to_bill['und'][0]['value'])) {
          print $node->field_invoice_amount_to_bill['und'][0]['value'];
   }
 ?>

```

Can anyone direct me on how I can change those two snippets to output their values in the formats I need?

Thanks!

# Answer
> 1 votes
Actually date() takes a timestamp so the code should be:

```
<?php if(isset($node->field_invoice_due_date['und'][0]['value'])) {
          print date('F j, Y', strtotime($node->field_invoice_due_date['und'][0]['value']));
   }
 ?>

```

and to insert the thousands separator, you can use number\_format():

```
<?php if(isset($node->field_invoice_amount_to_bill['und'][0]['value'])) {
          print "$". number_format($node->field_invoice_amount_to_bill['und'][0]['value']);
   }
 ?>

```

if you wish to avoid a preprocess function.

# Answer
> 2 votes
You'll need to preprocess these elements into the template and format them to the way you want.

Let's take this practical example. Let's say we have a content type of 'blog' and we wanted to preprocess the same variables as above to be used in the template file...

```
/**
 * Preprocess variables for node.tpl.php
 *
 * @see node.tpl.php
 */
function theme_preprocess_node(&$vars) {
  if ($vars['type'] == 'blog') {
    if (isset($vars['field_invoice_due_date'][0]['value'])) {
      // Makes June 1, 2012 format from the time provided
      $vars['date_format'] = date("F j, Y", strtotime($vars['field_invoice_due_date'][0]['value']));
    } else {
      $vars['date_format'] = '';
    }
    if (isset($vars['field_invoice_amount_to_bill'][0]['value'])) {
      // you can use whatever function to format the money value, this is just an example.
      $vars['amount_to_bill'] = "$". number_format('%i', $vars['field_invoice_amount_to_bill'][0]['value']);
    } else {
      $vars['amount_to_bill'] = '';
    }
  }
}

```

if your moving these fields into a custom template, than you can preprocess with this hook as well:

```
 /**
 *
 * Implements hook_preprocess
 *
 * @param $variables
 * @param $hook
 */
function hook_preprocess(&$variables, $hook) {
  if ($hook == 'custom_template') {
    // do your preprocess magic here, you can find the variables by either dsm() or print_r()
  }
}

```

then, in the template do this:

```
<?php print $date_format; ?>
<?php print $amount_to_bill; ?>

```

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


title: Post user location to a map

text:
# Question
Title: Post user location to a map
I am building a site where people can log power failures in their area on a google map in Drupal 7.

I want to be able to have my site users register their location on their profile. This seems pretty straightforward to do using the Profile 2 and Location modules, however it's the next step that I'm hung up on.

I want the user to be able to click an "add a power failure" button, fill in the details of the failure (time, date etc) and hit save. Once this is done, I want to be able to plot a point on the map (using views or whatever) with the location details they entered in their profile when they signed up.

I've been trying to play with User reference and node reference in the power failure content type, but this doesn't really give me what I want.

Does anybody have any ideas on how I can accomplish this?

Thanks!

G

# Answer
For the location to be displayed on the google map,You need to install few modules:-

1. Install GMAP and LOCATION module,
2. Install GEOLOCATION and its dependent modules.
3. Add a field in content type with field type GEOLOCATION and widget type GOOGLE MAP.
4. With this, When the user will ad content,he will be able to mark the location of the area of the power cut on the map.
5. Refer this GEOLOCATION for further help.
> 1 votes

# Answer
Add Geofield to the user profile. You can then build a view using OpenLayers... or Leaf... or others to display the Geofield on a map. I think you want OpenLayers, but here is a comparison of some Drupal Mapping Mods. OpenLayers does not use Location, but some others do. If you need your users to add addresses rather than lat/lon, you can make geofield hidden and derive its data from and address with Geocoder.

You could create a pwr failure report content type and allow unauthenticated users to create a PFR protected by capacha and what not and skip the address all together by using ip\_geoloc. Depending on the data, the PFR could be a form with just email address and a true or false toggle?

You really might want to look at doing it with a simple webform and use MapBox

Anyway, lots of ideas to map user locations.
> 0 votes

# Answer
I (sort of) wanted to build the same thing. But I prefer not on use a lot of modules. I came up with the following solution: http://www.webdev.vanrij.org/index.php/2013/06/06/store-location-on-a-node/

I store the location information (Longitude & Latitude) in the node table itself. I fill that information based on a given address (user input). Made a function that get's all the nodes with location information from within a given radius of a given point. And put in on a (google) map.

Check out the blog for more info & the related github for the code. https://github.com/jivanrij/locationsearch
> 0 votes

---
Tags: users, location
---


# Question
Title: Blanket CCK Field Permissions for Specific Content Type?
I am creating a rather large (100s fields) form using CCK. I would like access to edit the fields to be give to anyone who has access to create the content type rather than by role.

For example, I can allow an anonymous user to edit the field\_phone using user permissions, but I do not want the anonymous user to have such permission on other content types, only the custom form.

Also, since there are 100s of fields, managing the edit permission individually kinda drags.

thanks, tom

# Answer
"Editing a field" can mean a lot of things because a field has many properties for input ('widget'), storage and output ('formatter'). That's why I was trying to figure out what you're after.

If you can write PHP, anything is possible, but I think that introducing a way for content creators to edit (a limited set of) field settings, would require a lot of custom code. However I assume that you're looking for a solution that requires no (or a little) custom coding. In order to achieve that, you may need to choose an alternative solution, like a custom compound field, CCK Multigroup or Webform. However I cannot advice you about that because I don't know which problem you're trying to solve.

On a more theoretical level, I think you have to be careful not to get content and configuration mixed up. Drupal stores both configuration (like field settings) and content (the information in a node) in the database. What you're asking sounds as if editing the field settings would in fact become another way to enter information. That may not be a problem now, but it can become a problem later because other modules are not prepared to access field settings as if they are part of the content.
> 1 votes

# Answer
I suggest you to use Webform module for surveys. CCK is not the best way to create such things.
> 0 votes

---
Tags: entities, users
---


# Question
Title: Print CCK field "A" if CCK field "B" has a value of "Z"
I want to print a CCK field (we'll call it CCK field "A") only if the value of another CCK field (we'll call it CCK field "B") matches a string. CCK field "B" is a select-list field with two options: "red" and "blue". I'd like to display the value of CCK field "A" only if the value of CCK field "B" is "blue". If the value is "red", then CCK field "A" should not be displayed at all.

How can I do so?

Thanks!

# Answer
THIMK! Test the value of Field B before printing Field A.

```
<?php
if(isset($node->field_field_b['und'][0]['value']) && ($node->field_field_b['und'][0]['value'] == 'blue')) {
    if(isset($node->field_field_a['und'][0]['value'])) {
          print $node->field_field_a['und'][0]['value'];
    }
  }
 ?>

```
> 2 votes

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


# Question
Title: How to print formatted contents of Computed Field and Full HTML Textarea in a custom template?
I have used this code to print normal text fields in a print.tpl.php template file:

```
<?php if(isset($node->field_mytextfield['und'][0]['value'])) {
          print $node->field_mytextfield['und'][0]['value'];
            }
     ?>

```

But that same code will not work with Computed Fields I have set up in that same content type. The content type has a "Print" display type, and I have tried all of the Format options (Unsanitized, Plain Text, Filtered Markup, and Raw Value No Display Code) for the computed fields, to no avail. How can I print the formatted values of those computed fields, exactly as they are displayed by the actual fields themselves?

I also have a Textarea field that prints as a single line of unformatted text using the code above. How can I print the formatted value of that field when Full HTML is used to enter info into that field?

Thanks!

# Answer
The Computed field defines its own formatting in the *Display Code (PHP)* box. If you have done your formatting there, when the page is processed, `$vars` will contain the output as:

1. **Unsanitized**: the output of *Display Code (PHP)* (`$display_output`) is unchanged.
2. **Plain text**: `$display_output` is filtered through the Plain Text filter.
3. **Filtered markup**: Non-permitted HTML tags are stripped from `$display_output`.
4. **Raw Value**: *Display Code (PHP)* is ignored and the value from *Computed Code (PHP)* is used (`$entity_field[0]['value']` ).

This is fine for a rendered field using `$vars`. The *Display output* code is used when the node is preprocessed. If, however you wish to access the fields from the `$node` object, only the field value (*Raw value*) is presented. So you either have to duplicate the *Display output* code in your template, or you have to move the formatting into the *Computed code* box.

If you set your `$entity_field[0]['value']` to the actual formatted string, then use the default `$display_output = $entity_field_item['value'];` in the *Display output*, you should be able to use the above code to display the field as is.

This is why it is much easier to use the processed fields. Instead of coding something like:

```
print $node->field_fieldname[LANGUAGE_NONE][0]['value'];

```

If `$vars['field_fieldname']` has been set, the template file receives the result of extract($vars). Each array element becomes a variable in its own right and all you have to do in the template file is:

```
print $field_fieldname;

```

or

```
print render($content['field_fieldname'];

```

if you have not separately included it in $vars in a preprocress. Much simpler when you understand how the data gets moved around.
> 2 votes

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


# Question
Title: How to allow the banner to be editable via front end?
In the BlueMasters 6.x theme, the banner is hard-coded inside `page-front-tpl.php`:

```
<div id="banner" class="clearfix">
  <?php //print $banner;?>
  <div class="main_view">
    <div class="window">
      <div class="image_reel">
        <a href="event-1"><img src="sites/all/themes/bluemasters/images/slide-image-1.jpg"></a>
        <a href="event-2"><img src="sites/all/themes/bluemasters/images/slide-image-2.jpg"></a>
        <a href="event-3"><img src="sites/all/themes/bluemasters/images/slide-image-3.jpg"></a>
      </div>
      <div class="descriptions">
        <div class="desc" style="display: none;"> Event One </div>
        <div class="desc" style="display: none;"> Event Two </div>
        <div class="desc" style="display: none;"> Event Three </div>
      </div>
    </div>

    <div class="paging" style="display: block;">
      <a rel="1" href="#" class="">1</a>
      <a rel="2" href="#" class="">2</a>
      <a rel="3" href="#" class="">3</a>
    </div>
  </div>

</div><!--banner-->

```

How can I expose the above `banner` `div` such that it reads from a particular `page`'s (Full-HTML) content, instead of hard-coded. Such that the user can change the banner without FTP/SSH access.

# Answer
> 1 votes
I have no idea why it is set up this way, but I'll hazard a guess that it was set up as a demo/starting point for a slide show. Regardless, from a quick look at the bluemasters.info file, there is a banner region defined, so if you change the above to be just:

```
<div id="banner" class="clearfix">
  <?php print $banner;?>
</div>

```

eg, remove the // that is commenting out $banner and remove all of the hardcoded stuff under it, your front page will now have an extensible region in it called banner.

Then, from the Blocks UI, you will be able to place blocks in there. If you want to grab something from a specific node, you can easily do that from there, or programmatically via a small custom module.

If what you are wanting is a slide show, you can delve into this theme and figure out what it's looking for, or utilize any of the numerous Views slide show modules out there and then assign their resulting block to this region.

# Answer
> 1 votes
You have two ways without coding:

* Use Nodeblock to create nodes for banners. Give users right to edit nodes and place them where you need them as a blocks.
* Use Views to create a block displaying (random?) node of content type banner. Give your users right to create, delete and edit them.

You could also use Advertisement module, but for a simple case like this it's an overkill, I think.

# Answer
> 0 votes
You have to write your custom module that will allow user to change the banners via back-end process.

* Steps :
    1. Create Content Type for Banner
    2. Add image field in content type banner
    3. Create custom block in your module
    4. Load all the nodes related to node type banner using node\_load\_multiple and then just use foreach for iterating through your images fields .
    5. Adjust your theme and css in your block and return that output.
    6. Create Region for theme and render that region in page--front.tpl.php.
    7. And finally enable block in that region.

---
Tags: 6, theming
---


# Question
Title: Show name of the taxonomy filtered by in views block title
I have an 'articles' content type with a node reference field that allows you to select a term from the taxonomy 'category'. I have a views block that gets all the a contextual filter to return the titles of all the 'articles' with the same category as the article being viewed. I would like the title of the views block to read 'More *name of category* articles'. I have tried using 'More %1 articles', but this returns 'More 15 articles'. I'm guessing that this is the taxonomy term number?

Is there a way get the taxonomy name filtered by and use it in the view title? This would be really elegant. I guess the alternative would be to do something with the views 'header' and hide the views title?

Thank you in advance.

# Answer
> 2 votes
Yes, you can get the taxonomy term name and use it in the view title. It's possible with the contextual filter settings. You can achieve your goal in two ways:

> Option #1 ( Using "%1" for the first argument, "%2" for the second, etc. )

**When the filter value IS available or a default is provided:**

**Override title** -\> More %1 articles

**Specify validation criteria** -\> Taxonomy term

**Filter value type** -\> Term ID

**Action to take if filter value does not validate** -\> Hide view

> Option #2 ( using PHP code )

**When the filter value IS available or a default is provided:**

**Override title** -\> *check this option, but leave text field empty.*

**Specify validation criteria** -\> PHP Code

Enter the code:

```
$tid = $handler->argument;
$term = taxonomy_term_load($tid);
if ($term){
  $name = $term->name;
  $handler->options['title'] = "More $name articles";
  return true;
}
else{
  return false;
}

```

**Action to take if filter value does not validate** -\> Hide view

# Answer
> 1 votes
The only way I think you can do this is by using the views header (as you suggest) because you can actually use php there to get the term name from the term id that's provided.

If you have the '**PHP filter**' module enabled on your site (it comes with Drupal core, but I wouldn't enable it unless I have to, and make sure you don't give access to the 'php code' text format to any roles).

In any case, if you have that module enabled, you'll be able to put php code into the view header (make sure you select '**PHP code**' as the text format). Then you can get to the term name like this:

```
<?php
$term = taxonomy_term_load(%1);
$name = $term->name;
return ("<h2>More $name articles</h2>");
?>

```

I just tested it and it should work pretty well. :-)

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


# Question
Title: db_select() which selects nodes which have a certain term
I feel like this should be a simple question and therefore have been answered before, but all of the other Stackexchange answers I find doesn't seem to directly answer the question (at least as far as I can understand).

```
$query = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('status', 1)
      ->condition('type', 'photo_gallery')
      ->orderBy('created', 'DESC')
      ->execute();

```

This is my `db_select()` to fetch a list of nodes.

My `photo_gallery` content type also has a term reference field named `field_tags` which references the `tags` taxonomy.

How do I select a list of nodes from the db and only get nodes which have a particular tag?

# Answer
You have to use the Join statement; what you basically need to do is joining your query with another from another table.

Here is an example that you can use.

```
$query = db_select('file_managed', 'fm');
$query->join('field_data_field_image', 'fi', 'fm.fid = fi.field_image_fid');
$query->groupBy('fm.fid');
$query->fields('fm', array('filename', 'uri'));
$query->fields('fi', array('field_image_width', 'field_image_height'));
$query->condition('fi.bundle','image_for_slider','=');
$result = $query->execute()->fetchAssoc();

```

In this example, the file\_managed table is joined with field\_data\_field\_image; you have to switch those with node and field\_tags.
> 3 votes

# Answer
saadlulu's answer is also correct, but since it doesn't specifically address the topic of taxonomy terms, I want to post my solution which I got working just a few minutes ago and explain what is happening so that some other newbie who comes along can understand what is happening well enough to alter it for their own uses.

My nodes are of type `photo_gallery` and they have a taxonomy terms field called `field_tags` and I want to grab all of the nodes which have the term for `$term_id`

```
$query = db_select('node', 'n');
$query->join('field_data_field_tags', 't', 't.entity_id=n.nid');
$result = $query
  ->fields('n', array('nid', 'title', 'created'))
  ->fields('t', array('entity_type', 'bundle', 'field_tags_tid', 'entity_id'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'photo_gallery')
  ->condition('field_tags_tid', $term_id)
  ->condition('status', 1)
  ->condition('type', 'photo_gallery')
  ->orderBy('created', 'DESC')
  ->execute();

```

The part I didn't know/understand was how the tables were structured behind the scenes for things like a term reference. When I looked into the actual SQL tables, then it became clear. The connections between a node and a taxonomy term are stored in a separate table and knowing which table that is was one of the big questions.

So, my `field_tags` data is stored in the `field_data_field_tags` table. I grabbed the nid of one of my nodes to see what the data looked like.

```
mysql> select * from field_data_field_tags where entity_id=1082;
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
| entity_type | bundle        | deleted | entity_id | revision_id | language | delta | field_tags_tid |
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
| node        | photo_gallery |       0 |      1082 |        1082 | und      |     0 |              5 |
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
1 row in set (0.00 sec)

```

Once I understood the info above, then I could see that I needed to join to the `field_data_field_tags` table and do that join on `entity_id=nid`.
> 5 votes

---
Tags: 7, taxonomy-terms, database
---


# Question
Title: How to modify the Search box input value?
I would like to add a value for the search box input to my Bartik subtheme, and modify the value in my Clean Coorporate subtheme. How would I do this?

Edit: Found this code in template.php for the clean coorporate theme. Editing the 'Search' string updated the value I was wanting to change. I guess I just need to put the same code in my Bartik subtheme as well?

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    unset($form['search_block_form']['#title']);

    $form['search_block_form']['#title_display'] = 'invisible';
    $form_default = t('Search this site');
    $form['search_block_form']['#default_value'] = $form_default;
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');

    $form['search_block_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = '{$form_default}';}", 'onfocus' => "if (this.value == '{$form_default}') {this.value = '';}" );
  }
}

```

# Answer
> 3 votes
The only line you'd need to set the value of the input is

```
$form['search_block_form']['#default_value'] = $form_default;

```

The last line is a basic JS placeholder implementation, but in this day and age the HTML5 `placeholder` attribute would be preferable:

```
function MYTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['search_block_form']['#attributes']['placeholder'] = t('Placeholder text');
}

```

---
Tags: 7, theming
---


# Question
Title: Services 3 JSON format [null] at end of all result
I am using services module recently i have noticed that i am getting all responses along with `[NULL]` at the end. So my app dev team is unable to parse the `JSON`.

What i am doing wrong ? What may be the possible causes for this ?

I think it happens with my custom module only. But i am sure i am using drupal\_json\_output with sufficient parameters.

I have posted this question a few weeks ago, but my app dev tem fixed it. Now i am facing it again. Any help ?

```
/**
 * Implementation of hook_services_resources().
 */
function noteresource_services_resources() {
  return array(
    'gymcam' => array(
      'actions' => array(
        'sendmail' => array(
          'help' => 'Send gymcam to admin',
          'callback' => 'gymcam_sendemail',
          'access callback' => 'gymcam_resource_access',
          'access arguments' => array('sendmail'),
          'access arguments append' => TRUE,
          'args' => array(
            array(
              'name' => 'uid',
              'type' => 'int',
              'description' => 'The uid of the logged in user',
              'source' => 'data',
              'optional' => TRUE,
              ),
          ),
        ),
      ),
    ),
  );
}

function gymcam_sendemail($data) {
  $data = array('status' => 'error', 'msg' => 'Mail not sent');
  drupal_json_output($data);
}

```

# Answer
I dont know why do you need to convert the data to JSON format. My idea is that you just return an array. The returned data of your custom service will be based on how we call it.

```
function gymcam_sendemail($data) {
  $data = array('status' => 'error', 'msg' => 'Mail not sent');
  return $data;
}

```

If you want to use JSON for returned data, just call /gymcam/sendmail.json
> 4 votes

---
Tags: services, 8
---


# Question
Title: Is theme_pager() vulnerable to HTTP Parameter Pollution?
I'm currently running vulnerability scans against my application, which is based on Drupal. One "High" vulnerability is HTTP Parameter Pollution (HPP), and it has to do with pages that make use of drupal's theme\_pager().

I know that it could indeed be (and probably is) a false-positive, but I need to be able to understand why it *isn't* a vulnerability so that I can remediate the scanning report. I'm hoping that someone with more security experience than I can help.

The found vulnerability is as follows (I'll use drupal.org in this example):

The actual scan output was as follows:

> Vulnerability description This script is possibly vulnerable to HTTP Parameter Pollution \> attacks.
>
> HPP attacks consist of injecting encoded query string delimiters into other existing parameters. If the web application does not properly sanitize the user input, a malicious user can compromise the logic of the application to perform either clientside or server-side attacks.
>
> This vulnerability affects /. Discovered by: Scripting (HTTP\_Parameter\_Pollution.script).
>
> Attack details
>
> Path Fragment input / was set to qui&n950086=v982658 Parameter precedence: last occurrence Affected link: /search/node/qui?page=1&n950086=v982658 Affected parameter: page=1
>
> Request GET /search/node/qui%26n950086%3dv982658

So my question is two-fold: Should this be considered a false-positive? How is Drupal protecting itself from HPP?

Thanks!

# Answer
> 3 votes
Simple answer: no, `theme_pager()` isn't vulnerable to this kind of attack.

The pager functions only use the `page` parameter and don't make use of any other. As far as Drupal core goes, that argument is used only in the context of a PDO-prepared database query, and so any effort at malicious manipulation of that `page` parameter will simply fail.

As with anything, careless use of `theme_pager()` outside of the proper API - e.g. using the associated preparatory functions manually without properly prepared database queries - can result in unwanted side-effects. But the function and its associates aren't inherently insecure, and from a core perspective are used safely.

# Answer
> 3 votes
HTTP Parameter Pollution is only a problem if one of two things are true:

1. Those parameters are used to control something important and by polluting the parameter you can cause some inappropriate behavior (doesn't apply).
2. It's a problem to have user-controlled content inside the html of the page. This is an issue that is more visible via things like Drupal's urls that return 200 responses for a url that is "embarrassing" like https://drupal.org/node/1/acunetix-scans-are-not-super-valid

I would say the fact that the "vulnerability" only shows up on Acunetix sites is evidence is not a "real thing" in the security world.

---
Tags: security
---


# Question
Title: translate drupal commerce product titles in views
I have enabled the necessary i18n and l10n modules and I have been able to translate content without any trouble. I am now trying to translate some drupal commerce products. Using the title module I replaced the title of the product with a title field.

The product translations are showing correctly on the product display and cart pages but I also created a view with some products. For some reason the product title doesn't get translated in the view. The add to cart button does get translated however.

How can I get my products to show the correctly translated title in my view like they do on the product display page?

# Answer
> 1 votes
Found a solution. I rewrote the results of the `Commerce Product: Title` Field and used the replacement pattern `[title_field]`. The translation then showed correctly.

# Answer
> 0 votes
You are not the only one dealing with this complete trans did not happen in D7. Try this contrib module, Title.

> While working on the new content translation system for Drupal 7, we (the Drupal core i18n team) faced the need to convert node titles to the Field API in order to make nodes fully translatable.
>
> We were not able to make this happen in Drupal 7 core ... so we decided to find a solution for this in contrib: the idea is replacing node titles with fields à la Automatic Nodetitles.
>
> This will be exploited by the related Entity Translation project.

---
Tags: views, commerce, i18n-l10n
---


title: How to print $banner; without <div>?

text:
# Question
Title: How to print $banner; without <div>?
After moving some animation code from page-front.tpl.php to a block, the paging animation is broken.

Good:

Broken:

The slide code is:

```
<div id="banner" class="clearfix">
    <div class="main_view">
    <div class="window">
      <div class="image_reel">
        <a href="event-1"><img src="sites/all/themes/bluemasters/images/slide-image-1.jpg"></a>
        <a href="event-2"><img src="sites/all/themes/bluemasters/images/slide-image-2.jpg"></a>
        <a href="event-3"><img src="sites/all/themes/bluemasters/images/slide-image-3.jpg"></a>
      </div>
      <div class="descriptions">
        <div class="desc" style="display: none;"> Event One </div>
        <div class="desc" style="display: none;"> Event Two </div>
        <div class="desc" style="display: none;"> Event Three </div>
      </div>
    </div>

    <div class="paging" style="display: block;">
      <a rel="1" href="#" class="">1</a>
      <a rel="2" href="#" class="">2</a>
      <a rel="3" href="#" class="">3</a>
    </div>
  </div>
</div><!--banner-->

```

When I move the above code into a block and output via `print $banner;`, there is some extra `<div>` which breaks the animations:

```
<div id="banner" class="clearfix">
<div id="block-block-4" class="clear-block block block-block">
<div class="content">
    <div class="main_view">
    <div class="window">
      <div class="image_reel">
        <a href="event-1"><img src="sites/all/themes/bluemasters/images/slide-image-1.jpg"></a>
        <a href="event-2"><img src="sites/all/themes/bluemasters/images/slide-image-2.jpg"></a>
        <a href="event-3"><img src="sites/all/themes/bluemasters/images/slide-image-3.jpg"></a>
      </div>
      <div class="descriptions">
        <div class="desc" style="display: none;"> Event One </div>
        <div class="desc" style="display: none;"> Event Two </div>
        <div class="desc" style="display: none;"> Event Three </div>
      </div>
    </div>

    <div class="paging" style="display: block;">
      <a rel="1" href="#" class="">1</a>
      <a rel="2" href="#" class="">2</a>
      <a rel="3" href="#" class="">3</a>
    </div>
  </div>
</div>
</div>
</div><!--banner-->

```

Is it possible to force `print $banner;` to output the raw content of a block, without the `<div id="block-block-4" class="clear-block block block-block">` and `<div class="content">`?

# Answer
**Update:** *Changes made to work for Drupal 6 as your tag states 6.*

It looks like the system is using the standard `block.tpl.php` with this code:

```
<div id="block-<?php print $block->module .'-'. $block->delta; ?>" class="clear-block block block-<?php print $block->module ?>">

<?php if (!empty($block->subject)): ?>
  <h2><?php print $block->subject ?></h2>
<?php endif;?>

  <div class="content"><?php print $block->content ?></div>
</div>

```

What you need to do is add another block template file, and take away the `<div>` tags you want to eliminate. To do this, add a template named `block-module-delta.tpl.php` to your active theme.

For `block-module-delta.tpl.php`

* Module = the module that's creating the block (views, block, etc)
* Delta = the internal id assigned to the block

So if the block module made the block, and it has an id of 4, you'd name the template file `block-block-4.tpl.php`, and you'd put this PHP/HTML in the template file:

```
<?php if (!empty($block->subject)): ?>
  <h2><?php print $block->subject ?></h2>
<?php endif;?>

<?php print $block->content ?>

```

Notice how I eliminated the `<div id="block-block-4" class="clear-block block block-block"> and <div class="content">` from the template.
> 0 votes

# Answer
Thanks for inertialmedia's answer, now I found the root of the problem. When I move the paging code from `.php` to block:

```
<div class="paging" style="display: block;">
  <a rel="1" href="#" class="">1</a>
  <a rel="2" href="#" class="">2</a>
  <a rel="3" href="#" class="">3</a>
</div>

```

The html generated is:

```
<div class="paging" style="display: block;">
  <a rel="1" href="#" class="">1</a><br />
  <a rel="2" href="#" class="">2</a><br />
  <a rel="3" href="#" class="">3</a>
</div>

```

`print $block->content` converts (some) line breaks to `<br />` and so the paging buttons will be ok if I join the lines together:

```
<div class="paging" style="display: block;">
  <a rel="1" href="#" class="">1</a> <a rel="2" href="#" class="">2</a> <a rel="3" href="#" class="">3</a>
</div>

```
> 0 votes

---
Tags: 6, blocks, theming
---


# Question
Title: Why print $block->content sometimes converts line break to <br /> but sometimes does not?
During debugging of a sliding animation, I found that `print $block->content` sometimes convert line breaks to `<br />`.

The following code in a `block`:

```
<div class="paging" style="display: block;">
  <a rel="1" href="#" class="">1</a>
  <a rel="2" href="#" class="">2</a>
  <a rel="3" href="#" class="">3</a>
</div>

```

is output in HTML as:

```
<div class="paging" style="display: block;">
  <a rel="1" href="#" class="">1</a><br />
  <a rel="2" href="#" class="">2</a><br />
  <a rel="3" href="#" class="">3</a>
</div>

```

*Note:* there are two `<br />`.

While the following code in a `block` (`<a>` `</a>` surrounded by `<div>` `</div>`):

```
<div class="paging" style="display: block;">
  <div><a rel="1" href="#" class="">1</a></div>
  <div><a rel="2" href="#" class="">2</a></div>
  <div><a rel="3" href="#" class="">3</a></div>
</div>

```

is output in HTML as:

```
<div class="paging" style="display: block;">
<div><a rel="1" href="#" class="">1</a></div>
<div><a rel="2" href="#" class="">2</a></div>
<div><a rel="3" href="#" class="">3</a></div>
</div>

```

*Note:* there is no `<br />`.

How can I disable line break to `<br />` conversion when printing block content?

# Answer
This could be due to the `input format` you are using for the block's content region.

Assuming you are using the default input format (`id 1`), the filter option `Line break converter` is probably enabled. See admin page: /admin/settings/filters/1

You can uncheck this setting in the default input format or you can use a different input format by clicking on the `Input format` fieldset under the `Block body` content region.

If you do not have any other input formats, you can add a new one that does not use this `Line break converter` setting here: /admin/settings/filters/add

**Note**: Being able to configure or add any input format requires the `administer filters` permission from the `filter` module.
> 3 votes

---
Tags: 6, blocks
---


# Question
Title: Point me in the direction of developing new forum features?
Probably the most confusing part about Drupal for a beginner (read: Me!) is figuring out which modules should be used to develop new functionality. I'm looking for the path I would need to take to develop the specific functionality I'm trying to create.

This is what I'm looking to accomplish:

-Attach a user created "idea" or "opinion" to a forum post or thread

-Allow users to vote on & modify these "ideas" and "opinions"

Any leads are appreciated.

# Answer
In order to create a forum in drupal, you can start with the forum module. It is a core module, so it will already be installed. The following steps can make forum development simpler:

1. Enable the module-
    * Go ahead and navigate to Site Building\>\>Modules and check the box next to forums to enable the module.
2. Set up containers-
    * you need to navigate to administer \>\> forums to start setting up your new forum
3. Set up forums-
    * Each container "contains" several forums. In other words, your containers are children of the root node and your forums are children of your containers
4. Customize your forum for adding content or ideas-
5. In order to add the voting/rating features, use the following:

Advanced Forum may also be used if you wish to enhance Drupal's core forum module features.
> 2 votes

---
Tags: nodes
---


# Question
Title: Trying to access modules page callback while authenticated
I have a module below that will only show "hello world" when I am an administrator. I would also like "hello world" to display when I an authenticate user but right now all I am getting is you are not authorised. I have set mymenuitem as the home page and I am using Drupal 7.

```
 function mymenuitem_menu() {
  $items = array();
  $items['mymenuitem'] = array(
    'title' => 'mymodule',
    'description' => 'my menu access issue',
    'page callback' => 'mymodule_homepage',
    'access arguments' => array('access mymodule homepage'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function mymodule_homepage(){
  drupal_set_title(t('menu system'));
  return "hello world";
}

```

How can I achieve this?

# Answer
> 3 votes
1. Make sure you define your new permission using Drupal 7's `hook_permission()`.
2. Grant your new permission to `authenticated user` here: /admin/people/permissions/list

Try this:

```
function mymodule_permission() {
  return array(
    'access mymodule homepage' => array(
      'title' => t('Access My Module homepage'),
      'description' => t('View My Module homepage.'),
    )
  );
}

```

---
Tags: hooks, routes
---


# Question
Title: Image Resize Filter not working with WYSIWYG + CKeditor?
I have installed image resize filter, set it to be active on the 'full editor' content editing mode which is where I have CKEditor activated. CKEditor is working great, the problem is that I don't see any image resizing functionality.

I have insert installed as well. I can upload a file, and when I hit insert it goes into the CKeditor as the original size.

I added an images field to Basic Page which got the upload button/insert showing up and that's working great, but I see no sign of Image Resize Filter in action anywhere :?

# Answer
For re-sizing of images instead of using Image Resize filter you colud use the feature of drupal 7 itself ie by setting up an File Type for your image.

You could set up a File type you should go to Configuration -\> Media -\> File types -\> Manage Display

There are basically 6 types of image file type that you could use

1. Link
2. Default
3. Preview
4. Large
5. Original
6. Small

These are the default file type that you can select and are there with there default values so we could override the default values by our own values and could use that file type for uploading our own images of particular size.
> 1 votes

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


# Question
Title: How to cache forms with a reverse proxy and deal with stale form tokens?
When Form API generates a form, it also generates a token that is passed out with the form in a hidden field, and expected to be returned back. If it is, the form is processed.

If a rendered form where ever to be cached, say, by Varnish, this mechanism breaks. The first user submitting the form will consume the token, and following attempts to use the form will be rejected.

What strategies are available to keep forms working while caching their rendered form?

# Answer
> 5 votes
I use BOA for my sites, but by default BOA simply disables front end-caching on the fly for form submissions. Beyond my actual experience I came a cross a one year old artificial on how the New Zealand Post deals with Drupal & Varnish and the form token issue. Holy John Wayne, its a must read for Drupal caching -really. Focusing only on the the form issue:

> The final piece to our puzzle is the Cookie Cache Bypass Advanced module, which automatically sets a special NO\_CACHE cookie whenever the user submits a POST form on the site, including things like the login form. Our Varnish is configured to bypass the page cache (but not the ESI cache) when it sees this cookie.

You can also disable form tokens when XSRF production is not reaquired with in form\_alter (unset($form\[‘#token’\]);) or ($form\[‘#token’\] = FALSE;)

An Acquia Drupal performance article puts forth a Drupal Module Authcache, but reading the doc on Authcache, it works out the caching with a place holder for the form (not caching the form):

> Authcache attempts to intercept any customized content and set up a placeholder within the HTML. Then after the page is loaded, an Ajax callback is used to retrieve custom data and fill in the placeholders, dynamically updating the page HTML.
>
> Current Authcache placeholders: Form tokens (logged-in users only; required by \> Drupal to prevent cross-site request forgery attacks)

The strategy is, **cache everything but the form**. So addressing everything else: Maybe Varnish is not used at all, Memcache & Redis? My strategy would be to use what BOA offers because I use BOA and the wizards behind it (omega8.cc) know a ton more than I. I dont think there is an external cache that solves the problem. They all seem to bypass for the form.

Do *partial caching* with the aforementioned authcache and with finely tweaked Views and Panels as mentioned in the NZ Post article and described by the brain trust at Wunderkraut \- its old, but addresses the issue.

Use Drupal ESI Module and Varnish is partially ESI compliant):

> ESI - or Edge Side Includes - is a high performance caching solution for Authenticated users but can be helpful for Anonymous users as well.
>
> Typically, pages which are personalised for authenticated users (even minor personalisations, such as a block which says "Logged in as manarth") will prevent reverse-proxies (which can easily perform 100 times faster than Drupal) from caching the page, because messages intended for one user could then be seen by another.

Hope thats more helpful.

# Answer
> 0 votes
One potential solution would be to disable the token all together with `$form[‘#token’] = FALSE;`, then override the submit callback to instead of actually posting the comment, regenerate the original form with an token, and ask the user to confirm the post.

If the user supports ECMAScript, one could improve the user experience by having a services resource which exposes form generation of new form tokens and inserts the relevant form into the `form_cache`. Then, as soon as the user focuses on the form, and is thus likely to want to submit it, disable the submit button, fetch a new token and insert it into the already rendered form, and enable the submit button again.

---
Tags: caching, forms
---


title: Change form validation error messages

text:
# Question
Title: Change form validation error messages
In my theme I'm already using the hook\_form\_alter to customize the form fields but now I want to customize the validation error messages.

After some research, the only way I'm finding is to write a whole separate function and custom error handling of each form field.

I don't want to reinvent the wheel. Isn't there just a simple way to change the default form validation error so I can get away from "XYZ field is required?"

# Answer
There are a number of options to resolve this issue:

1. One option is using the String Overrides module to replace the string used to generate the message.
2. Another option is to create a custom module that overrides the validation function for a particular form or field, replacing any error messages with the messages of your choosing.
3. The following link may also help:
> 2 votes

---
Tags: theming, forms
---


# Question
Title: How to Create content type per organic group
Hi i have created a content type and i have 4 groups using organic groups.

Is there any way i can restrict content type to one of the organic group.so other groups cant create any content with the content type.

Please help me thanks a lot.

# Answer
> 0 votes
You could simply add taxonomy terms to differentiate different content types.

# Answer
> 0 votes
To restrict one content type to only one organic group,you can:

1. You may create a vocabulary with any name. For example: `organicgroups`.
2. You may add lists (terms) to that vocabulary.
3. Then while creating a content, associate a vocabulary term with each content node as per the organic group for which you are creating the content.

---
Tags: nodes, organic-groups
---


title: Use menu in panels

text:
# Question
Title: Use menu in panels
I have problem. I have panel page with 2 columns. On the left I have menu, and on the right I want to have a content from this menu, how can I have static menu on the left, and only change the content on right? Do you have any proposition or suggestions?

# Answer
> 1 votes
You can use **block menu** model this give you a dynamic menu but if you want a static menu you have to add a menu from(admin/structure/menu) after create the menu it will show on blocks(admin/structure/block) and put it on the specific region and you have a region called content this is by default show the content on it see that http://www.youtube.com/watch?v=lTZT\_ucpYMQ

# Answer
> 0 votes
In general you can create a menu that calls a URL to a view and then use the View to provide the desired content. You will find more on how to use Panels here and views here

# Answer
> 0 votes
Ashlar's answer is correct, but I would like to add some more background info.

Any menu item is linked to a specific callback in Drupal. A callback may or may not be handled by the Page manager and rendered through Panels. A callback rendered with Panels may or may not have your specific two column layout. There is no way to use Panels to "force" any specific piece of content to render in a specific Panel region, that's just not how it works.

You are responsible for ensuring that each link in the menu points to a page that is rendered with the two column layout. One common, and good, way of doing that is what Ashlar suggests. However, this will not necessarily work for all types of content.

# Answer
> 0 votes
Instead of using different module to perform the desired functionality you could simply make node template pages so that the menu remains the same and there is only a change in the content.

To Add node template pages you

1. Go to structure -\> Pages -\> Node template -\> Enable and Edit
2. Add Variant on the top. Add as many variants that you need to add. In the Selection rule select add the **Node Bundle** and select the Content type that that you want to display.
3. Select the type of layout from the **Layout** option.
4. In the content part click on Add Content and select what do you want to put there in the display.

---
Tags: routes, panels
---


# Question
Title: Link Mini Panel thumbnail formatter to node
Working on a site that shows images and video with a Mini Panel formatter in a View withe File Entity and Media modules. The Mini Panel has a piece of content of file display that shows an Image display as well as Vimeo Video and YouTube. The Image display settings uses an Image style.

How do I link the media from the mini-panel to the referencing entity? (User clicks on the thumbnail in the view listing and is taken to the node's path).

# Answer
> 0 votes
If you go to the view display page and click on the field of your thumbnail, on the settings page scroll down and you should see a drop-down with title of **Link image to**. Choose content and save.

# Answer
> 0 votes
To link the media to the node,you need to follow some steps as:-

1. Edit the view which contains images and videos which are to be linked to a node.
2. In the fields section,Just Click on the field which would link to some node.

3.1 In the REWRITE RESULT's tab,check the checkbox :Output this field as a link and specify the destination url to which you want to link to.

3.2. or to link the formatter, just click on the field and in the LINK IMAGE TO and select a option to which you want your formatter to be linked to.

---
Tags: views, panels
---


# Question
Title: Path-based context and URL aliases - wrong block shown
My (Drupal 7) site has a search which uses two blocks - one for entering the criteria and one for the results.

(For brevity, I won't explain in detail why I need two blocks but it's basically because I'm doing a drop-down search a bit like this approach. Suffice to say that I can't do it all in one block.)

The search is at *mysite.com/contact-us*. I've got a context rule which shows the criteria block in the sidebar when the *contact-us* URL path matches.

I want the results block to appear on the same page as the criteria block, appearing in its place. Therefore, I've got a URL alias of *contact-us/find*, which points to *contact-us*. My context rules say that if the path is *contact-us/find*, the results block should be shown. (The alias was set up via the UI, i.e. Configuration \> URL aliases)

So both *contact-us* and *contact-us/find* show the Contact Us page, but there are different Context rules and so different blocks are shown in the sidebar.

That's the theory anyway. Here's what happens in practice:

1. I browse to *mysite.com/contact-us*. I see the criteria block.
2. I fill in the search criteria
3. I am taken to e.g. *mysite.com/contact-us/find?property=35* (the querystring provides an ID which the results view uses). I see the results block in the sidebar. So far, so good!
4. However, if I then go back to *mysite.com/contact-us* (e.g. to search again), I still see the results block and not the criteria one! And it thinks there are no results as I no longer have the querystring.

If I clear the cache, all is well again - I see the correct blocks. But I need a solution which doesn't require a cache clear - that's not something my users will be doing!

I presume that I'm running into problems because both *contact-us* and *contact-us/find* are actually the same node, and so Context can't accurately differentiate between them unless the cache is empty, but I'm not sure.

Any suggestions how I could resolve this one? Could I have a different type of rule specifying when the blocks should appear? Or something else? I'm all out of ideas!

# Answer
> 0 votes
In the end, we changed the whole approach here, and made the jump menu load the new block with AJAX. (I wasn't the person who developed the new way of doing this, so I can't provide much more detail, I'm afraid.) This was a lot less buggy than my original approach!

---
Tags: uri, 7
---


title: Sort downloads from dropdown

text:
# Question
Title: Sort downloads from dropdown
i have alot of car drawings that i want to upload to my website and make downloadable .. the thing is that i want to have a dropdown menu, 1 with manufacture, 1 with model, and 1 with year .. from there you must be able to find your specific car from the drop down menu ..

i know i need to use taxonomy but thats about it, i dont really know how to implement it in views, or what content type i must create, if its 1 for each car model or 1 for each manufacture ..

all ideas are appreciated.

Thank you.

# Answer
You only need to create one content type of type car. The content type will have different fields such as manufacturer (which will be a term field), brand(Will also be a term field), date manufactured (It can be a term field or a dropdown).

Then you go ahead and create a view of type display page according to your specification.

**UPDATE**

Add the three fields (manufacturer, type and brand) to the sort criteria and expose them.

See screenshot below

For the download link use the download file module with your car content type
> 2 votes

# Answer
For generating drop-down menus we have a module nice\_menu refer to the module go through it readme.txt for better understanding .

and use command

"drush dl nice\_menu"

for the most compatible version
> 1 votes

# Answer
Use OM Menu. This is a better solution I have already implemented this in one of my project. This will give you block for menu as drop down. Please check OM menu
> 1 votes

# Answer
1. For creating drop down menus for selecting the appropriate car based on some properties ,you may use HIERARCHICAL SELECT module.
2. hierarchical select module ,hope this may be of some help .
> 1 votes

---
Tags: taxonomy-terms, nodes
---


title: How to add HTML tag in Drupal block ?

text:
# Question
Title: How to add HTML tag in Drupal block ?
I would appreciate your help in my problem with html tagging or css class in blocks.

I've tried Field Formatter Class and Field Formatter CSS Class modules, but with those I only could add class to Article, Basic page and own types, which doesn't help me as I don't want to add Read more or RSS. When I definied my new content type, I didn't check the RSS box and I did check the full content box, but stil...

So, is there any module to add CSS class or HTML tag to a block. Different tags, of course for every block.

No PHP please.

Thanks, cs.

# Answer
You can use the Block class module which adds a field to each block where a class can be added.

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent `<div class="block ...">` element of a block.
> 2 votes

# Answer
1. There is a method to add **class** to the **BLOCK-VIEW**(view in which results of the view would be displayed in a block)
2. In the Advanced setting tab,which is located near the block settings tab, **second last property is to add a css class**.

3.**save the settings and changes** you have made,and now you are done. Your block now has a individual css class.
> 0 votes

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


# Question
Title: How to show the product "add to cart" button on a product kit?
I would like to add a "add to cart" button on a product kit, for each product in the product kit. How may I achieve that? I have been searching for a while now. Ubercart 3.

This would be similar to iTunes when viewing an album, the user may buy a single song of the album. Currently with product kit, the user has to click the product link to get to the song then be able to buy it.

# Answer
> -1 votes
Drupal has a number of modules that make "add to cart" and other similar features of Drupal commerce work, by simply enabling those modules.Check out the following links:

1. Commerce Line Item Cart Form
2. This link may also help- Cart Modules

---
Tags: ubercart
---


# Question
Title: On content update email referenced users - Drupal 7 Rules module
I feel like I am almost there but I am running into a problem.

I have a contenttype called projects with some users assigned to each project node. When a project node is updated I want to send a notification email to the referenced users.

What I have now is that all users get the email as the content gets updated.

Your help is greatly appreciated!

# Answer
I just figured it out, i used a loop that went trough all the referenced users and then I added a action that send an email to every user in the loop.
> 3 votes

# Answer
It can be done by using the Rules module and using the user reference field in particular.When one of the fields it has is a user reference and you wish to send an email to that user of that reference each time a node is updated, try using the following piece of code:

```
// Change $node->field_userreference to point to the correct CCK field
$recipient = user_load($node->field_userreference);
return $recipient->mail;

```

Another option is: Add the action Load a referenced user and select the user you want to load in the DO section. Give it a name if you want, otherwise it will default to 'Referenced User'.

Then add another action, Send mail to a user and select the name you chose in the previous step under the Arguments configuration.
> 0 votes

# Answer
Have you considered the subscriptions module? It provides the notification on node update functionality you desire, but also allows the users receiving the notifications (subscription preferences) to toggle them off or on, or add them to new nodes too. Hope that can help.
> 0 votes

---
Tags: rules, users
---


# Question
Title: How can we change the default URL what we get through the view blocks on a basic page?
I am working on a site, I had used a view block on a basic page, this view block has a pager. When we navigate through the pager links we are getting url structure like this

**http://www.website.com/page-name?page=1** **http://www.website.com/page-name?page=2**

I want to remove this **?page=1** from the url and want to modify it to **page-name-1** and so on.

# Answer
You can use the Clean Pagination module to get reasonably close:

> Clean Pagination is a very simple module that allows you to enable clean URL pagination for specified pages. The way Drupal typically works, if you had a view with the URL 'my-view', subsequent pages would normally use a query to pass the page number, as in 'my-view?page=2'. When Clean Pagination is being used for a page, it will create a url like 'my-view/2'.

If that doesn't do the trick that module should at least serve as a good starting point to convert the pager to exactly what you're looking for.
> 2 votes

---
Tags: views, uri
---