# Question
Title: Getting "TypeError: $ is not a function" with (or without) jQuery Update installed
I'm creating a custom theme and have run into a bit of a snag. Drupal won't recognize jQuery even though I have jQuery Update module enabled.

The error in console:

```
TypeError: $ is not a function
$(document).read(function() { alert('hit'); });

```

My .info just to be thorough:

```
name = Theme
description = The Theme
core = 7.x

stylesheets[all][] = css/style.css
scripts[] = js/scripts.js

regions[header]         = Header
regions[highlighted]    = Highlighted
regions[help]           = Help
regions[content]        = Content
regions[sidebar_first]  = First sidebar
regions[bottom]         = Page bottom

;Hidden Regions
regions[page_top] = Page Top;
regions[page_bottom] = Page Bottom

features[] = logo
features[] = node_user_picture
features[] = comment_user_picture
features[] = favicon
features[] = main_menu
features[] = secondary_menu

```

Head tag on view source with jQuery Update set to 1.10:

```
    <head profile="http://www.w3.org/1999/xhtml/vocab">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="http://localhost/TLSConnect/misc/favicon.ico" type="image/vnd.microsoft.icon" />
<meta name="Generator" content="Drupal 7 (http://drupal.org)" />
<title>Welcome to TLSConnect | TLSConnect</title>
@import url("http://localhost/TLSConnect/modules/system/system.base.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/system/system.menus.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/system/system.messages.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/system/system.theme.css?mxpb1v");</style>
<style type="text/css" media="all">@import url("http://localhost/TLSConnect/sites/all/modules/jquery_update/replace/ui/themes/base/minified/jquery.ui.core.min.css?mxpb1v");
@import url("http://localhost/TLSConnect/sites/all/modules/jquery_update/replace/ui/themes/base/minified/jquery.ui.theme.min.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/overlay/overlay-parent.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/contextual/contextual.css?mxpb1v");</style>
<style type="text/css" media="all">@import url("http://localhost/TLSConnect/modules/comment/comment.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/field/theme/field.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/node/node.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/search/search.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/user/user.css?mxpb1v");
@import url("http://localhost/TLSConnect/sites/all/modules/admin_menu/admin_menu.css?mxpb1v");
@import url("http://localhost/TLSConnect/sites/all/modules/admin_menu/admin_menu.uid1.css?mxpb1v");
@import url("http://localhost/TLSConnect/sites/all/modules/admin_menu/admin_menu_toolbar/admin_menu_toolbar.css?mxpb1v");
@import url("http://localhost/TLSConnect/modules/shortcut/shortcut.css?mxpb1v");</style>
<style type="text/css" media="all">@import url("http://localhost/TLSConnect/sites/all/themes/ukvi/css/style.css?mxpb1v");</style>
  <script type="text/javascript" src="http://localhost/TLSConnect/sites/all/modules/jquery_update/replace/jquery/1.10/jquery.min.js?v=1.10.2"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/misc/jquery.once.js?v=1.2"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/misc/drupal.js?mxpb1v"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.core.min.js?v=1.10.2"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/sites/all/modules/jquery_update/replace/misc/1.9/jquery.ba-bbq.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/sites/all/modules/jquery_update/replace/misc/1.9/overlay-parent.js?v=1.0"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/modules/contextual/contextual.js?v=1.0"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/sites/all/modules/admin_menu/admin_menu.js?mxpb1v"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/sites/all/modules/admin_menu/admin_menu_toolbar/admin_menu_toolbar.js?mxpb1v"></script>
<script type="text/javascript" src="http://localhost/TLSConnect/sites/all/themes/ukvi/js/scripts.js?mxpb1v"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, {"basePath":"\/TLSConnect\/","pathPrefix":"","ajaxPageState":{"theme":"ukvi","theme_token":"YdYlp6PGGL8uOVLaL_gtRv-n5Z8pyvsoVoSd7spnI0E","js":{"sites\/all\/modules\/jquery_update\/replace\/jquery\/1.10\/jquery.min.js":1,"misc\/jquery.once.js":1,"misc\/drupal.js":1,"sites\/all\/modules\/jquery_update\/replace\/ui\/ui\/minified\/jquery.ui.core.min.js":1,"sites\/all\/modules\/jquery_update\/replace\/misc\/1.9\/jquery.ba-bbq.min.js":1,"sites\/all\/modules\/jquery_update\/replace\/misc\/1.9\/overlay-parent.js":1,"modules\/contextual\/contextual.js":1,"sites\/all\/modules\/admin_menu\/admin_menu.js":1,"sites\/all\/modules\/admin_menu\/admin_menu_toolbar\/admin_menu_toolbar.js":1,"sites\/all\/themes\/ukvi\/js\/scripts.js":1},"css":{"modules\/system\/system.base.css":1,"modules\/system\/system.menus.css":1,"modules\/system\/system.messages.css":1,"modules\/system\/system.theme.css":1,"misc\/ui\/jquery.ui.core.css":1,"misc\/ui\/jquery.ui.theme.css":1,"modules\/overlay\/overlay-parent.css":1,"modules\/contextual\/contextual.css":1,"modules\/comment\/comment.css":1,"modules\/field\/theme\/field.css":1,"modules\/node\/node.css":1,"modules\/search\/search.css":1,"modules\/user\/user.css":1,"sites\/all\/modules\/admin_menu\/admin_menu.css":1,"sites\/all\/modules\/admin_menu\/admin_menu.uid1.css":1,"sites\/all\/modules\/admin_menu\/admin_menu_toolbar\/admin_menu_toolbar.css":1,"modules\/shortcut\/shortcut.css":1,"sites\/all\/themes\/ukvi\/css\/style.css":1}},"overlay":{"paths":{"admin":"node\/*\/edit\nnode\/*\/delete\nnode\/*\/revisions\nnode\/*\/revisions\/*\/revert\nnode\/*\/revisions\/*\/delete\nnode\/add\nnode\/add\/*\noverlay\/dismiss-message\nuser\/*\/shortcuts\nadmin\nadmin\/*\nbatch\ntaxonomy\/term\/*\/edit\nuser\/*\/cancel\nuser\/*\/edit\nuser\/*\/edit\/*","non_admin":"admin\/structure\/block\/demo\/*\nadmin\/reports\/status\/php"},"pathPrefixes":[],"ajaxCallback":"overlay-ajax"},"tableHeaderOffset":"Drupal.admin.height","admin_menu":{"destination":"destination=node","hash":"0272a75636951355671f0daca74a5137","basePath":"\/TLSConnect\/?q=admin_menu","replacements":{".admin-menu-users a":"0 \/ 1"},"margin_top":1,"position_fixed":1,"toolbar":{"activeTrail":"\/TLSConnect\/"}}});
//--><!]]>
</script>
</head>

```

# Answer
jQuery is namespaced in Drupal 7. You need a closure:

```
(function($) {
  $(document).read(function() { alert('hit'); });
})(jQuery);

```
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: Can Display Suite render content without my theme around it?
I'm just getting familiar with Display Suite and I want to know if I can use it to display only the content - not my header/footer/etc from my theme.

My goal is to display this content in a modal popup so I don't want anything around it.

# Answer
aDisplay suite should allow you to modify the output for the fields and even choose some layouts but AFAIK it won't let you completely omit the site theme (i.e. create a page without header or footer).

You can use js/ajax to grab just the portion of the page you want to appear in the modal pop-up so that it doesn't pull in the header/footer. Depending on the JS library(ies) you are using this could be easy or challenging.
> 0 votes

---
Tags: 7, display-suite, javascript
---


# Question
Title: Submit button calling wrong submit handler
I have a form with 3 different "Submit" buttons, and I want each of them to map to a particular Submit handler.

I have included these items using the following, generic, pattern:

```
                    array(
                        '#prefix' => '<td>',
                        '#suffix' => '</td>',
                        '#type' => 'submit',
                        '#value' => 'Update',
                        '#submit' => array('user_profile_details_edit_phone_submit')
                    )

```

But, every time I click the "Submit" button, the incorrect function is called. The function that IS called is the LAST function I add to a submit handler in this way.

Am I doing something wrong?

# Answer
Drupal uses the name and value of submit buttons to identify which was pressed, and subsequently which submit handlers to run. If the names and values of all three buttons are the same, the FAPI will only be able to use one of them (in this case the last one).

To fix it you can assign a unique `#name` property to each of the buttons.
> 3 votes

---
Tags: forms
---


# Question
Title: minifying css in drupal and getting the original source css
We have inherited a drupal 7 installation. We have the source code. When we look on the front end there are series a of minified css files named like below. We are interested in getting the original source css files. I have no experience in drupal css minification. Does this kind of output look like out the box drupal minification. If so is there a location that specified the exact css that was used?

```
 <link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_hYCLW089C9S9sP3ZYkuG6R-Q5ZHbEhblZBFjwZ_bE_I.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_YYoEBheeHSoZ5EBVRncs-cuvNClW-5FNm_tmYaEdRwM.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_5-5L742ZPRdlG5Jq9Yz3AIRJ3MBxYr6H_bolFIoqd68.css" media="all" />

```

Each css file that we see on the front end is collection of multiple css files.

# Answer
Yes that looks like Drupal's built in CSS aggregation.

The easiest solution would be to turn aggregation off temporarily. Then you'll see the original sources in the markup.

You can turn it off at the admin/config/development/performance page.
> 4 votes

# Answer
In addition to what Clive said. The default location of the css file would be in the theme directory. Navigate to:

root/sites/all/themes/*\[select your theme that is listed as the active theme in the appearance admin page\]*/style.css

If you do not see the style.css go the themes ".info" in that directory and in that file it will tell you where the .css file(s) are located.
> 3 votes

---
Tags: theming
---


# Question
Title: Set a content type's teaser image (right outlined)
So I'm looking to get the image of the teaser display from the bottom outlined to the right. Here's screenshots to make it clearer.

As you can see, I've already managed to do it once, but I can't reproduce. Also, can't find how to get the "add to cart button" on the product.

# Answer
What you will want to do is go to your views admin page for that view.

If the view is built using fields simply click on that field and select:

1. Style Settings
2. Check the box titled "customize field HTML"
3. You can modify the view to display it as a div or leave it as is
4. Check the box titled "create a css class"
5. Type in a css class
6. Click apply. And save the view.

Now you can go to your theme .css file and create a new css rule to position the image. And should apply for all future views with that css class for that field.

Let me know if you need further help.
> 0 votes

---
Tags: media, ubercart, nodes
---


# Question
Title: Files View, How to display Images related to Media Gallery?
I have created a view in views to show files of type image. Under fields I have selected File Rendered. Now my view is displaying all the images.

The problem is this that **I only want to display images which belongs to galleries created through media gallery module**.

# Answer
In my view under relationships I used **File: Content using Gallery media**. This is now showing the images which are related media Media Gallery.
> 0 votes

---
Tags: views, media
---


title: CKEditor - Apply Script

text:
# Question
Title: CKEditor - Apply Script
I got a script that will change headlines etc in the CKEdtior. I'm sure a lot of you have done this before. Talking about the ckeditor.styles.js

Now, where do I apply this script into CKEditor? I can't find it anywhere. Can somone walk me through of how do add it into CKEditor

Thanks!

# Answer
> 1 votes
You need to FTP into your site and go to `sites/all/modules/ckeditor/ckeditor.styles.js`. There is not an admin option to do this, which it sounds like you expected.

---
Tags: wysiwyg
---


# Question
Title: Subtheme: How to use the template function of a parent theme (from inside the parent theme)
I have created a theme that contains several functions.

I now want to create a sub theme. That way, I can use the parent theme on all my sites (and any updates to the parent the theme can be easily applied to all the sites). The sub theme will contain all the modifications that are specific to that individual website.

I have created a sub theme following the instructions in this tutorial. When I enable the subtheme, the site breaks. Most of the content disappears and I get this error message:

> Fatal error: Call to undefined function `legendary_views_field_compare_value()` in /all/themes/legendary/templates/slideshow.tpl.php on line 20

* `legendary_views_field_compare_value()` is the name of a function in my parent theme.
* legendary is the name of my parent theme.
* slideshow.tpl.php is a template in my parent theme.

I don't understand why this is happening. I thought the sub theme should inherit all the functions of the parent theme (especially is the function is being called from inside the parent theme and NOT in the sub theme).

How can I fix this?

# Answer
## **The problem**

Pay attention to your first sentence:

> I have created a theme that contains several functions.

The link that you have provided warns about what type of functions hold a `template.php` in a theme.

> There are two main types of functions in template.php: **theme function overrides** and **preprocess functions**. The template system handles these two types in very different ways.

Is legendary\_views\_field\_compare\_value() any of these cases? OK, we agree that the anwers is **No**. It's a custom function that you have written.

***Why should not you put your custom functions in `template.php`?***

Because Drupal has a registry of implemented hooks and templates that have been overriden. The system only load the `template.php` when match the hook in the registry. So, the `template.php` is not always load.

## **The solution**

First of all, you should keep separate the custom functions from the theme functions. You need to create a file called for example `my_custom_functions.inc` , and insert all your custom functions in that file.

***How do i load a file with custom functions that i need to call in my templates?***

To keep separate the logic from the theme functions, i would stored the custom functions in a module. But, it is also possible store the functions in your theme. In both cases, you have to follow the next strategy.

It's really easy. Every time that a template is rendered, a preprocess function is fired by default to let other modules to act. So, it is always fired a preprocess (and process) function before the slideshow.tpl,php. In this moment, we will load the file with our custom functions.

Here an example:

```
/*
 *  Implements hook_preprocess_slideshow()
 *
 *  The file will load  before rendering slideshow.tpl.php
 */
 function NAME_OF_YOUR_THEME_preprocess_slideshow(&$variables){

     include_once 'my_custom_functions.inc';
 }

```

Please, pay attention to the name of the template. In my simulation, i have changed the template called `views-slideshow.tpl.php` . So, when you implements in hook\_preprocess\_HOOK(&$vars) , you need to change the hyphens. The result would be `NAME_OF_YOUR_THEME_preprocess_views_slideshow(&$vars)`

If you have to load the same file with custom functions in lots of templates, you could implement the general `hook_preprocess($vars)`, that it is always fired. Here an example:

```
 /*
 *  Implements hook_preprocess()
 *
 *  The system always load the file
 */
 function NAME_OF_YOUR_THEME_preprocess(&$variables){

     include_once 'my_function.inc';
 }

```
> 1 votes

---
Tags: theming
---


# Question
Title: Can I recreate content types via db tables only?
My D7 (7.18) got corrupted, but just about functioned. However, I couldn't update modules, core or anything, so I took as many backups as I could and did a clean install of 7.24.

I'd like to recreate the custom content types and content I had in the old system (there's a lot). Can I import specific tables into the new MySQL db (from a MySQL export) and expect Drupal to pick it up ok? If so anyone know which tables I should bring in/merge.

Otherwise anyone got any suggestions for how to recreate content without a few weeks worth of cut+paste?

Thanks Sparks

# Answer
If you have a full backup, you could get the old version running locally.

Then

* Content: Migration (http://drupal.org/project/migrate) or Feeds (http://drupal.org/project/feeds)
* Content Types and other code-ish stuff: Features http://drupal.org/project/features
> 1 votes

---
Tags: nodes
---


# Question
Title: Drupal - Just want to add HTML to a node's form element how?
I have a node/content that outputs like a form that is available to guests to add jobs to. I would like to implement this HTML inside of the form to reduce spam:

```
<div style="POSITION: absolute; TOP: -1000px; LEFT: -1000px">
    <label for="address">If you see this, Leave Empty:</label>
        <input id="address" name="address" />
</div>
<div style="display: none;">
    <label for="username">If you see this, Leave Blank:</label>
        <input id="username" name="username" />
</div>

```

I kind of need this within the `<form>` tag.

Now when the form gets submitted, I'd like to be able to check for this and be sure both inputs are empty, and if they are empty, the form should be submitted, otherwise, if either is filled in with anything, it should not be allowed to be submitted. I did this on another, Non-Drupal, site and it eliminated the SPAM on that form completely. But now I'm on a Drupal site, and would like to understand how to do this via a node.

I don't currently have FTP Access, however, I do have complete Admin Access on the Drupal site, so if there is a way to do this via Drupal that would be preferable. Is there a module that will do something similar to this that I can add as a field on that node?

Any help to point me in the right direction on getting started for this is greatly appreciated. Also, I have the Devel Module installed if that helps...

# Answer
> 4 votes
Create own helper module. Use `hook_form_alter()`, specifically `hook_form_node_form_alter()` variant. In it, just add `#markup` element.

```
$form['my_markup'] = array(
  '#markup' => "Your HTML here",
);

```

But in content of your question, it seems you want more than own html. It looks like you want to add some active elements. So see Form API Reference for elements you need. To process values, you will need to define submit handlers.

---
Tags: 7, nodes, forms
---


# Question
Title: What would be the Alias for this 'User Edit' page link?
Working on a User Dashboard (using the Workbench Module), I have a link in a Views Block which the user can click to 'edit' their details. The current link looks messy (as shown below) and I would like to use an Alias to give a much more attractive frontend link Edit profile to reflect the page link and not the one as shown below. The current path links from the 'Edit Link' field in an Account Views Block and I'm using a 'Rewrite' as user/\[name\] within the path of the said field.

However, currently changing the link in Alias module gives me multiple errors trying with the likes of 'user/edit' path, what am I doing wrong, or is it an issue with Workbench?

\[http://localhost/sitename/user/46/edit?destination=admin/workbench\]

# Answer
please check this module, which should do the job for you

https://drupal.org/project/path\_alias\_xt

> Extended Path Aliases finishes the job left incomplete by core's Path module, fixing all of the above. And it does so automatically, without any configuration options or permissions to set and without requiring any other modules. Just install and you're away.
> 0 votes

---
Tags: views, path-aliases
---


# Question
Title: Drupal Static HTML content not rendering
Hoping all is well.. I have developed a personal theme and enabled it in a drupal installation. However static html doesn't show up at all.

I have used wysiwyg with ckeditor and enabled full html and still nothing shows up after saving. This happens with nodes and blocks. Only Plain text works and of course that doesn't implement html.

This problem's just began with this project. I have tried to create a fresh website and the problem prevails. I have even tried enabling garland (one of the default drupal themes) and i am still facing the same problem.

Has anyone faced a problem like this before?

# Answer
> 1 votes
Looks like it worked out after Upgrading Mysql (from 5.1.. to 5.5..) had php (5.4.17) now its 5.4.22 (guess there's no big difference there..). Thought i'd put it here incase anyone runs into such a weird problem in the future.

Thanks everyone for trying.. Really appreciate it!

# Answer
> 0 votes
make sure your Full HTML settings are as shown. As you see that there is no HTML, there is a strong probability that second option "Display any HTML as plain text" is enabled.

---
Tags: theming
---


# Question
Title: How to limit the list of nodes in a view based on a text field value?
Is it possible to show only Views content that passes a text in a given field?

For example, I have 3 content types and each content type has an identifier field (text field) which is hidden to the public.

So on my main content type, which is an information page, I list information about a football team. And then in the second content type I create results and a review of a match. And I display them as a view on the football team page (content type 1).

Content type 1 has a unique identifier, for example a text field saying "barcelona001". And this is the same on the "match results" content type field. How do I let views filter that, so that it only shows the right information?

If I can do this with a text field that would be great since I need to use a lot of taxonomy fields already to make it all work.

Any suggestions?

# Answer
1. Create a new view that displays content of all types.
2. Add your text field to 'Filter Criteria'. It looks something like this...

`Content: My Text Field Name (field_my_text_field_name)`
3. Select 'is equal to' and enter 'barcelona001' to the 'Value' field.
4. Press Apply (twice).
5. If you have the value already on some contents text field it should now display a list of matching content in the preview.

You would probably also benefit from contextual filters. Remember first to remove the field from 'Filter Criteria' if you added it earlier.

1. Choose 'Advanced' from the Views settings page. It should now show you 'Contextual Filters' setting.
2. Add your field.
3. Click Apply.
4. You can now write 'barcelona001' in the 'Preview with contextual filters' field.
5. It should display the result in preview.
6. See the 'Path' value in the views settings. You can go to that path and put whatever value you have used in the textfield after the path like this .com/my-page/

I hope this helps!
> 1 votes

---
Tags: 7, views
---


# Question
Title: Setting up Multiple Databases on a current site
I'm having issues with my current shared hosting provider due to my core database exploding upwards of 1GB due to cache\_form. I've been looking at trying to offload the cache and revisions databases into different databases entirely and set them away in order to hold down the load. I think my understanding of how is ok but I want to be sure as this is a current live site.

I declare the default database then declare where each table is explicitly in the prefix array. If this is accurate then I will just do it that way, if not then I'd like to know where I'm going wrong. Do I need to explicitly declare ALL my databases first in settings.php or do I need to declare just my default and let it work that way?

# Answer
> 0 votes
I think I figured out what to do in order to pull this off. The issue was that the documentation in default.settings.php was rather lacking but I managed to piece it together. You do have to set your tables up explicitly and your databases as well. It has not helped the issue at all, and frankly it concerns me due to the issues with Drupal 8 coming that frankly might not be usable. So I'm going to pursue a different course of action on this.

---
Tags: database, configuration
---


title: Manually sort Views output

text:
# Question
Title: Manually sort Views output
Is it possible to manually sort items from Views? I want to be able to define which content goes first and which one's last.

# Answer
DraggableViews was designed for just this purpose.
> 3 votes

# Answer
The best I've found is to add the integer field to your content type. Then just number your content items in the arbitrary order you want them. When you create a view, you can use that field as your sort, and update them any time. You can even reuse numbers to make a nested inner-sort, so all items with number 3 are sorted alphabetically, for example.
> 3 votes

---
Tags: 7, views
---


title: URL rewrites & Drupal functions

text:
# Question
Title: URL rewrites & Drupal functions
I have a server that hosts our Drupal 7 development, testing, and production environments:

* /var/www/html/dev
* /var/www/html/test
* /var/www/html/prod

Instead of having dev and test live in subdirectories like http://ourdomain.edu/dev, we want the URLs to be http://dev.ourdomain.edu.

From a Drupal standpoint, is this best accomplished through an .htaccess file in each directory? Or in settings.php?

At the moment, functions like path\_to\_theme() aren't working at http://ourdomain.edu/dev since path\_to\_theme begins with a forward slash. Consequently, the theme refers to http://ourdomain.edu/sites/all/themes/ourtheme/images/logo.png instead of http://ourdomain.edu/dev/sites/all/themes/ourtheme/images/logo.png

It would be great to know what's considered best practice.

Thanks!

# Answer
> 2 votes
If you are running Drupal in subdirectory named "dev". Then you need to put `$base_url = 'http://www.example.com'` in your settings.php. You may need to put `RewriteBase /dev` in your .htaccess but generally that isn't necessary for me.

If you want to run Drupal at `http://dev.example.com` that is purely an issue of configuring Apache correctly. Your likely need to change your httpd.conf or similar file to setup virtual hosting. Drupal won't need any changes.

---
Tags: uri, domain-access, subsites
---


title: Custom menu named arguments

text:
# Question
Title: Custom menu named arguments
i was wondering is it possible to create custom menu named arguments in D7. I can do this

```
function MY_MODULE_menu(){
  $items['my/callback/%user'] = array(
    ...
    'page callback' => 'MY_MODULE_callback',
    'page arguments' => array(2),
    ....
  );
}

```

and it will load the user entity. So instead i want to do this:

```
function MY_MODULE_menu(){
  $items['my/callback/%my_entity'] = array(
    ...
    'page callback' => 'MY_MODULE_callback',
    'page arguments' => array(2),
    ....
  );
}

```

and my custom entity to be loaded.

# Answer
Yes, name your function **my\_entity\_load** and it will be passed the id.

From the Drupal hook\_menu documentation (emphasis mine).

> Auto-Loader Wildcards Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule\_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule\_abc' part defines the prefix for a load function, which here would be named mymodule\_abc\_load(). When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments (see "load arguments" in the return value section below). **For example, your module could register path 'my-module/%mymodule\_abc/edit':**
>
> ```
>   $items['my-module/%mymodule_abc/edit'] = array(
>     'page callback' => 'mymodule_abc_edit',
>     'page arguments' => array(1),
>   );
>
> ```
>
> **When path 'my-module/123/edit' is requested, your load function mymodule\_abc\_load() will be invoked with the argument '123', and should load and return an "abc" object with internal id 123:**
>
> ```
>   function mymodule_abc_load($abc_id) {
>     return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
>   }
>
> ```
> 1 votes

---
Tags: 7, routes
---


title: Filtering a glossary view

text:
# Question
Title: Filtering a glossary view
I have a glossary view, which is just the one that comes with Views. I want to allow users to filter the results by taxonomy terms (dropdown) and also by title (search field). The problem I'm running into is that when I click on a glossary letter (e.g. X) then I try to type in a search term that begins with something other than X (e.g. Cat) I get no results. The title search filter is basically just searching within the selected letter in the Glossary. So if I'm on the X page and I search for Cat nothing is found. If I would search for X-ray then that would appear.

Is there any way to make the title filter relatable to the entire view result and not just things that begin with the glossary letter than I have selected?

In the attachment of the view I've tried turning on the "Inherit exposed filters" option but that does not help.

# Answer
> 0 votes
This can be solved by changing your Views filters to be connected using an OR instead of an AND. This option can be accessed by through the Views interface using the steps below.

**1.**

**2**

**3**

---
Tags: views
---


# Question
Title: Show views display based on exposed filter value
I've a views with 2 different displays which are Picture View and List View, both sharing the same exposed filter(the query string).

I have an exposed filter block, one of the exposed filter(Radio Button) is **View by: 1) Picture view 2) List View**

How to show the respective views result based on user selection (**View By filter**)?

**Updates:** My intention is to let the user to choose which Display she wants to see **before clicking** the Apply/Search button of the exposed filter block. There is only **ONE display at a time**, no tabbed/links for multiple display option. Solution similar to Views Mode module is not i looking for.

# Answer
> 1 votes
I find out two methods here.

Method 1: Use set\_display function

```
function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  $view->set_display('view_photo');
 }
}

```

Method 2: drupal\_goto (if the two displays are not sharing the same exposed filter)

```
function mymodule_views_pre_view(&$view, &$display_id, &$args)
{
 //To get the query string to find out the field value
$query = drupal_get_query_parameters($_GET, array('q', 'page'));

if( $query['viewby'] == 'photo')
 {
  //build up the the query string here
 $query['filter_a'] == 'xxx';
 drupal_goto('viewphoto_path',array('query' => $query));
 }
}

```

To my case, i used Method 2.

I am really new to drupal, and not sure are these methods will cause any problem or not. Let me know if they are ok.

# Answer
> 0 votes
May be Views Modes module can help you. It works different than you want, but this is an alternative method.

> A Drupal Views display plugin which provides alternate display modes that can be switched to for a single View. This allows exposed filter parameters or contextual filters to be kept active while switching display mode.

# Answer
> 0 votes
I guess this could help you getting ride of the problem,

I have created two view displays (as blocks)

* Block name: title\_image (Custom Themed with views-view-field--custom-view-theming--block-1--title.tpl.php)
* Block name: image (Custom Themed with views-view-field--custom-view-theming--block-2--field-image.tpl.php)

**views-view-field--custom-view-theming--block-1--title.tpl.php**

```
     <!-- Themed with node title, image and a small description -->

    <div class="main-content" style="float: left; clear: both;margin-bottom: 30px;">
    <a href="/?q=node/<?php print_r($row->nid);?>" title="<?php print_r($row->node_title);?>" style="float: left; padding-right: 20px;">
      <img width="170" class="bordered-image -align" title="<?php print_r($row->node_title);?>" src="sites/default/files/field/image/<?php print $row->field_field_image[0]['raw']['filename']; ?>" />
    </a>
    <h2>
     <a alt="" title="<?php print_r($row->node_title);?>" href="/?q=node/<?php print_r($row->nid);?>"> <?php print_r($row->node_title);?> </a>
    </h2>
    <div class="article-additional-info">
      <?php if($row->field_body) print $row->field_body[0]['raw']['value']; ?>
    </div>
    </div>
    <div style="clear: both;"></div>

```

views-view-field--custom-view-theming--block-2--field-image.tpl.php

```
     <!-- Themed with only node  image -->

    <div class="main-content image-only" style="float: left; clear: both;margin-bottom: 30px;">
        <img width="170" class="bordered-image -align"  src="sites/default/files/field/image/<?php print $row->field_field_image[0]['raw']['filename']; ?>" />
    </div>
    <div style="clear: both;"></div>

```

Both the contents are themed separately now we need to couple both the tpl files in a common place. Since both the displays are created as blocks we can add a comon wrapper in the following tpl views-view--custom-view-theming--block.tpl.php.

**views-view--custom-view-theming--block.tpl.php**

```
<div class="tab"> <!-- class="tab" is a wrapper for each tab-->
<input type="radio" name="tab-group" <?php if ($view->current_display == "block_1") print_r("checked")?>>
<!-- The above radio button is used to switch the tab , here we are controlling through css no js required-->
<label for="tab-<?php print_r($view->current_display);?>">Tab One<?php print_r($view->current_display);?></label>

<!-- The following are the common variables / template served by drupal-->
<div class="<?php print $classes;?>">
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php if ($header): ?>
    <div class="view-header">
      <?php print $header; ?>
    </div>
  <?php endif; ?>

  <?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

  <?php if ($attachment_before): ?>
    <div class="attachment attachment-before">
      <?php print $attachment_before; ?>
    </div>
  <?php endif; ?>

  <?php if ($rows): ?>
    <div class="view-content">
      <?php print $rows; ?>
    </div>
  <?php elseif ($empty): ?>
    <div class="view-empty">
      <?php print $empty; ?>
    </div>
  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>
    <div class="attachment attachment-after">
      <?php print $attachment_after; ?>
    </div>
  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>
    <div class="view-footer">
      <?php print $footer; ?>
    </div>
  <?php endif; ?>

  <?php if ($feed_icon): ?>
    <div class="feed-icon">
      <?php print $feed_icon; ?>
    </div>
  <?php endif; ?>

</div>
</div> <!-- END class="tab" is a wrapper for each tab-->

```

Add the following css :

```
    /** Tabbing Starts here**/

/** Drupal region class .region-content**/
    .region-content {
      position: relative;
      min-height: 200px; /* This part sucks */
      clear: both;
      margin: 35px 0 25px;
      background: white;
    }
    .tab {
      float: left;
    }
    .tab label {
      background: #eee;
      padding: 10px;
      border: 1px solid #ccc;
      margin-left: -1px;
      position: relative;
      left: 1px;
      top: -29px;
      -webkit-transition: background-color .17s linear;
    }
    .tab [type=radio] {
      display: none;
    }
/** Drupal region class .view-custom-view-theming **/
    .view-custom-view-theming {
      position: absolute;
      top: 14px;
      left: 0;
      background: white;
      right: 0;
      bottom: 0;
      padding: 20px;
      border: 1px solid #ccc;
      -webkit-transition: opacity .6s linear;
      opacity: 0;
    }
    [type=radio]:checked ~ label {
      background: white;
      border-bottom: 1px solid white;
      z-index: 2;
    }
    [type=radio]:checked ~ label ~ .view-custom-view-theming {
      z-index: 1;
      opacity: 1;
    }

```

Sample output :

---
Tags: 7, views
---


title: Shell problem with remote hosts

text:
# Question
Title: Shell problem with remote hosts
I'm having a problem when executing a drush command on a group of aliases that are all remote.

When I do this:

```
drush -y @group.host1 status -v

```

all works fine.

When I do that:

```
drush -y @group status -v

```

it fails with the following message for each host in that group:

```
ssh -o PasswordAuthentication=no host1 'DRUSH_PHP=/usr/bin/php drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1' 2>&1
fish: Unknown command 'DRUSH_PHP=/usr/bin/php'. Did you mean to ru
n drush with a modified environment? Tr
y 'env DRUSH_PHP=/usr/bin/php drush…'. See the help section on the set command by typing 'help set'.
Standard input: DRUSH_PHP=/usr/bin/php drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1

```

So, how I read the error it looks like fish (which is the shell used instead of bash) is having an issue with the command

```
ssh -o PasswordAuthentication=no host1 'DRUSH_PHP=/usr/bin/php drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1' 2>&1

```

Now what's the difference when I call the same thing for @group.host1 instead of @group? Then the command looks like this:

```
ssh -o PasswordAuthentication=no host1 'drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1' 2>&1

```

The difference is that the leading "DRUSH\_PHP=/usr/bin/php" is missing and then it works fine.

I have played around with /usr/bin/drush and removed the option --php="$php" from the last line in that file, and then everything works fine again too.

**Important:** This only happens since I've upgraded to Drush version 6.2 - before I had 6.0 on my local laptop and 5.9 on the host1.

# Answer
Drush was designed for use with bash, not fish. Would it be an option to make your login shell bash for your remote Drush user?

Your other option would be to submit a patch to Drush to fix this problem. There are two possibilities:

1. Modify Drush to use `env DRUSH_PHP=...` in backend invoke.
2. Modify Drush to not pass --php when --remote-host is set.

Option (1) may be harmful to remote sites where `env` is not in the PATH, so it may be a dubious proposition. It might be okay, though; `env` is probably in the PATH on most systems.

Option (2) seems better. There is little reason to think that the path to php will be the same on a remote system as it is on the local system, so Drush probably shouldn't be assuming that the php option is relevant for remote aliases, unless it was set in the alias' %path section.

Either of these actions would require a discussion in the Drush issue queue.
> 0 votes

---
Tags: drush
---


# Question
Title: Multilingual translation for anonymous users
I have enabled i18n module in my site. But it didn't work properly for me.

I have created two quizzes in three languages with english language as a source language. I am using language dropdown block for switching to different languages.

The problem is that, the quizzes are translating to corresponding language well for administrator and authenticated users. But the quizzes are not properly translated for anonymous users. It remains in english only. Same problem for basic page also.

I have checked permissions but I found there is no issue in permission. Please tell if anybody knows solution for this. Thanks in advance.

# Answer
I found solution for my problem. The problem is in row weight of url present in detection and selection method in the path admin/config/regional/language/configure.

The row weight for url was -5 and row weight for default method was -6. Then I changed row weight for url to -7. It works. Now the quizzes are translating properly for anonymous users also.
> 3 votes

---
Tags: i18n-l10n, quiz
---


# Question
Title: how to get the values of entity reference fields of a content type in a node page?
There is a content type in my website called `singer` and every singer may have `name` and some other information. there is another content type called `songs` and every song has two fields: (1) File (2) name. I also created an Entity Reference field in `songs` which links the song to a singer. obviously every singer may have any number of linked songs.

I listed the singers in a page and it must display every singer information and `songs` when the user click on any of the singers. this is my `template.tpl.php`

```
function MyThere_preprocess_page(&$variables)
{
    if (isset($variables['node']))
   {
        switch ($variables['node']->type)
        {
        case "singer":
            $suggest = "page__node__singers";
            $variables['theme_hook_suggestions'][] = $suggest;
            $variables['name'] = t($variables['node']->field_singer_name['und'][0]['value']);
            break;
        }
    }
}

```

I can get value of `singer` fields (using `kpr()`) but I don't know how to get the value of `songs` fields that are linked to a singer.

thanks

# Answer
> 5 votes
You can try this thing

```
// $node represents the node object
// field_songs is the field used in content type to reference field.
$wrapper = entity_metadata_wrapper('node', $node);
$songs = $wrapper->field_songs->value();

```

Now in `$songs` you will have each songs object and you can print what ever information you want to print from it.

# Answer
> 1 votes
one approach is directly quering the referenced field table. e.g.:

```
function MyThere_preprocess_page(&$variables)
{
  if (isset($variables['node']))
  {
    switch ($variables['node']->type)
    {
      case "singer":
        $suggest = "page__node__singers";
        $variables['theme_hook_suggestions'][] = $suggest;
        $variables['name'] = t($variables['node']->field_singer_name['und'][0]['value']);

        // I don't know what is your table's structure, correct ref.field table col names. Because they are wrong in my example:)
        $query = db_select('node', 'n')''
        $query->join('field_data_field_MY_REF_FIELD_NAME', 'fdfr',
          'n.nid = fdfr.field_MY_REF_FIELD_NAME_NID');
        $query->fields('n', array('nid'));
        $query->condition('n.nid', $variables['node']->nid, '=');
        $query->execute()->fetchCol();

        break;
    }
  }
}

```

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


# Question
Title: How to change the label of exposed grouped Filter field in Views?
Ok, I also have the Better Exposed Filters module installed and enabled on this view, but this does not help. I have no control over the label of this exposed filter that is being grouped. There is no option to change the label on grouped items, only on single items.

What do I have to do to be able to change the label? Am using Drupal 7.24 and Views 7.x-3.7 and Better Exposed Filters 7.x-3.0-beta3.

Thanks to anyone who can help... right now it is showing the machine label in parenthesis next to the actual title of the field. I'd rather just have only the title of the field.

Here is what the settings look like for an exposed grouped filter to me:

And here is what the filter looks like on the actual view:

How to get rid of the (field\_department) text or change the label completely?

# Answer
Normally you can remove field machine name from the configuration itself as shown below, but seems like those portion is hidden from your screenshot. Please check those portion, also check this troubleshoot Can't set the label for an exposed grouped filter.

If still no help you can use hook\_form\_alter(&$form, &$form\_state, $form\_id) to change the label
> 2 votes

---
Tags: views
---


# Question
Title: duplicate order_number in commerce/orders
I have a shop implement with drupal commerce, I have a problem, I have 2 method on payment method1 and method2, in payment step, when user select method1 and go to bank to pay,it has a order record in `commerce/orders` , when the payment with method1 not successful in `commerce/orders` ,status is processing, after payment with method1 not successful drupal come back to payment step and if user select method2 I see another record with same order\_number in `commerce/orders`, The problem is here when the user accomplish payment with method2 , the 2 record status field will set to "completed" and manager of site dont understand finally by which method payment finished,

anybody know where is the problem and how can correct it?

# Answer
> 0 votes
Finally I found the solution for my problem, the problem came from relation of views to product\_order table, I just go to that views and revert views. and worked

---
Tags: 7, commerce
---


# Question
Title: In search result page, pagination is not showing up
I have migrated a site from Drupal 6 to Drupal 7. I have rendered the search form in page.tpl.php as follows:

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

```

I am able to search, but pagination is missing in the search result page.

In the theme folder I have search-results.tpl.php and **search-results.tpl.php**.

In the search-results.tpl.php `<?php print $pager; ?>` is available.

**If I change theme to default theme or core theme pagination is working fine.**

What is the issue over here which is causing not showing pagination links?

# Answer
i don't think that this will help you but do it like this:

```
// template.php
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

```

page.tpl.php:

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

```

according to this discussion. You should not put your logic into tpl.
> 0 votes

---
Tags: 7, search, migrations
---


# Question
Title: How to just show front page and message when search api search was queried with blank input
How can I just show front page when no letters were printed in search input, but it was submitted?

And optionally maybe show message 'please enter the terms of the search'

I thought of doing this with Rules, but no rules considering searches are present(

# Answer
Here is a solution:

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

  if($form_id == 'search_block_form' || $form_id == 'search_form') {
    array_unshift($form['#validate'], 'custom_search_validate');
  }
}

function custom_search_validate($form, &$form_state) {
  dpm($form_state);
  if(isset($form_state['values']['search_block_form']) && $form_state['values']['search_block_form'] == FALSE) {
    drupal_set_message('please enter the terms of the search', 'error');
    drupal_goto();
  }

  if(isset($form_state['values']['keys']) && $form_state['values']['keys']
    == FALSE) {
    drupal_set_message('please enter the terms of the search', 'error');
    drupal_goto();
  }
}

```
> 3 votes

---
Tags: search
---


title: How do I consume REST as a client?

text:
# Question
Title: How do I consume REST as a client?
I need to import on node save information from a third party REST server and map that data to an entity that references the node saved. There will be a field in the node that the user can input an id that is passed in the url of the REST call. The REST call will return an XML object that needs to be mapped to a new entity that is referenced to the node.

How is this done? Are there an examples of Drupal 7 modules that do this?

# Answer
> 11 votes
Normally, I just roll my own.

I use a combo of drupal\_http\_build\_query and drupal\_http\_request to make the request. I then use drupal\_json\_decode to parse JSON results, or simplexml\_load\_string to parse XML results.

When possible, I try to abstract out all of this into a PHP class as a singleton, which also includes static caching and/or caching via cache\_set/cache\_get for the actual requests. I will then wrap up everything as a normal Drupal module.

Invariably, the service I am consuming will have something odd about it that precludes using a generic solution. Also, I don't find the generic solutions any simpler than a custom one.

# Answer
> 1 votes
You can also use Web Service Clients module. It is a perfect match when consuming from drupal Services module but it also can be used with other REST API.

# Answer
> 0 votes
Have you looked at REST Client? It's not for production use (currently) but is a good place to start if you don't just want to use drupal\_http\_request against whatever API you're hitting.

---
Tags: 7, nodes, importing-exporting
---


title: How to add JQuery code to drupal site

text:
# Question
Title: How to add JQuery code to drupal site
I am trying to add my JQuery code to my drupal 7 site.

In my drupal based site i have image in the featured block. My JQuery code slides up the image after 2 seconds.

When i added the JQuery code to my page it is showing the JQuery code on the page.

Here is my code:

```
<script src="/drupal/sites/default/files/js/jquery.min.js"></script><script>
$(document).ready(function(){
    $(".sec1").slideUp(7000);
});
</script>

```

when i save the configuration, below codes are displayed in web page.

```
$(document).ready(function(){
        $(".sec1").slideUp(7000);
    });

```

How can i solve this?

# Answer
If you don't know how to add your js code to drupal, there are two ways:

1. Create js file in your `theme_folder/js`, e.g, scripts.js, put your code into that file, open .info file of theme and add `scripts[]=js/scripts.js`
2. Create a js file as I wrote above and open template.php of your theme and put

```
drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/scripts.js', array('type' => 'file', 'group' => JS_THEME));

```

in `YOUR_THEME_preprocess_page()`. (This is not an ideal way, but it shows how you can use a drupal\_add\_js() function)

also read documentation for more info.
> 3 votes

---
Tags: views, javascript, 7
---


# Question
Title: Multistep form loses input when visiting previous step
I am developing a custom module with the ability to store data on an external database using Drupal 7 Form API. I started with the multistep form example, added few more steps and other fields.

To implement the ability to edit those data I created a class that retrieves returns an array suitable to fill the $form\_state\['values'\] element in order to have a default value for each form element. Here follows the code I have in the form callback when going to edit my data:

```
if( !empty($form_state['build_info']['args'][0]) ) ) {
    $a = new ind();
    $a->get_ind( $form_state['build_info']['args'][0] );

    $form_state['values'] = get_object_vars($a);
    unset($a);
}

```

Problem is when I hit the previous/next buttons because of the form is being rebuilt always with the data from the class so every change in a field is lost when hitting "Previous"; suddenly every change gets lost when I click "Next" after "Previous" (fields are empty!).

How do you achieve editing with multistep form with existing data? I am stuck here attempting to put the code above at submit and previous handlers with no success.

# Answer
I think you should add `if` statement with `#triggering_element` or `#clicked_button`. Example:

```
function PREVIOUS_STEP_submission_OR_SOME_KIND_OF_CALLBACK($form, &$form_state) {
  if($form_state['clicked_button']['#value'] == 'BACK') {
    //show_previous_step()
  }
  else {
    $a = new ind();
    $a->get_ind( $form_state['build_info']['args'][0] );

    $form_state['values'] = get_object_vars($a);
    unset($a);
    // or your logic
  }
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Is there any way to validate taxonomy terms?
Is there any way to validate a taxonomy term before it will be saved? I'm using Simple Hierarchical Select with its "add new item" functionality. I would like to enable this option for registered users. They are not completely trusted though. What I would like to do is to create some limit on number of terms that can be added, for example per day. This is a ajax callback of SHS that creates new terms:

```
function shs_json_term_add($vid, $parent, $term_name) {
  if (!user_access('edit terms in ' . $vid)) {
    // Sorry, but this user may not add a term to this vocabulary.
    return FALSE;
  }

  $term = (object) array(
    'vid' => $vid,
    'parent' => $parent,
    'name' => check_plain(filter_xss($term_name)),
  );
  // Save term.
  $status = taxonomy_term_save($term);

  // Return term object or FALSE (in case of errors).
  return ($status == SAVED_NEW) ? array('tid' => $term->tid, 'name' => $term->name) : FALSE;
}

```

As you can see, it basically checks permissions and saves term by using `taxonomy_term_save($term);` . Would there be a way for validating this term without patching SHS module?

# Answer
there are these lines in shs.module:

```
$callbacks = array(
    'shs_json_term_get_children' => array(
      'callback' => 'shs_json_term_get_children',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_array',
        'settings' => 'is_array',
      ),
    ),
    'shs_json_term_add' => array(
      'callback' => 'shs_json_term_add',
      'arguments' => array(
        'vid' => 'is_numeric',
        'parent' => 'is_numeric',
        'name' => 'is_string',
      ),
    ),
  );
// Let other modules add some more callbacks and alter the existing. (!)
drupal_alter('shs_json_callbacks', $callbacks);

```

I think we can do something like this:

```
function MY_MODULE_json_callbacks(&$callbacks) {
  $callbacks['shs_json_term_add']['callback'] = 'CUSTOM_CALLBACK';
}

function CUSTOM_CALLBACK($vid, $parent, $term_name) {
  if(!NEW_CONDITIONS) {
    return FALSE;
  }

  return shs_json_term_add($vid, $parent, $term_name);
}

```
> 3 votes

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


# Question
Title: How to make a content type a Ubercart product
Basically I want to add the "add to cart" button to a content type. I've got Ubercart installed and enabled. Normally whilst editing a content type there should be a section "ubercart product settings" where I can check "products... are shippable"

But there's no such section to make it a ubercart product.

# Answer
> 4 votes
Go to admin/store/products/classes.

From there you'll be able to assign a product class to an existing content type, after which you should see the Ubercart-specific settings on the content type edit form.

---
Tags: nodes, ubercart
---


# Question
Title: Taxonomy Menu: Display Descendants does not work
> I could not find any good answer to this question online, so I decided to post it with the answer I found as it might help some people, I hope so :)

I am using Drupal 7.

In taxonomy menu 1.4 module, if you check option "Display Descendant" , nothing change in your menu.

In taxonomy menu 2.0alpha2 module, if you select the similar option: "Menu path type =\> Multiple terms" , the items in your menu that have descendants vanish from your menu

How to get this to work ?

# Answer
With taxonomy menu 2.0alpha2 if you select multiple you'll see the warning : "Multi-terms path is not available in Drupal by default, which means that you will have to register it using a module like Views for example."

Luckily views provide by default a taxonomy term view to emulate drupal default taxonomy term handling, so you need to activate it. But even with this view activated you wont see your menu items, and this is because the path generated by taxonomy menu(ie: taxonomy/term/tid1+tid2 ) is still not handled.

This is because default taxonomy term view handle multiple terms ids argument but does not validate them (WTF !?).

So what you need to do in a nutshell:

> 1. In taxonomy menu 2.0alpha2 module, select "Menu path type =\> Multiple terms"
> 2. Activate taxonomy term view
> 3. In \[ Contextual filters =\> Content: Has taxonomy term ID (with depth) =\> Specify validation criteria =\> Filter value type \] change to "term IDs separated by , or +"

There you go !

ps : I did not try this with taxonomy menu 1.4, anyone ?
> 0 votes

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


# Question
Title: Drupal paid subscription manager where nodes are removed upon expiration
I would like to charge my users to post content. For example, 1$ per node/ week that it's visible.

Now I know there are many subscription modules. But how can I manage a subscription system with re-occurring payments, which also automatically interacts with my website and makes changes in real time. For example - how can I have nodes 'expire' after 2 weeks if the user only pays for two weeks.

Are there any combination of modules people would recommend to use to implement such a system? I was thinking of Ubercart, UC Node Checkout, Node Published, however these are D6 modules and i've been on D7 for a while.

# Answer
> 1 votes
You want Commerce License, a framework built exactly for that. You can write a custom license type that creates / deletes the node when the license status changes (and it would be a good candidate for a generic contrib).

The recurring side is handled by Commerce License Billing.

EDIT: There is now a Commerce License Node project too, doing what I described.

# Answer
> 0 votes
Did you check this out http://nicksantamaria.net/article/commerce-subscriptions? Using this module you can purchase role and the expiry of the role is set by rule schedular

---
Tags: 7, ubercart, commerce, notifications
---


title: Specific user-based admin view

text:
# Question
Title: Specific user-based admin view
For testing whether Drupal 7 runs on an local nginx server:

One of the user should get more rights than an editor/writer, but less than an admin. Is there a way to create a 2nd specific admin role without certain permissions (e.g. Admin VBO Views)?

Regards, bolshii

# Answer
I am not 100% sure, but I think you just need to create a new role and specify what the user can do and what he cant? I have for example a role which can add new content and nothing more. So they see the admin bar in the top and it only lists add content :) and which types of content they can add.
> 0 votes

# Answer
Go to http://example.com/admin/people/permissions to see and change the permissions for administrative, authenticated and anonymous users.

On the upper right hand side of the screen, click 'roles'. On the next screen, you can add a role. Use the handles on the left to position the new role above administrator, since it will have only slightly less permissions.

Now, go back to the permissions page to adjust the permissions.

If the default permissions are not granular enough, install contributed modules like nodeaccess.
> 0 votes

---
Tags: views, users
---


# Question
Title: Problem with mobile_theme theme switcher module
I've tried using mobile\_theme to switch to a selected mobile theme when a mobile visitor browses. But using online mobile emulators: mobilephoneemulator.com and transmog.net I found that half of pages get shown as Desktop version pages.

I thought of using ThemeKey but I'll need to use browser version, operating system to serve mobile content. But it could fail for Googlebot, Bingbot etc, they also need to see my mobile pages.

Is there any alternative auto theme switcher for mobile? I'm on shared hosting and can't use Browscap etc php modules.

# Answer
> 0 votes
mobile\_theme wouldn't work with Drupal cache on. It is not mentioned anywhere in the documentation. We should use m.example.com for mobile url's for Drupal. I tried many such modules except for ThemeKey but the same problem( since I was using the cache).

I finally wrote my own module. But later found : simple\_mobile\_redirect to be good one but have not tried yet.

# Answer
> -1 votes
For one language site, you can use Mobile JS Redirect module for Drupal 7.

> This is a simple module that adds a JS in the HTML head to perform a redirect from a desktop site URL to a mobile one or the other way around. This is useful when Varnish or any other reverse proxy cache is being used to cache your site and keep a mobile vs desktop redirect working.

---
Tags: 7, theming
---


title: Change pathauto generated URL of node

text:
# Question
Title: Change pathauto generated URL of node
Does anybody know where/how to change the pathauto-URL of a node (that comes out of the db table "url\_alias")?

Background (Example):

I have a page with list of nodes (A, B, C)

A -\> links to "clean-URL/A.html" B -\> links to "clean-URL/B.html" C -\> should not link to "clean-URL/C.html" but to "clean-URL/A.html" (C has a field that says it should link to A)

So, I want that everywhere there is a link to C, the link should be changed to A. For example in search results or in views.

Unfortunately I can't find a pathauto hook that does something like "render\_pathauto\_link\_of\_node"...

# Answer
> 1 votes
I found what I needed. It is the function hook\_url\_outbound\_alter...

```
function myModule_crawler_url_outbound_alter(&$path, &$options = FALSE, $original_path){
    $mother_nid = $options['entity']->field_mother_series_nid["und"][0]["value"];
        if( $mother_nid > 0 ){
            $path = "CLEAN-URL/".$mother_nid;
            $options['alias'] = "CLEAN-URL/".$mother_nid;
        }
}

```

Thanks for helping!!!

# Answer
> 0 votes
I'm not really sure exactly you are trying to ask here, but if you use drupal's l() function, it will return a link utilizing the aliases, eg:

```
$foo=l('Click here to goto bar','node/' . $nid);

```

will create a link using the url alias of the node in question (assuming of course that `$nid` contains an actual node id).

You could use this in custom PHP code or in a PHP field in Views, but, I am also thinking you could use Views' field rewriting along with tokens to accomplish this as well if it is based upon a reference field inside another node as well that is included (and then hidden) in the View's fields.

ADDITION based upon commentary:

You could take a dull ax to this and do something along these lines in hook\_init()...

```
function YOURMODULE_init() {

  $mgo=menu_get_object();

  if (!empty($mgo-> /* whatever field you are talking about in your content */ )) {

    $nid= /* get the node id from that field */ ;
    if ($nid && $nid!=$mgo->nid) {
      drupal_goto('node/' . $nid);
    }

  }

  // any other init stuff from your module goes here

}

```

...which would do the redirect upon page load so your users might see their browser address bar change quickly at the beginning but would end up at the right place.

*Also realize you'd never be able to edit the node again without further logic added into the above :)*

---
Tags: views, hooks, path-aliases, uri
---


# Question
Title: Comparing entity against previous entity in views
Say my view lists people and their salaries using data from their profile..

```
Abby, 10000, O
Amelie, 10000, O
Alan, 15000, O
Ben, 15000, O
Bertie, 20000, O
Boris, 20000, O
Carl, 20000, O
Carol, 25000, O
Derek, 25000, O

```

How can I change the third column to an X when the salary changes?

```
Abby, 10000, X
Amelie, 10000, O
Alan, 15000, X
Ben, 15000, O
Bertie, 20000, X
Boris, 20000, O
Carl, 20000, O
Carol, 25000, X
Derek, 25000, O

```

I'm guessing I do it in hook\_views\_pre\_render($view), but there are so many variables/objects in the $view, I don't know where to start.

I don't think it matters, but I'm using views\_data\_export to output this into a CSV.

# Answer
Probably late by now, but have you tried using revisions? You can pull in individual fields that has any revision.
> 0 votes

---
Tags: views
---


title: What is "Main page content" block?

text:
# Question
Title: What is "Main page content" block?
what is "Main page content" block?

and why do I get "Region for Main page content block field is required." when I disabled it?

I have commerce kickstart installed

# Answer
Main page content block is the primary content of whichever page you are viewing.

Removing does not normally make sense.
> 1 votes

---
Tags: commerce
---


# Question
Title: Two database? One for user & content the other for structure?
For site builders like me who do not do much programing but theming of existing modules and functions. Since those items such as views, panels, user badges, rules, points e.g. are written into the database. It makes updating a lot harder.

Is it possible for Drupal to be able to store user data, and user created content, and messages on one database(say A) and everything else on database (B)?

THe idea behind this is that this way it will allow me to easily update site structure (views, panels) without affecting production data created from the users.

Is this possible and or doable?

# Answer
> 1 votes
In theory, perhaps.

In practice, I think you're in for a world of pain.

Others frequently solve your problem by instead exporting configuration using Features.

That is also the direction in which Drupal 8 is headed, with the CMI Initiative.

---
Tags: database
---


# Question
Title: Display Node or Entity Reference Content
I can't seem to figure this one out.

Goal: To allow the back end user to select from a list of "leasing contacts" when creating a "property." And have the view show the full content of the "leasing contacts" selected.

So far I have a Content Type for "leasing contacts" with several contacts in there. I have a Content Type for "properties" which has an Entity Reference field that references the "leasing contacts." This works great on the back end, the user can select from the numerous "leasing contacts" when creating the "property". HOWEVER, I can't seem to understand how to get a view to show the full "leasing contact" content. The view only displays the "leasing contact" name in plain text. How can I get the view to show not only the "leasing contact" name, but all of the other field content that's in the entity.

Any pointers would be much appreciated!

# Answer
The keyword you are looking for here is 'relationship'. You want to create a relationship between your two content types using your entity reference field. Once this is enabled, all the fields available for the 'leasing contact' field will be available.

This tutorial from NodeOne is the best out there for explaining the process: http://nodeone.se/en/using-entity-reference-in-views
> 1 votes

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


# Question
Title: Which hook to use when a date is going to be saved into the database
I have a situation where I would like to know when a date (for an event) is going to be saved into the database so that I can modify the corresponding date in another module to match it. That is it in a nutshell. I need to do this because of the way this other module works. What is the best hook to use to accomplish this? Is it hook\_node\_update?

Thanks.

# Answer
If you are only using nodes then yes, implementing `hook_node_update` is a good approach. You also will need to implement `hook_node_insert` if you need to do logic when the nodes are first created.
> 0 votes

# Answer
If its node as it seems to be you can use hook\_node\_update which will act when an existing node is updated and hook\_node\_insert which will act when a new node is inserted so here you will be using two hook or you can use hook\_node\_presave which incorporate both events insert and update.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Implement structure like wikipedia on node
I want Implement structure in drupal like wikipedia, register user can change the node content but if admin(a role for this job) approve them the updated node show to user,else the old version ( not changed ) show. drupal has revision feature but this it applied and not wait for admin approve the changes,any way exist in drupal to achieve this job? In before project I did something like this but It was about user profile not on content, I used profile module ,but here I want work on content and nodes .

# Answer
> 2 votes
You can setup a content moderation system for nodes using the Workbench Moderation module

---
Tags: 7, nodes
---


# Question
Title: Unable to add WHERE conditions as OR to query object
I'm attempting to override the query method for a node migration in the migrate\_d2d module by adding two where conditions with "OR", and the first one is being added as AND instead of OR for some reason. In this case, there is already one WHERE condition of node type, so I am adding two more, which means I'm trying to change

```
SELECT blah from {node} WHERE type = 'type1';

```

to

```
SELECT blah FROM {node} WHERE type IN ('type1', 'type2', 'type3');

```

It doesn't look like it is possible to override an existing WHERE condition without completely overriding the entire query method, so it seems that my next best bet is to add the WHERE conditions with OR so that the resulting query is

```
SELECT blah FROM {node} WHERE (type = 'type1') OR (type = 'type2') OR (type = 'type3');

```

To accomplish this, based on what I've found searching around (such as here), I used db\_or():

```
$db_or = db_or();
$db_or->condition('type', 'type2')
  ->condition('type', 'type3');
$query->condition($db_or);

```

However, when I print out the resulting query what I actually get is

```
SELECT blah FROM {node} WHERE (type = 'type1') AND (type = 'type2') OR (type = 'type3');

```

and this is verified by the migration results, since the migration doesn't bring across any nodes (which makes sense, since one node can't be of two types).

I also tried it with separate additions to $db\_or:

```
$db_or->condition('type', 'type2')
$db_or->condition('type', 'type3');

```

and even tried adding as one condition:

```
$db_or->condition('type', array('type2', 'type3'), 'IN');

```

but the result is still the same.

What it looks like to me is that no matter how you add a WHERE condition when there already is one, it automatically adds the next one as AND, even if you specify that it should be OR.

So my questions are:

* Am I adding these conditions to the query object correctly (assuming I want them as OR)?
* Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?
* Is there a better way to do this?

Thanks.

# Answer
> Am I adding these conditions to the query object correctly (assuming I want them as OR)?

Not quite; all components of the the `OR` need to be added to the condition object, so you need to do something like this:

```
$query = db_select('node')->fields('node', array('nid'));

$db_or = db_or();
$db_or->condition('type', 'type1')
  ->condition('type', 'type2')
  ->condition('type', 'type3');

$query->condition($db_or);

```

That'll give you this query string:

```
SELECT  node.nid AS nid
FROM
{node} node
WHERE ( (type = :db_condition_placeholder_0) OR (type = :db_condition_placeholder_1) OR (type = :db_condition_placeholder_2) )

```

> Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?

Yes you can use `SelectQuery::where()`, but there's really no need. You can use the above, or preferably...

> Is there a better way to do this?

Yes, by using `IN` as you originally planned:

```
$query = db_select('node')
  ->fields('node', array('nid'))
  ->condition('type', array('type1', 'type2', 'type3'), 'IN');

```

That gives:

```
SELECT  node.nid AS nid
FROM
{node} node
WHERE  (type IN  (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2))

```

Note that the third parameter of "IN" to `condition()` isn't strictly necessary, as the DB class automatically assumes "IN" if an array is passed.
> 1 votes

---
Tags: database, migrations
---


# Question
Title: How do I provide one-time access to a downloads page to anonymous users?
Our company wants to have a secured downloads area for software. We want to send a link to a customer via email, after they have purchased a license for the software. We don't want to create a site account for every customer; we just want them to click the link to get one-time access to the downloads page. All the modules I have seen for one-time use links either assume that the link is something used for password reset, etc., or the module is not ready for prime-time.

Any ideas?

Thanks!

# Answer
> 0 votes
No need to write a new module. One of the modules that I referred to as "not ready for prime-time" is a module called "Deep link". I had said that because there seemed to be some bugs with the use of one-time-only links. After looking at the code for a few days, I was able to fix a couple issues and submitted patches back to the project page. The module now works well enough to suit my purpose, and I would recommend it!

# Answer
> 0 votes
You need write a module to do this job, I wrote a module that do something like this ( count download times )

```
<?php

/**
* Implements hook_menu();
*/
function bicuk_downloadounter_menu() {

    $items=array();
    $items['download/%']=array(
        'title' => 'increase Download counter ',
        'description' => t('callback url for increse Downloading count'),
        'page callback' => 'downloadcounter_tickup',
        'page arguments' =>array(1),
        'type' => MENU_CALLBACK,
        'access callback' =>true,

    );
    return $items;
}

/* call back function to increase counter
 * @param $fid , file id
 */
function downloadcounter_tickup($fid){

   if(!is_numeric($fid))
              drupal_goto();
   $file=file_load($fid);
   if(!isset($file->fid))
            drupal_goto();
   $acceptable_ext=unserialize(variable_get('bicuk_downloadounter_valid_extensions'));
   $file_path=file_create_url($file->uri);
   $pathinfo=  pathinfo($file_path);
   $extension=$pathinfo['extension'];
 if(!in_array(strtolower($extension), $acceptable_ext))
             drupal_goto();
   $query=  db_select('bicuk_downloadcounter_counter','bdc')->fields('bdc',array('count'));
   $query->condition('fid',$fid, '=');
   $count=$query->execute()->fetchField();
if($count)
{
    $query=  db_update('bicuk_downloadcounter_counter')->fields(array('count'=>$count+1));
    $query->condition('fid',$fid, '=');
    $query->execute();
}
else
  {
    $query=  db_insert('bicuk_downloadcounter_counter')->fields(array('name','count','fid'),array($file->filename,1,$fid));
    $query->execute();
  }
   drupal_goto($file_path);
}

/**
 *
 * @param type $fid fid
 * @return type int count
 */

function downloadcounter_get($fid){
   $query=  db_select('bicuk_downloadcounter_counter','bdc')->fields('bdc',array('count'));
   $query->condition('fid',$fid, '=');
   $count=$query->execute()->fetchField();
   return $count;
}

```

**you can get idea from this code to achieve your job,instead of counting download time try to check downlading time by IP and do your limitation**

---
Tags: navigation
---


title: use title content as existing field

text:
# Question
Title: use title content as existing field
I have created content type with multiple entries some of them have term reference / autocomplete.

Why cant i do that to the title for the content type? Is there a way I can make that happen?

Also why can't I use the title in other content types?

Attached image with title .

# Answer
> 0 votes
The reason you can't use the title as you wish, is because it's not a `Field`, but a `Property`.

Unfortunately I can't find a meaningful explanation of the difference between the two at this time, so no link, sorry.

If it helps in any way, you can create your own title field, which will then behave more like you expect. Of course, you'll then have two "titles", so this will various annoying side effects.

---
Tags: nodes
---


title: Where is tmp file directory?

text:
# Question
Title: Where is tmp file directory?
Strangely I cannot find this directory anywhere inside sites or files. There is only one in /var would that be it? I need to edit the .htaccess as it states in my reports. Also what ownership and permissions should this display?

Ok I found it in directory above /var and deleted it then created it again and set it as 755 permissions with apache ownership and placed security script in .htaccess as given in reports link.

Update: the .htaccess in files and tmp folders to create more security shut me out! I had to remove them. OKAY finally worked this out and why looking for tmp folder in first place! A status report glitch error for files and tmp folder saying needed to add security .htaccess file is BOGUS! it is a bug of some sort in 7.24 for my system Centos linux so my removing them was exactly what I needed to do after adding erroneous security updates.

# Answer
Look in your Drupal admin area at `/admin/config/media/file-system`

This will tell you where Drupal thinks it's `tmp` folder is currently set to.

Depending on your host provider you may or may not be able to write to that location.

The php-info report found on your Status Report page `admin/reports/status` can tell you where PHP's temp directory is defined to be on your system:

`upload_tmp_dir no value`

Using htaccess, or `ini_set` in `settings.php` you can tweak where the upload temp directory is for your Drupal installation if need be.
> 2 votes

---
Tags: files
---


title: How to add picture to every panel?

text:
# Question
Title: How to add picture to every panel?
I am using the panels module and the mini panels modules.

I have mini panel with two section (left and right). For my design, I want to add a picture on the left side of each section. These pictures are not supposed to come from any node or content, they are just pictures for design purpose only.

How can I do that? If you suggest CSS, I will be happy to understand how?

I am a newbie, and building my first Drupal site, so I will appreciate any help.

Thanks.

# Answer
All your panels have a common class. Probably .panels. You need to see if your left panels also have a common class, probably .panel-left or something. You can use your browsers element-inspector to see this. It will show you something like this (simplified example) if you select your node that has panels:

```
<div class="panels">
  <div class="panel-left">
    content
  </div>
</div>

```

This gives you a clue where to set your background in CSS.

```
.panels .panel-left {
  background:url('path/image');
}

```

You need to find classes that the elements you want to style have in common, but are unique enough so that you style only those.
> 1 votes

---
Tags: panels
---


# Question
Title: Automatic way to delete users with no content
I have created an artist registry that needs help deleting users that have not created a content type node "Artist Page".

I can find ways to delete users that are inactive, but in this case, some users might be inactive for years if nothing on their page has changed.

Preferably, I would first like to send a reminder email notice to users without an "Artist Page". When a user registers within the site they are instantly directed to fill out their artist page, but some users are only registering and not filling out their page, and of course, some registration spam is getting through.

Once an email is sent, and if no content is provided after a certain amount of time, I would like to delete them from the system to keep the site as clean as possible.

Any help would be greatly appreciated.

# Answer
> 0 votes
if I understand you correctly then you have somekind of users and one content type "Artist Page". That users must fill (create) a node of that Artist Page content type. but some users may skip this step. In that case you can do following I think:

1. `node` table has a `uid` field (author of content).
2. Fetch separately (as array) uids of `node` and `users` tables and compare them;
3. Get difference of arrays and compare there created time with current time, if difference is reaches(notification time) then send them an email, if difference is reaches(deletion time) then delete them.... These operation can be done on cron job. I recommend Elysia cron module.

Example:

```
function MY_MODULE_cronapi($op, $job = NULL) {
  $items['my_custom_task'] = array(
    'description' => 'My custom task description',
    'rule' => '*/20 * * * *', // Example rule - execute job every 20 min
    'callback' => 'my_custom_task',
    'arguments' => array(),
  );

  return $items;
}

function my_custom_task() {
  $subquery = db_select('node', 'n');
  ->fields('n', array('uid'))
    ->condition('n.type', 'MY_TYPE', '=')
    ->execute()
    ->fetchCol();

  $uids = db_select('users', 'u')
    ->fields('u', array('uid', 'created'))
    ->condition('u.uid', $subquery, 'NOT IN');
  ->execute()
    ->fetchAll();

  if(!$uids) {
    foreach($uids as $key => $uid) {
      $user_id = $uids[$key]->uid;
      $user_created = $uids[$key]->created;

      $notif_time_min = time() + 60*60*24*7; // example
      $notif_time_max = time() + 60*60*24*8; // example

      $del_time = time() + 60*60*24*15; // example

      if((time() - $user_created > $notif_time_min) && (time() - $user_created < $notif_time_max)) {
        // send_email()
      }
      elseif(time() - $user_created > $del_time) {
        //del_user()
      }
    }
  }
}

```

//P.S: I'd recommend to modify the callback part of cronjob. You can have too many users and every time cron job queries the tables(users and node tables) for existence of left users; Good solution will be creating a custom module which holds somekind of flag, which verifies that user is valid or not, you can flag as unverified on registration and change to verified on creation on node. This can be achieved by Rules or Action or custom code...

---
Tags: users, emails
---


# Question
Title: Getting all the nodes NOT tagged with a taxonomy term
I am a bit stuck with this... I am not a drupal expert (yet :D) so I really don't know if I am using the best approach...

I have few nodes tagged with some terms from a vocabulary. Let's say my node 1 is tagged with term 1 and node 2 is tagged with terms 2 and 3. My vocabulary has, let's say, 5 terms in total.

Is there a way of getting in a view all the nodes NOT tagged with a particular term? This mean if I had a content node in a view tagged with term1 (node 1 in our example) I could get in another display of that view (or even in another different view) a list of the remaining terms not tagged (2, 3, 4 and 5 in my example).

I know I can make it using "static" filters, but I need to extract the information (terms tagged) from the node itself, which is loaded dynamically using contextual filters.

I am using panels as well but I am not sure wether that details are worth explaining for my porpoise.

I hope my question is clear enough as English is not my mother tongue.

Thanks in advance for your help.

# Answer
> 0 votes
Finally I ended up width different approaches to this problem. The simplest one:

1. Use a contextual filter in views.
2. Use the option "Exclude" at the end of the form (under "More" tag). This way you can get all the nodes NOT tagged with the term passed to the contextual filter.

¡Hope this can help to someone else!

# Answer
> 0 votes
1. Create a new views page
2. Select/Add the node related fields that you would like to refer while filtering the nodes.
3. Add a filter to filter the nodes by content type
4. Add a filter: Taxonomy term: Term
5. Select: Expose this filter to visitors, to allow them to change it
6. Select: 'Expose operators' and 'Reduce duplicates'
7. Save the filter and view.
8. Now go run the url of the views page.

You will see the filter at the top of node fields. 1. Select the filter as (Operator: Is none of) and select the term (Term 1) as per your eg. 2. Click apply button 3. You will see all the nodes which are not tagged to Term 1

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


# Question
Title: Are there any benefits/caveats with using Entity Reference over Term Reference?
Pretty simple question really, but is there any benefit to using a core term reference field over an Entity Reference field?

Obviously tagging is not really an option with Entity Reference, but I've used the Inline Entity Form for creating new terms from a node page and it works fine (I prefer it over tagging if my terms have fields).

*tl;dr*

Apart from tagging are there any benefits/caveats with using Entity Reference over Term Reference for referencing taxonomy terms?

# Answer
> 21 votes
Swings and roundabouts really, it depends on your use case...

Behind the scenes there's essentially no difference - both field types relate one entity to another by way of an ID, so it really comes to down which type provides you with the 'frills' you need/want.

As you mentioned Taxonomy has the open tagging widget, which is nice, but then Entity Reference has Views integration (by way of Entity Reference View Widget) which means you can define as complex a view as you like for your selection widget. Also very nice.

And then there's Inline Entity Form which you also mentioned. That's a superb tool obviously, but only really useful if you *need* it in your project.

What Taxonomy has going for it is that it's part of core, and doesn't require a bunch of other modules installed to work. But then in a normal Drupal build a lot of those modules will probably already be there. It also maintains a term index table for nodes which can help with performance, but obviously only if you're relating your terms to node types.

I think your choice is going to come down to what widgets/formatters you need for a particular situation to be honest, it's too tight to call :)

# Answer
> 10 votes
Just thought I would add to this discussion that it looks like term reference will be deprecated in D8. So it seems with all the pros of entity reference you may want to avoid using term reference on new sites as it will just be more of a pain to migrate later when you move to D8.

https://drupal.org/node/1847596

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


# Question
Title: Really strange WSOD after submitting a form/add to cart
I've read everywhere, but just can't seem to find an answer for my particular problem.

Basically when I click 'add to cart', or 'login'. I get a white screen of death with absolutely no errors. Error reporting is on.

For example:

* I am on a product page mydomain.com/product
* I click add to cart
* I am not redirected to the cart page, it just redirects back to mydomain.com/product except the page is completely blank
* The form still submits successfully however. If I navigate to the cart page the item has been successfully added.
* After I have viewed the cart page, by manually navigating to it in the browser. Adding any other item to my cart works as expected.

A similar issue happens when I login to the backend. At first I get a WSOD, but if I refresh the page it works fine.

Now here is where it gets really damn strange.

I suspected that perhaps it was a cookie issue, so after I logged in I decided to delete the session cookies from my browser. I was hoping that I could replicate the issue once more. However, the problem had disappeared, no WSOD even though I had deleted my cookies.

The next day the issue returned. I logged into the backend and the issue disappeared. To confirm that the issue had disappeared entirely, not just for me. I asked a friend on a computer in another building to visit the site and attempt to add an item to cart. He said it worked fine.

Every morning the issue returns predictably and only when I login to the backend does the issue disappear for everybody for the entire day until the next day.

Has anyone experienced similar issues or have any idea what this could be? I'm on drupal 6.26 using ubercart

# Answer
> 0 votes
I had a similar issue a year and a half ago. But in my case, it was **Drupal 7** with **Ubercart**. Drupal had the same behaviour that you has described in your post.

If my memory serves my right, the problem was that references to the products when the cart is executed. They are stored in 2 different ways:

1. If you are a authenticated user (you have an account on a drupal site), the references to the products added to the cart are stored in database. Concretely, in a table called **\*uc\_cart\_products\***. If you log out, the products remain safely in database until the user log in again. So, the user doesn't miss any information.
2. If you are an anonymous user (not authenticated), the references are stored in database as in step 1, but you have a radomly generated token that is stored in Cookies to identify you . The cookie has a limited time of life, so finally, the cookie will be deleted.

When the cart is built, Ubercart take that reference from cookies if it's needed and load the products. But, i had deleted some products manually from database ( i know, it's a bad deccision ), so when the system try loading a product that hadn't exist, the system failed and appeared WSOD.

To solve this problem:

1. I deleted manualy all lines in **\*uc\_cart\_products\*** database table. If you have lots of records, only delele your products. Each record has an user id or a token assigned to identify who is the user.
2. Log out and delete the cookies

---
Tags: ubercart, wsod
---


title: create a custom field schema

text:
# Question
Title: create a custom field schema
When I create a new field programmatically, drupal create a default schema for my being added and for each new field added is create a new database schema. I noticed that the columns always have the same structure except for the last column 'FIELD\_NAME\_value'.

entity\_type | bundle | delete | entity\_id | revision\_id | language | delta | FIELD\_NAME\_value

I have many fields that have the same "entity\_type" and "bundle".

Can I create programmatically a single schema that contains all of them?

Thanks!

# Answer
No, it won't be recognized by Field API. By default Drupal uses Field Api and Field Storage API to store field data. It creates two tables for every new field which you create from Field UI (field\_data\_\* and field\_revision\_\*). If you are able to create your own Storage for Field Api then you can use it... Here are some resources:
> 0 votes

# Answer
I would like to point out some things to improve the answer of @xurshid29:

1. The schema of your fields don't have to be **equal or uniform**. A field could contain more attributtes than you expect. Take a look to next hook, called hook\_field\_schema. With this hook you can add more attributes to your field, and the hook build a new column in database for each new attribute. You can find several shared modules in Drupal that apply their own fields and have a different number of columns in database.
2. The attributes that you have noticed in the schema are common in all fields.
3. Try to reuse fields previously created. A field could be attached to different entitys and bundles. You don't need to create, for example, a date field if you prevoiusly created one for your *article* content type.
> 0 votes

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


# Question
Title: Have To Recreate Feature After Rollback - Features Module
I have strange issue. I have several node instances included part of the packaged feature XXX that service as test pages. These node instances have two fields - the default body and extra text field 'description'. When I install this feature for the first time on new Drupal site, everything works. If I roll back via Migrate\_backup or physically dropping all tables, the second time installing the same feature all body fields is coming up empty and the extra field 'description' is not installed at all

There is no messages in the watchdog log. My current versions:

```
Feature 7.x-2.0
uuid_features 7.x-1.0-alpha3
fe_block 7.x-1.0-beta1
strongarm 7.x-2.0

```

I also tried this with newest dev versions of uuid\_features, fe\_block, strongarm, but the same issue

My solution is recreating feature with different name but its unnecessary extra work and time. Have you ever experienced this issue? How would you troubleshoot? Can i enable some kind debug mode for feature installation or any module for that matter? I may be just doing it wrong as this my first experience with Features module. Thank You

# Answer
It turns out the feature is in 'overridden' state

```
drush fl name_on_feature

```

If I did revert

```
drush fr name_on_feature

```

Then that solved my problem but i am still puzzled. If I drop tables, then how is it detecting 'overridden' state. Does Features module has some local file cache used for handling states?..just thinking loud. To my understanding revert updates database according to the code of the feature.
> 1 votes

---
Tags: 7, features
---


title: /tmp folder still not writeable

text:
# Question
Title: /tmp folder still not writeable
> PDOException: SQLSTATE\[HY000\]: General error: 1 Can't create/write to file '/tmp/#sql\_e0f\_0.MYI' (Errcode: 13): SELECT DISTINCT SUBSTRING\_INDEX(source, '/', 1) AS path FROM {url\_alias}; Array ( ) in drupal\_path\_alias\_whitelist\_rebuild() (line 380 of /var/www/html/includes/path.inc).

After noting report status for updating .htaccess in this tmp folder i found in root directory I then changed permissions to 755 and ownership apache:apache also tried owner:apache Anyway, when tested and trying to delete content as admin it throws above error.

UPDATE: All of this occurred due to erroneous status report for drupal 7.24 saying needing to add security update to files and tmp folder .htaccess but it is a bogus bug and you need to delete them then run cron will recreate and status report disappears.

SEE http://www.ostraining.com/blog/drupal/drupal-724-tmp-directory/

problem solved

# Answer
You need to find the user your server is running with (or the owner of files and folders). If your drupal is working correct besides this error then go to your website root and type `ls -l` in terminal. It will show you something like this:

```
-rw-rw-rw-  1 www-data charlie 6604 aug  8 04:04 authorize.php
drwxrwxrwx  3 www-data charlie 4096 nov 12 13:02 cgi-bin
etc.

```

Here you see the owner (www-data) and the group (charlie). This can be different on your system, but remember which you have for the chown-command below.

Give your /tmp folder the same owner. Go to `/admin/config/media/file-system` on your site and see the path to your tmp folder. If it starts with a '/' then it's located in the root of your system. If it doesn't start with a '/' then its relative to your website-folder, tmp for example is then really /var/www/httpdocs/tmp.

Then use `chown -R www-data:charlie /path/to/tmp` and you should be good to go. When you use your systems tempfolder at /tmp you really should create and set a subfolder inside /tmp.
> 2 votes

# Answer
Two possible issues there, disk space or write permissions.

**Disk space**

You could out of disk space in the /tmp folder, try

```
df -h

```

to list disk free space. Your query could be very large if many url aliases to process.

**Write permissions**

The error isn't actually apache / php but rather a mysql error. The query is trying to write to the /tmp folder to store additional temporary data. You need to make sure the /tmp dir is also writeable by the mysql user. Easiest way is

```
sudo chmod 777 /tmp

```

Alternatively, you could make it `775` (recommended) and add the mysql user to the same ownership group for write access.
> 1 votes

# Answer
I usually do it like this (if I have a FTP access to my project):

1. Create a new tmp or temp directory in root folder of my drupal installation;
2. Give it 777 permission (what owner is not matter I think);
3. Open admin-\>configuration-\>file-system;
4. Enter my recently created folder name to Temporary folder input field (WITHOUT ANY SLASHES);
5. It's done;
> 0 votes

# Answer
I had this issue and removed the forward slash from it and it worked, took me hours to work that out. It was "/tmp" and I changed it to 'tmp'. Thought I should mention just in case.
> 0 votes

---
Tags: files
---


title: How to position elements within views?

text:
# Question
Title: How to position elements within views?
I have a view which is displaying a content type with text and image (1 column grid). Right now, the image is positioned under the text. Is it possible to position the image to the right?

Is this possible without using custom css? Or if it isn't, which css file should i be looking for? (Haven't done custom css yet)

# Answer
The best way to accomplish a floating image is to have some custom css: http://css.maxdesign.com.au/floatutorial/

Anyway, the drupal module Media can help you alot. Please follow this complete and well explained article: http://purewebmedia.biz/articles/2013-01-10/how-insert-and-float-inline-images-drupal-7.
> 0 votes

---
Tags: views, media, theming
---