# Question
Title: Organic Groups - define content type to be of Group type
I am using the Organic Groups module and am following the readme file. I am on step 2 and already struggling...

Create a new content type via admin/structure/types/add. Call it "Group", and define it to be of Group type.

How do I define it to be of Group type?

I have enabled the following modules: Entity Reference 7.x-1.0 Organic groups 7.x-2.0 Organic groups access control 7.x-2.0 Organic groups context 7.x-2.0 Organic groups field access 7.x-2.0

# Answer
> 2 votes
On the create content type page you should have a vertical tab named `Organic Groups`. If this tab is missing, make sure you have enabled the `Organic groups UI` module. Clicking the `Organic Groups` tab reveals a couple of check boxes. Check the one for `Group` and hit save to make this content type a group which you can associate content with.

The other check box `Group content` defines that the content type can be posted into a group, i.e associated with the group you previously created.

To get you started you can also enable the `OG example` module.

The above is mainly for OG 7.2.

# Answer
> 0 votes
Here are tutorials you might find very useful. Both are for (7.x-1.0). I've watch both many times & used them to build a demo site.

---
Tags: organic-groups
---


# Question
Title: How to require one of two fields to be filled out?
Let's say i have two fields in a content type. An integer field and a text field (two options with select list widget) and i want the user to fill out one of the two. Can someone help me achieve this ?

Thanks

# Answer
> 3 votes
Have a look at the Conditional Fields module.

---
Tags: 7, entities
---


# Question
Title: Is there a way to limit / enforce permissions on image style downloads?
I have a few image styles that I only want certain node types to be able to view because certain images on my site have an open license for use and so I have a style for a large image gallery view, while others do not and so they shouldn't use this style.

The images, and the image styles are stored in private locations and served through Drupal.

Is there a way I can set conditions on when an image style can be downloaded for an image; for example by node type, a field flag, or who a user is logged in as?

Is there another solution to this issue?

# Answer
This is not really possible. The module the create this doesn't care or know where the image comes from, so you can't make any permission checks like that. It would be possible to display such images through custom theming Views and many other ways which makes a 100% failsafe permission check more or less impossible.

You can make sure nothing like this will happen based on how you setup your site, and you could add some extra security by overwriting the settings/rendering for image fields, but it won't be 100% fail safe.
> 3 votes

# Answer
There is no access handling on image styles, only on images/files.

The only way to do this would be to completely override the page callback the menu entries in image\_menu() for the public and/or private file system, then copy the image\_style\_deliver() function and change it.
> 1 votes

# Answer
The problem, I think, is that you are trying to do this through a single field. Create two image fields (e.g. Public image and Private image or whatever you want). Set whatever image styles you want on them. Then use the Field Permissions module to protect the private field to only display when a user with the right privileges is logged in (you could also hide from displaying the public one, so they don't get confused as to which one). Then, as long as your image styles folder is in the Drupal's private folder they should be protected from anyone wanting to access the image styles directly.
> 1 votes

# Answer
You can use the Image Style Access module to control access to images by style and file location.
> 1 votes

---
Tags: 7, media
---


title: Search through page titles?

text:
# Question
Title: Search through page titles?
Is the Search module supposed to search through the node/page titles, or just the node content?

Because, for me it is only searching through the content, and not the page titles.

Note: I am using Drupal 7.

# Answer
> 1 votes
You didnt say what version of Drupal your using, but if you are using D6 check this out Views Search

If not then check out Views

Then I guess you just have to get the node titles and make them as a exposed filter. So you will need to expose 1 Filter, one for the node title and then also check out Autocomplete Filter

This link can also help you Views Exposed Filter Search

Update :

You might also wanna take a look on this, if your not to happy about using Views , Its more integrated to the Search API Custom Search Module

# Answer
> 0 votes
Try Search configuration

This module has five main functions.

1. Alter the appearance of the core node search form
2. Group content types for more meaningful searching
3. Restrict search results by the content type.
This is a role based restriction.
4. Restrict search results from showing individual items.
Use search\_config 7.x-1.1-beta2 or above.
5. Alter the pager limit (aka number search item results per page).
Usesearch\_config 7.x-1.1-beta1 or above.

---
Tags: 7, search
---


# Question
Title: Prefill taxonomy term reference field while in term page
I have a content type A with a required term reference field (vocabulary: category, widget: radios). I would like to accomplish the following:

In every term page (of this specific vobaulary) i will have an "add type A" link. When the node/add form appears (upon clicking on this link) i want the value of taxonomy term reference field to already be chosen as the category term which corresponds to the specific term page. Ideally i would like the above and also to dissapear this field from the form.

Any help?

# Answer
There is a module for this and it's called Entity reference prepopulate.
> 2 votes

# Answer
When you define the field for the content type, you can set a default. Then you can use the Fields Permissions module to restrict access to the field the the admin role. If the user does not possess the required role, they will not have access to the field on the edit form.
> -1 votes

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


# Question
Title: Using Contextual Filter to Filter "Entity Selection" on Node Edit won't pull Raw Value From URL
I'm trying to filter the values available in an Entity References "Entity Selection" list on a node edit form to only show nodes relevant to the current node being edited.

I am using views and have selected the "Views: Filter by an entity reference view" for the Entity Selection Mode.

In my view I have created an Entity Reference Display with a contextual filter. I have tested that the contextual filter works the way I want it to by using "Preview with contextual filters" and entering a sample ID to filter on (1200). It filters just fine.

When I use "Display all results for the specified field when the filter value is not available" all the results display on the node edit form. But as soon as I choose "Provide a default value" -\> "Raw Value from URL" then nothing is displayed on the node edit form.

I have checked that the raw value is in the URL: content/assembly/1200 (1200 being the value that works in the "Preview with contextual filters") and am using the right path component to reference it and ticking or unticking "use path alias" makes no difference.

Does anyone know why this would not be working?

Thanks very much.

# Answer
> 0 votes
Try Content ID from URL instead of the Raw Value.

---
Tags: views, entities
---


title: Can't reorder items in Text formats

text:
# Question
Title: Can't reorder items in Text formats
On Drupal 7.15, I cannot save reordered draggable items at /admin/config/content/formats. That is the dialog with all text formats and their options, and dragging them in order force their order of appearace.

I am able to drag items and reorder them, but after saving, items returns in previous order, in spite Drupal says "The text format ordering has been saved."

I do not have clue yet how to troubleshoot this issue, as there is no error anywhere.

# Answer
This was very strange issue, now solved, but can't texactly the point that solved it, as i ran extensive code/config sweep both on code / server side. (Including Apache restarts, MySQL restarts, module maintance (many unused gone with the wind), APC configs, and running registry rebuids.
> 0 votes

---
Tags: input-formats
---


title: Displaying translated taxonomy terms

text:
# Question
Title: Displaying translated taxonomy terms
I am trying to achieve a multilingual site that shares its content across all the (currently two) languages, so the same content resides under the same term no matter what language is currently active.

I've been told that I should use the i18n module, which I did. So right now I have all the names of the terms translated in both languages, so that is all working as it should.

The problem is that when I change the language to, for example, Arabic, all the term titles are still in English, even though I have a nice list of translated Arabic counterparts.

So the question I would like to ask is: is there a way to get Drupal to replace all the English terms with the Arabic ones wherever a term's name is displayed? (so make it behave as if every term name has been run through Drupal's t() function)

Most people who tried to answer this question just suggested I use the i18n module. So yeah, I already did that. **I have the translations for the term names, but when changing the language, the term names are still in English**

Any help would be greatly appreciated

**Edit**: Please note that I am not talking about a specific module here. For example, when I go to the admin panel's "Add Node" page, I have a drop-down box filled with terms that I have translated, with the language set to Arabic, and yet they still show up as English. This goes to show that it does not work with Drupal Core modules, so it is not likely to be caused by a poorly coded module per se.

# Answer
> 1 votes
Fixed, the problem was that the translations did not have the correct context linked to the translation.

---
Tags: 7, taxonomy-terms, i18n-l10n
---


# Question
Title: Prevent Drupal from auto-caching pages in all translations
After clearing the cache, Drupal generates cached versions of every node/page that gets visited. Which is fine.

However – if I visit the German version of a node/page, not only the german version will be cached, but also all the translations of that specific node.

(Normally, this wouldn’t be a problem, but I have a custom input filter working which detects the current language and changes things in the text accordingly. This input filter has only access of the current system language, not the language of the currently filtered node. Which leads to wrong results.)

Can I prevent the automatic caching of node translations?

# Answer
> 2 votes
So there is a function called drupal\_page\_is\_cacheable() which you can call, on a site, in order to avoid the caching, so you could for example call that on your uncachable filter.

# Answer
> 1 votes
I had the same problem with node translations being cached. After some backtracing I found that the module responsible for loading and caching translated versions of the node is the Translation core module.

The function `translation_node_view` implements the `node_view` hook to create links to the translated versions when viewing a node. There is an option to disable showing these links in the translation options, but this hook will run anyway, causing the translated nodes to load and consequently be cached.

Too fix the problem you have to disable the hook in the translate module. But since hacking the core is not a good option, try instead to 'unhook' it by adding the following function to your own module:

```
function YOURMODULE_module_implements_alter(&$implementations, $hook) {
    if($hook == 'node_view') {
        unset($implementations['translation']);
    }
}

```

This code removes the hook from being cached by drupals hook system. Keep in mind that this will completely disable the translated links when viewing a node. If that is not a problem then this solution should work. More info about the affected hook can be found here: translation\_node\_view

---
Tags: 7, i18n-l10n, caching, input-formats
---


# Question
Title: Is there a rule condition to check if the url is the front page?
Just wondering if is there a rule condition to check if the url is the front page of the site?

# Answer
I dont think there is such a rule, but you can do this: add a rule for `User is going to view page` and in condition add PHP snippet and check for `drupal_is_front_page()` based on this add actions as desired.
> 3 votes

---
Tags: rules, database
---


title: Not passing the clean URL test

text:
# Question
Title: Not passing the clean URL test
We've got a multi-site install on Amazon's AWS that used the Bitnami Drupal image (ami-3f21aa56 - 64bit, Unbuntu) as a base. Per the documentation, each site has it's own subdirectory in the sites folder. Each site has a corresponding DNS A record that is pointed at our server. Drupal handles the traffic via the **sites.php** file and that's been working well so far.

Now I'm trying to implement Clean URLs and the test continues to fail. I've played with the Rewrite settings in the .conf files per various recommendations around the web but nothing has worked so far.

mod\_rewrite is enabled. My current drupal.conf file is:

```
# App url moved to root
DocumentRoot "/home/bitnami/apps/drupal/htdocs"
#Alias /drupal/ "/opt/bitnami/apps/drupal/htdocs/"
#Alias /drupal "/opt/bitnami/apps/drupal/htdocs"

<Directory "/home/bitnami/apps/drupal/htdocs">
    Options +MultiViews
    AllowOverride All
    <IfVersion < 2.3 >
    Order allow,deny
    Allow from all
    </IfVersion>
    <IfVersion >= 2.3>
    Require all granted
    </IfVersion>
</Directory>

# Uncomment the following lines to see your application in the root
# of your URL. This is not compatible with more than one application.
# RewriteEngine On
# RewriteRule ^/$ /drupal/ [PT]

```

The htaccess.conf (I believe this is Bitnami's way to have a global .htaccess for drupal 7, including multisite config) is as follows (apologies for the length):

```
<Directory "/opt/bitnami/apps/drupal/htdocs/">
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
# Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

php_value memory_limit 64M

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

</Directory>

```

When it comes to server configuration, I am lucky to spell Apache. I've played with a few settings but I am feeling quite out of my depth, especially with regard to Drupal Multisite. If someone can point me in the right direction, it would be very much appreciated.

Thanks!

Scott.

# Answer
> 1 votes
Sounds like it might be a similar problem to http://drupal.org/node/488188

* edit /etc/httpd/conf/httpd.conf
* Under \<Directory /var/www/html\>
* change AllowOverride None to AllowOverride All

---
Tags: 7, uri, multi-sites
---


# Question
Title: Views - how to display a column showing who made the last update
I'm updating the main content2 view, and I'd like to add another column to show which user made the last update. I'm using workbench moderation, in case that makes any difference.

# Answer
1. Edit your content type's Publishing options & enable 'Create new revision'.
2. In Views' Advanced pane, add a Relationship of type 'Content revision: User'.
3. Under Fields, add the field 'User: Name' AND use the relationship you just created.

Voilà!
> 1 votes

# Answer
1. Download revisioning
2. In your view fields section you will now find a new option called **Content: Last edited by**
> 0 votes

---
Tags: views, users
---


# Question
Title: How can I throw a form error if a submission field has a certain value in webform?
I am using mymodule\_webform\_submission\_presave() to alter some of the data before it gets saved. I want to check if a certain select field has a certain option selected, dont save the form to the db and give the user an error like "you may not pick this" and dont save the form.

I would remove the option itself from the form but this wont be possible.

I've also tried to do it via the webform gui but there is no rule which says "this select may not have this option selected", is there?

Thanks!

# Answer
> 2 votes
Create your own validation function of your webform and do it there:

```
function modulename_form_webform_client_form_FORMID_alter(&$form, &$form_state, $form_id) {
     //FORMID - your webform id
    $form['actions']['submit']['#validate'][] = 'modulename_form_webform_client_form_FORMID_validate';

}

function modulename_form_webform_client_form_FORMID_validate($form, &$form_state) {
    //validate it here
    if ($form_state['values']['yourvalue'] == 'somevalue') {
        form_set_error('you can\t do that');
    }
}

```

also you can use `hook_form_alter` to provide your own validate function. Further reading form\_set\_error, hook\_form\_alter,

# Answer
> 1 votes
You would have to hook\_form\_alter your form and add your own validation function like:

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR-FORMS-ID') {
   // ADD YOUR OWN VALIDATOR TO THE VALIDATORS ARRAY
   // use devel module and dpm($form)
   $form['#validate'][] = '_my_module_validate';
  }
}

```

then you could write the validator

```
function _my_module_validate(&$form, &$form_state) {
   if($form_state['values']['your-element'] == 'some-forbidden-value'){
     form_set_error('my-module-error','ERROR MESSAGE');
   }
}

```

---
Tags: webforms, forms
---


title: Workflow - sms/email notifications

text:
# Question
Title: Workflow - sms/email notifications
Is there a way to set up sms/email notifications to be sent out to site users responsible for each workflow stage? Also, is there a way of automatically "assigning" a node to the correct resource for managing the workflow stage?

# Answer
> 0 votes
Check out the rules module. You can set up a rule that accesses other module (search for a sms module), or core features (like mail).

---
Tags: workflows, notifications
---


# Question
Title: VIEWS: How can i Related (CONCATENATE) current_user to content fields?
DRUPAL ROCKS!

I need your help! in a website i am currently working with. i have 700 active users with the following users field: -Name, Sure name, last name, worker number.

And i created a content type called: Turns.With the fields: title, body, full name, turn's date, worker number.

One of the main goals of this website is that in the moment that the user logs in he will have a button that say my turns, and he will just see his "turns".

i need to be able to related in a view, some how, user's worker number with turns (content, node) worker number field in order to show just user "turns".

view=user(work number field) + turns(work number field) and off course display all the turn fields.

any help will be really really appreciated...

love drupal!

# Answer
> 0 votes
You can create a Relation (on the right side), Here you can link to a author. Create a filter that filters on the current loged in user. This should do the trick.

---
Tags: views
---


# Question
Title: Exporting settings in a code with Features / Strongarm - how to detect right variables - config ones
Many modules does not support Features, so I need Strongarm module to export config in the code. But in situation where i have many contrib modules, it seems tedious work. not all variables are named after module.

More important, how can I know which variables are used for settings, as I noticed some vars are not used for settings but may be user/module specific, and I need to aviod them.

I want to Strongarm only variables that have to do something with the config.

Is it done by researching modules one by one ? What are your experiences (It would be nice if I could filter variables that are used only in config :) )

# Answer
> 3 votes
Unfortunately, the Drupal variables table doesn't provide any distinction between **variables used for configuration** (e.g., whether anonymous pages should be cached) and **variables used to store transient values** (e.g., date cron was last run, which tabs are currently active in the UI), so there's no automatic way to do this. *(Fortunately, it looks like Drupal 8's configuration management system will handle this better.)*

I typically export and update Features modules from the command line using Drush. I've been using the following **Unix shell script** to list Features Components which haven't yet been exported to any feature — the script **filters out Features Components I know I don't want in my Features modules**:

```
drush fc % --not-exported \
    | grep -v '^ dependencies:' \
    | grep -v '^ user_permission:access devel information' \
    | grep -v '^ user_permission:execute php code' \
    | grep -v '^ user_permission:switch users' \
    | grep -v '^ uuid_node:' \
    | grep -v '^ variable:additional_settings__active_tab_' \
    | grep -v '^ variable:cron_key' \
    | grep -v '^ variable:cron_last' \
    | grep -v '^ variable:ctools_last_cron' \
    | grep -v '^ variable:date_api_version' \
    | grep -v '^ variable:dev_mem' \
    | grep -v '^ variable:dev_timer' \
    | grep -v '^ variable:devel_api_url' \
    | grep -v '^ variable:devel_error_handlers' \
    | grep -v '^ variable:devel_execution' \
    | grep -v '^ variable:devel_krumo_skin' \
    | grep -v '^ variable:devel_page_alter' \
    | grep -v '^ variable:devel_query_display' \
    | grep -v '^ variable:devel_query_sort' \
    | grep -v '^ variable:devel_raw_names' \
    | grep -v '^ variable:devel_rebuild_theme_registry' \
    | grep -v '^ variable:devel_redirect_page' \
    | grep -v '^ variable:devel_use_uncompressed_jquery' \
    | grep -v '^ variable:devel_xhprof_directory' \
    | grep -v '^ variable:devel_xhprof_enabled' \
    | grep -v '^ variable:devel_xhprof_url' \
    | grep -v '^ variable:drupal_css_cache_files' \
    | grep -v '^ variable:drupal_http_request_fails' \
    | grep -v '^ variable:drupal_js_cache_files' \
    | grep -v '^ variable:drupal_private_key' \
    | grep -v '^ variable:entityreference:base-tables' \
    | grep -v '^ variable:features_codecache' \
    | grep -v '^ variable:features_ignored_orphans' \
    | grep -v '^ variable:features_semaphore' \
    | grep -v '^ variable:install_profile' \
    | grep -v '^ variable:install_task' \
    | grep -v '^ variable:install_time' \
    | grep -v '^ variable:mimemail_key' \
    | grep -v '^ variable:prod_check_module_list_lastrun' \
    | grep -v '^ variable:simplenews_last_cron' \
    | grep -v '^ variable:simplenews_last_sent' \
    | grep -v '^ variable:simplenews_private_key' \
    | grep -v '^ variable:simplenews_source_cache' \
    | grep -v '^ variable:update_last_check' \
    | grep -v '^ variable:xmlsitemap_generated_last' \
    | grep -v '^ variable:xmlsitemap_rebuild_needed' \
    | grep -v '^ variable:xmlsitemap_regenerate_needed'

```

---
Tags: features, strongarm
---


title: How to map a URL to an attachment

text:
# Question
Title: How to map a URL to an attachment
I'd like to have a simple and clean URL for a PDF file, such as

```
http://www.examples/file1

```

that maps to an attachment in a Drupal node, rather than using something like

```
http://www.examples/sites/default/files/files/file1.pdf

```

I've tried using URL Aliases, but Drupal complains and won't let me create the alias. I can obviously do this with Apache redirects (with mod\_rewrite) or (gasp!) with a meta tag refresh, but both seem inferior to being able to manage it from within Drupal.

# Answer
> 1 votes
You can use File Aliases module for this.

---
Tags: 7, files, uri, path-aliases
---


# Question
Title: Fatal error: Call to a member function fields() on a non-object
I have the following code that is throwing an error:

```
/**
 * Custom content function
 *
 * Get system status from the helpdesk database
 *
 * @return
 *   An key => value pairing of systems and their status
 */
function system_status_sjhc_status_check() {
    //connection info for the helpdesk database
    $helpdeskDB = array(
            'database' => 'mydb',
            'username' => 'myuser',
            'password' => 'mypass',
            'host' => 'myhost',
            'driver' => 'mysql',
    );
    Database::addConnectionInfo('helpdeskDB', 'default', $helpdeskDB);
    db_set_active('helpdeskDB');

    //grab the current light status
    $result = db_select('hd_lights', 'l')
        ->fields('l')
        ->leftJoin('hd_status', 's', 'l.id = s.id')
        ->fields('s', array('stamp', 'message'))
        ->orderBy('`order`', 'ASC')
        ->execute();

    db_set_active(); // without the paramater means set back to the default for the site

    return $result;
}

```

The error I'm receiving is:

> Fatal error: Call to a member function fields() on a non-object

and its being thrown on this line:

```
    ->fields('s', array('stamp', 'message'))

```

I can't figure out what I've done wrong, everything looks OK to me and the code runs fine without the join and additional table fields.

Any thoughts?

# Answer
`SelectQuery::join()`, `SelectQuery::leftJoin()` etc. don't return the query (they return the alias to the created JOIN), so they can't be chained.

Just separate your code out like this:

```
$query = db_select('hd_lights', 'l')
  ->fields('l')
  ->fields('s', array('stamp', 'message'))
  ->orderBy('`order`', 'ASC');

$query->leftJoin('hd_status', 's', 'l.id = s.id');

$result = $query->execute();

```
> 18 votes

# Answer
This is how you suppose to write db\_select with join (leftJoin in your case)

```
   //grab the current light status
    $result = db_select('hd_lights', 'l')
        ->fields('l');
    $result->leftJoin('hd_status', 's', 'l.id = s.id');
    $result->fields('s', array('stamp', 'message'))
        ->orderBy('`order`', 'ASC')
        ->execute();

```
> 1 votes

---
Tags: database
---


# Question
Title: Enable modules across platforms using Features/Drush
I am wondering, could this be automated.

1. I download and enable contrib modules on @dev
2. I push files on @live (including new modules)
3. via Features/Drush I tell @live to enable new modules, so servers are in sync.

I do some needed disabling/enabling of dev modules when doing sql-sync to @dev, but this is case when I install new modules on @dev and want them on @live automagically when I commit.

I could, of course, do **drush @live en \[modulename\]** for each module I installed on dev.

# Answer
Yes, this could be automated. I'd suggest the missing component is git or possibly another source control tool, so you can create commits that represent complete sets of configuration changes.

(I see you mention commit in your question so presumably you already use git).
> 2 votes

---
Tags: drush, features
---


title: Are Drush and Phing redundant?

text:
# Question
Title: Are Drush and Phing redundant?
I've installed JenkinsCI on our dev server to start automating our dev build and test process. I'm using Jenkins with the Git Plugin and some Drush commands via a shell script.

When researching how to use Jenkins in my Drupal dev workflow, I came across a post about using Phing with Drush and Jenkins. So I looked at Phing and I can't see what it does that cannot be done by using Drush commands via a shell scripts.

I'm trying to decide if it makes sense for me to invest the time in learning how to use Phing. I'm looking for some clarity as to what benefit I will gain by incorporating Phing vs. Drush commands via Shell script.

So my question is for those who use Phing with Drush and Jenkins: how is it that Drush/Drush-Make and Phing differ? Why did you decide to start using Phing in your process?

Thanks

# Answer
The answer is that they are certainly not redundant.

It's true that one can accomplish the same end result using a bash script that includes drush commands (at least the building part). But, if what we are looking to do is to integrate our process into a CI framework like JenkinsCI, then using something like phing (ant or capistrano could be substituted here) is the way to go.

With phing we can break up the build process into distinct segments that can report back to Jenkins in an intelligent way.

So for example. Say that as part of my build process I use drush to enable two modules, node and shouldfail. Then the build should fail. But if all we do is tell JenkinsCI to run the following shell command, JenkinsCI will say that the build PASSED:

```
drush --quiet --yes @staging en node shouldfail

```

Clearly that's not right. However if instead we use ant or phing to define the same process, we can also add some fail logic that Jenkins understands, and therefore fail as it should. The following phing build script tries to do the same thing as the former command, but fails as we expect it to:

```
<project name="staging" default="enable modules" description="Jenkins Staging Build">

    <target name="enable modules">
      <exec  command="drush --quiet --yes @staging en node shouldfail" error='error' checkreturn="true">
      </exec>
      <loadfile  property="en.error" file="error" />
      <if>
        <contains string="${en.error}" substring="warning" />
        <then>
          <property name="en.fail" value="Could not enable all modules" />
        </then>
      </if>
      <fail if="en.fail" message="${en.fail}" />
    </target>

</project>

```

BTW ant and phing are almost identical. The advantage for PHP developers in using phing is that they can more comfortably extend phing.

As for Drupal development and drush being as good as it is, I don't see too much value in extending phing, and think that running exec tasks would suffice to create a smart build template.

Well, in order to answer my question I ended up investing the time to figure out phing. It's actually pretty intuitive and it doesn't take too long to figure out.
> 16 votes

# Answer
There is a Drush task available for Phing now:

Instead of using exec you can include Drush comands like this...

```
  <drush command="site-install" assume="yes"">
        <option name="locale">uk</option>
        <option name="site-name" value="${sitename}" />
        <param>expert</param>
  </drush>

```
> 2 votes

# Answer
Phing scripts are replacements for shell scripts, to control the execution of multiple commands and their results. Drush is a CLI interface for commands to interact with a Drupal site or related to Drupal. They complement each other.
> 2 votes

# Answer
**Your question: Does Phing and Drush overlap?**

*TLDR; version:* Sorta. But mostly no.

*The unabridged version:* Drush and phing do overlap in only a few instances. Mainly, dumping and archiving a website would be one of the larger overlaps. You could do it in phing but you would have to write a lot of tasks. You could Dump a database but drush does it so easily with one command. Phing does do that but you just have to write a command line script. Where phing shines is the ability to run phpunit tests, run external tools like a jar that compresses your css files, create and package a build of your drupal site/application, etc.

**What is phing?**

Phing is essentially the pilot that executes commands. If you're familiar with Ant, Phing is actually a close port from Ant (It's java based cousin). Phing is written in PHP.

You can use Phing to automate tasks and report results based on those tasks. Drush, on the other hand, just performs tasks. It's unable to determine evaluate the results of the output.

**Example use case for phing / drush:**

I need drush to dump the database and phing to `scp` the package from prod to testing.

Phing can store these settings in an external `build.properties` file and source them into your project. It's able to also store different settings for each environment as well. E.g. Phing can symlink the latest completed that has been dumped by drush to the right document root.

**How does all this work?**

Phing is driven by an xml. It consumes a build.xml file and takes in attributes (sometimes called targets) and executes simple commands.

**More on this:**

I highly recommend you review this slideshare by the Phing project leaders:

http://www.slideshare.net/michieltcs/building-and-deploying-php-applications-with-phing

It'll give you a high level and some concrete usage (plus code) of phing. It's not in any way related to drupal but it'll give you a better idea of how it works.
> 1 votes

---
Tags: drush, deployment
---


# Question
Title: AJAX Throbber - Keep throbber image but delete Please wait... message?
This question has been asked a few times in various forms but is there a simple way to keep the animated blue throbbing image but delete the Please wait... text?

I'm trying this in my form\_alter hook:

```
unset($form['my-model']['#ajax']['progress']['message']);
// or
$form['my-model']['#ajax']['progress']['message'] = '';

```

But this appears to remove the message AND the animated throbber! I want the throbber to remain. Is it a requirement for message to not be empty for the throbber to even render?

# Answer
> 2 votes
@Jimajamma answered the question correctly in the first comment.

```
 $form['my-model']['#ajax']['progress']['type'] = 'throbber';
 $form['my-model']['#ajax']['progress']['message'] = NULL;

```

Must explicitly be set and configured within the \['#ajax'\] form element.

---
Tags: forms, ajax
---


# Question
Title: Drupal views relationships to an indirect referenced contenttype
I want to create a view with a field which shows an indirect referenced contenttype (see Design) using Drupal 6.

I have 3 content types: Person, Organization and Workgroup.

Each person is related to only one organization by the node reference field: field\_related\_org\_unit. Multiple persons can be linked to the same organization.

Each workgroup is related to only one organisation by the node reference field: field\_supported\_org. Multiple organizations can have the same workgroup.

Now I want a view which displays the information of a certain person (firstname, lastname) and in the same view I wan to show the workgroup which he is indirect related to (sharing the same organization).

So say, Person A is related to organization XYZ. Workgroup B is related to organization XYX. I want to show the title of Workgroup in the view.

I tried several relationships in the View, but couldn't get it working. see Setup View

Is it possible to realize this kind of setup? Could someone help me out?

# Answer
> 0 votes
The node reference fields in both the person and the workgroup both point to the same organization. Set up a relationship between person and workgroup on the organization field. That should make the workgroup name available to the view.

---
Tags: views
---


title: Effective use of tokens view mode?

text:
# Question
Title: Effective use of tokens view mode?
Most probably because of the naming coincidence with the Token module, I cannot find any tutorial or reference as per how to effectively use the Tokens view mode that I can see in perhaps all entities in Drupal.

I smell this serves some particular purpose but cannot get a clue.

# Answer
> 4 votes
This allows you to change the output of field tokens without disturbing the default display of the field.

For example, you might want the Body field displayed as formatted text by default, but plain text whenever it is output as a token.

Take a look at http://drupal.org/node/1299662 for an example of how to use.

---
Tags: tokens, entities
---


# Question
Title: Using Commerce, how do I create a filterable view of "Who Bought What"?
I need to create a list of users that have made purchases on my site. I need to be able to filter this list by product and show which users bought it. It is similar to how the Who Bought What module in Ubercart does it (but now I need it for commerce). Any thoughts are appreciated.

# Answer
> 3 votes
Use Views! I guess you saw that coming, right? If you're in need of great examples, check out the default Views shipped with the Commerce Reports module.

In your case, I'd create a View using Commerce Order as the base entity. I'd filter it by order state or status so you only show completed orders. I'd then add relationships to the user table and to the line item table. Through the line item table, I'd add a relationship to referenced products. This will get you all the data you need in your query, and you can then add display fields pertaining to the user / order / line item info and filter based on the SKU / title of the product. You'll probably need some sort of aggregation to group multiple purchases of the same product by the same user.

That is by no means a complete recipe, but it's basically the only way you're going to solve this short of coding a custom interface and doing it all through EntityFieldQuery.

---
Tags: commerce
---


# Question
Title: How to access a remote site using the command line (with drush)?
I don´t know how to use drush nor the command line, so I´ve started to read some tutorials, and watch some videos. I´ve installed the drush windows installer, because I have windows.

The thing is that all examples I´ve read so far, start with localhost. What if I have my devel installation in a shared hosting or a VPS, in the cloud? How to access that?

Using my ftp program, I access it using hostname ftp.mysite.com the username and the password to that account. How may I do that with the command line?

Thanks!

# Answer
> 3 votes
If I understand correctly, you want to just use Drush on remote site. You don't need to do anything with aliases.drushrc.php for it. You need to have access to SSH on your remote server, there are many tutorials on the net how to use SSH. You need to upload Drush through SSH on server - create a folder, like "programs" (it would be nice if it would be not accessible through http) and put there drush-7.x-5.8.tar.gz . Untar it with command:

> tar -zxvf drush-7.x-5.8.tar.gz

Next: Edit your .bash\_profile file located in your home directory or create it (you can use command "nano .bash\_profile" in your home directory), and put there:

> export DRUSH\_PHP=\[absolute path to your php\]/bin/php-cli

For example: "export DRUSH\_PHP=/usr/local/php54/bin/php-cli" - you can check this path in output of your phpinfo().

Also add this line:

> PATH=~/programs/drush:${PATH}

After this if you are logged on your remote server through SSH, you can go to directory of your Drupal site and use command "drush status" to check if everything works ok. Voila - you have drush installed on your server.

# Answer
> 4 votes
1. go into your drush folder
2. Copy the file examples/example.aliases.drushrc.php to root of your drush folder and rename it to aliases.drushrc.php
3. Read the comments in that file and this slideshare
4. create your aliases for both the local site and development site (on shared or vps)
5. make sure you have a proper ssh connection setup to your remote server

# Answer
> 3 votes
To access a remote server using the command line, you usually use ssh.

For windows, you can use a tool called PuTTY - there's a tutorial here: http://support.suso.com/supki/SSH\_Tutorial\_for\_Windows

# Answer
> 1 votes
See this post for Drupal on shared hosting accounts: Installing Older Versions of Drush on Shared Hosting Accounts. Here is an excerpt about it:

> These instructions are for installing older versions of Drush that pre-date the Composer requirement. Please try to install Drush using the method in Installing Drush 6 and 7 on Shared Hosting Accounts first, unless you need an older version of Drush, or you cannot install Composer on your shared host.

---
Tags: drush
---


# Question
Title: View to display user points and the reason for the points
Using user points module, the users of my site are successfully being assigned points for any content they post or revisions they make and so on. Now when a user logs in, i want the user to be able to see his points and the reason for the points being assigned. The view output would be something like this:

* 1.Blog Pic A, Blog Title A, Blog TeaserA (and then) *Points*

2.Blog Pic B, Blog Title B, Blog TeaserB (and then) *Points*

Here then user gets points for their blog uploads. How can i create a view showing the above result. I tried but was not successful. I created a view of **user points** with Contextual filter **Userpoints Transactions: User** and fields as **Userpoints Transactions: Points (Points)** . However i am not getting any fields as content:body and so on. I understand i have to add a relationship but i am a bit confused here. I tried adding the relationship **Userpoints Transactions: Entity ID** but the i get an error: **SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'userpoints\_txn.nid' in 'on clause'**. What is this. How can i create the view for the above shown usecase. It seems a simple solution. What am i missing?

Edit: I tried different views but none are showing what i need. Would appreciate if someone can export a view, or at least, and preferable, guide me so that i also understand where i am going wrong.

# Answer
> 5 votes
I have userpoints active on one of my sites, and the display you are looking for is integrated with the module.

Look at the user account, there should be a tab (Points) (`/user/$uid/points`).

To create your own page, introduce a required relationship to the users table, then a contextual filter using that relationship on user:uid. When the configuration screen comes up, under 'When the filter is not in the URL' provide a default value \> UID from currently logged in user. This should get your view working.

**Note**: The relationship must be created first, then it is available for the contextual filter.

---

**Edit**: Step by step.

1. Add new view: (`/admin/structure/views/add`)

In the 'Add View' screen, enter view name, and choose to Show 'Userpoints Transactions' of type 'all'. I chose a Table format to show fields. The rest is adjustable later.

Click 'Continue and Edit' to go to the edit screen.
2. Add a relationship for 'Userpoints Transactions:User'. Check 'Required' and 'Apply all displays'. This will bring the users table into the view.
3. Create a contextual filter on 'users:uid' using the relationship you just created. Configure the default value provided as 'UID from logged in user', and Apply.
4. Add whatever fields you wish and format the view.

This is the export:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Users Points';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Userpoints Transactions: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'userpoints_txn';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Field: Userpoints Transactions: Description */
$handler->display->display_options['fields']['description']['id'] = 'description';
$handler->display->display_options['fields']['description']['table'] = 'userpoints_txn';
$handler->display->display_options['fields']['description']['field'] = 'description';
/* Field: Userpoints Transactions: Points */
$handler->display->display_options['fields']['points']['id'] = 'points';
$handler->display->display_options['fields']['points']['table'] = 'userpoints_txn';
$handler->display->display_options['fields']['points']['field'] = 'points';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'users-points';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';

```

---

**Second Edit**:

The descriptions shown in the screen print you showed me are not stored in the database, but are generated on the fly when the page is requested.

Here is how you complete the view.

First, install and activate the Views PHP module.

Second, go into userpoints.views.inc and change `'field' => 'nid';` on line 435 to `'base field' => 'nid';`. Then insert the following code after line 466:

```
$data['userpoints_txn']['txn_id'] = array(
      'title' => t('Transaction ID'),
      'help' => t('The transaction ID for the points allocation.'),
      'field' => array(
          'handler' => 'views_handler_field',
      ),
      'filter' => array(
          'handler' => 'views_handler_filter_string',
      ),
      'sort' => array(
          'handler' => 'views_handler_sort',
      ),
  );

```

This will make the Transaction ID accessible to views. (The necessary changes are included in a patch file linked at the end of this answer.)

Save your view in its current form to clear its temporary cache, then go to `/admin/config/development/performance` and clear your caches.

Return to your view, and add 'Userpoints Transactions:Transaction ID' as a field, and set it as excluded from the display.

Then add another field. In the 'Add Field' screen, filter on Global, and select 'Global:PHP'.

To configure the field, Create a label of your choosing, and in the Output box add the following:

```
<?php
$transaction = userpoints_transaction_load($row->txn_id);
$value = userpoints_create_description($transaction);
echo $value;
?>

```

**Note**: Do not place anything in the Value box! It is used for another purpose.

Save your view, and you are good to go.

**BTW**. The changes necessary in userpoints.views.inc are in a patch attached to the Features Request issue I opened on D.O.

---
Tags: 7, views, users, userpoints
---


# Question
Title: my D7 batch is running with every request to anywhere on my site
I'm writing a batch module and for some reason every time I load any page on my site, the batch is running. The other weird thing that may be related is that the $context\['sandbox'\] is not being preserved between iterations, so every time around it resets the progress count and starts over. I can't figure out what I'm doing wrong. This is a batch module that worked fine under D6, I made some changes based on what I thought was different in D7, but apparently i've really broken something.

here's my code for the entire module:

```
function batch_add_freetags_perm() {
  return array('batch: add editorial free tags to nodes');
}

function batch_add_freetags_menu() {
  $items['admin/content/batch_add_freetags'] = array(
  'access callback' => TRUE,
  'page callback' => 'drupal_get_form',
  'page arguments' => array('batch_add_freetags_form'),
);
return $items;
}

function batch_add_freetags_form() {
      $form = array();
      $form['import'] = array(
        '#type' => 'fieldset',
        '#title' => t('Import Free Tags'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
      );

      $form['import']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Import'),
      );
      return $form;
}

function batch_add_freetags_form_submit($form, &$form_state) {
      batch_add_freetags_start();
}

function batch_add_freetags_start() {
  $batch = array(
    'title' => t('Tagging all Nodes'),
    'operations' => array(
        array('batch_add_freetags_process', array())
    ),
    'finished' => 'batch_add_freetags_finished',
    'init_message' => t('tag processing has started.'),
    'progress_message' => t('Processed @current out of @total nodes.'),
    'error_message' => t('Batch has encountered an error.'),
  );
  batch_set($batch);
}

```

This is what seems to run every time (I only want it to run when a certain form is submitted, of course.) :

```
function batch_add_freetags_process( &$context) {
  if (empty($context['sandbox'])) {
    $context['sandbox'] = array();
    $context['results'] = array();
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;

    // get data from the old d6 database
    $query = Database::getConnection(SOURCE_DB_KEY, SOURCE_DB_KEY)
      ->select('term_node', 'tn');
    $query->fields('tn', array('nid', 'tid'));
    $query->join('term_data', 'td', 'td.tid = tn.tid');
    $query->fields('td', array('vid'));
    $query->condition('td.vid', 15);
    $result = $query->execute();

    // set the maximum number of items from the results of the db call.
    $context['sandbox']['max'] = count($result->fetchAllAssoc('nid'));

    $context['results']['updated'] = 0;
    $context['results']['failures'] = 0;
    $context['results']['processed'] = 0;
    $context['sandbox']['max'] = 20;   // this is just for testing

  }

  // For this case, we decide that we can safely process
  // N nodes at a time without a timeout.
  $limit = 5;

  // bunch of actual operations commented out just to make sure this for loop is just a test while i'm figuring this out...

  for($i = 0; $i<5; $i++) {
    // Update our progress information.
    $context['sandbox']['progress']++;
    $context['sandbox']['current_node'] = $i;
    $context['results']['processed']++;
    $context['message'] = t('Now processing tag "%name" for nid: %nid, <br/> completed tags for %current out of %max nodes', array('%name' => $term, '%nid' => $context['sandbox']['current_node'], '%current' => $context['sandbox']['progress'], '%max' => $context['sandbox']['max']));
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    // $context['finished'] = 1;   // make it stop!
  }
}

/**
 * Batch 'finished' callback
 */
function batch_add_freetags_finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = count($results) .' processed.';
    $message .= theme('item_list', $results);
  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
  }
  drupal_set_message($message);
}

```

thanks for any tips!

# Answer
Well, I figured it out. There's a new D7 hook, hook\_process(). So since my batch function was called "batch\_add\_freetags\_process", it was getting called with every page load. I changed the name of the function and now things work fine.
> 0 votes

# Answer
You need to change this function name `batch_add_freetags_process` to something else like `batch_add_freetags_batch` because hook\_process() is utilized by Drupal and used to process theme variables for theme templates hook\_process

Your code should look like the following:

```
function batch_add_freetags_start() {
  $batch = array(
    'title' => t('Tagging all Nodes'),
    'operations' => array(
        array('batch_add_freetags_batch', array())
    ),
    'finished' => 'batch_add_freetags_finished',
    'init_message' => t('tag processing has started.'),
    'progress_message' => t('Processed @current out of @total nodes.'),
    'error_message' => t('Batch has encountered an error.'),
  );
  batch_set($batch);
}

function batch_add_freetags_batch( &$context) {
  // body
}

```
> 1 votes

---
Tags: routes, batch-operations
---


# Question
Title: I get this error with my custom module, Any advice on tracking down the problem?
I get this error when i select an option form a select list.

https://i.stack.imgur.com/ACmDg.png

**Drupal Watchdog log Error Details**

PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'examplesite.field\_data\_field\_for\_date' doesn't exist: SELECT r.entity\_id AS entity\_id FROM {field\_data\_field\_for\_date} r WHERE (field\_for\_date\_target\_id = :db\_condition\_placeholder\_0) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 0 ) in stopsale\_getcurrentsale() (line 249 of /nfs/c05/h02/mnt/examplesite.com/html/sites/all/modules/custom\_apps/stopsale/stopsale.module).

https://i.stack.imgur.com/ACmDg.png

# Answer
You need to create a custom field called `for_date` which will be represented in the database as `field_data_field_for_date` or remove `field_data_field_for_date` from the SQL query.
> 1 votes

---
Tags: 7, ajax
---


# Question
Title: pass result of Rules loop to variable to use outside loop
In Drupal Commerce, i have created a rule that calculates the price by adding some fields (custom line items), and then sets a result.

Now i want to make a loop (to pass over fields of a Field Collection with unlimited fields, so for each field collection set), and then set a result.

The question is: how can i get the result available to use outside the loop? (as a Data Selector value for a normal action)

# Answer
> 0 votes
You may have success there using the "provides" key in hook\_rules\_action\_info to provide a variable.

more info: http://drupal.org/node/878972

---
Tags: commerce, rules, entities
---


title: Alternative to drupal_goto

text:
# Question
Title: Alternative to drupal_goto
Within a page callback, I need to:

1. Create a new node.
2. Retrieve the nid from that new node.
3. Create an entity reference in an already existing node (referenced in a parameter passed to my page callback) TO that newly created node.

The first thought was to use drupal\_goto. However; drupal\_goto "ends the request".

> (per http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_goto/7)

As expected, I execute the drupal\_goto('node/add/*newnode*'); The node gets created, and I'm out of the page callback...

Any suggestions would be most welcome!

# Answer
Perhaps something like this:

```
function mymodule_page_callback($parent_nid){

  global $user;
  try{
    // Create new node, assumes default LANGUAGE_NONE
    $node = new stdClass();
    $node->title = 'Title';
    $node->type = 'my_type';
    $node->language = LANGUAGE_NONE;
    $node->uid = $user->uid;
    $node->status = 1;
    node_object_prepare($node); // Sets some defaults.
    $node = node_submit($node); // Prepare node for saving
    node_save($node); // Returns $node by reference with nid

    // Set entity reference on parent node
    $parent = node_load($parent_nid);
    $parent->field_entity_reference[LANGUAGE_NONE][] = array(
      'target_id' => $node->nid
    );
    // Save parent
    node_save($parent);
    // Go to edit form for new child node
    drupal_set_message("Node created");
    drupal_goto('node/'.$node->nid.'/edit');
  }catch(Exception $e){
    watchdog_exception('my_module', $e);
    drupal_set_message("A problem occured creating the node", 'error');
    drupal_goto(); // front page
  }

}

```
> 4 votes

---
Tags: forms
---


# Question
Title: How to deal with deleted posts: Returning 410 status and preventing path re-use
For my jobs site, I want to return 410 status for those jobs which expire or are removed permanently. How can I do it so that 410 instead of 404 is returned for say job related node types( they'll be unpublished first and later deleted permanently I guess I should return 404 for unpublished then 410 when deleted)?

Secondly in case it really works out to use 410 for such pages but later new job pages may be published by Path Auto which could assign the very same url's based on title name for which 410 was returned once. I understand if a url comes back after 410 it will be permanently ignore by Google. So I guess I'd need that Path Auto always generate a non-duplicated (deleted) url. So solve this I'd need to tag an always increasing number with the url or adds jobs in url directories based on dates like xyz.com/oct/job1.... So I'd need to take care of this too if I'm able to return 410 for such page.

# Answer
Pathauto will not duplicate paths. If your Pathauto URL pattern results in the path 'oct/job1' and that path already exists, Pathauto will add an integer to the end of the alias, incrementing it for every new 'identical' path. IE, you'll end up with these paths:

```
oct/job1
oct/job1-0
oct/job1-1
oct/job1-2
oct/job1-3

```

... etc.

So what you need to do is:

1. Implement `hook_menu()` to create a custom page callback that will map to a function which will return the 410 HTTP code.
2. Create the callback function for the path you created in `hook_menu()`
3. Implement `hook_node_delete()` and look at the type of the node being deleted; if the type matches the content type you're working with, run a query to update the `url_alias` database table, changing the 'source' of the records relating to your node from the 'node/##' value to the menu callback you created in step 1. This will prevent Pathauto from deleting the aliases, and will instead map them to your function which will return the 410 HTTP code.

One thing to keep in mind is that the module in which you implement this custom functionality needs to fire before Pathauto, so you may need to alter your module's 'weight' value in the `system` database table.
> 2 votes

# Answer
i would add a special flag (boolean via FieldUI) like deleted on that content type, then in the preprocess function for that content type, make an drupal\_add\_http\_header, like `if(DELETED) { drupal_add_http_header('status', 410); exit; }`
> 0 votes

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


# Question
Title: Workbench moderation and check permissions tab
Reading through the workbench\_moderation module readme file I came across this:

For reference, these are the permission sets recommended by the "Check Permissions" tab:

```
Author:
  Node:
    access content
    view own unpublished content
    view revisions
    create [content type] content
    edit own [content type] content
  Workbench Moderation:
    view moderation messages
    use workbench_moderation my drafts tab

```

However, going to /admin/config/workbench/moderation/check-permissions on my drupal 7 instance, when I select the drupal role of editor, I don't see any of the options listed in the readme file (as above).

All I see is, Moderation task dropdown menu, and then a list of Content types (which I previously enabled in the structure section)

Why am I missing all these options in the Check permissions tab?

# Answer
You're not missing the permissions, just looking in the wrong spot. Log in as an admin user and head over to `yoursite.com/admin/people/permissions`. This is the main permissions management page which shows all permissions defined by all modules.

You'll see 'sections' of permissions defined by various modules. There will be 'Node' and 'Workbench Moderation' sections mentioned in the file you read, as well as the relevant permissions.
> 1 votes

---
Tags: workbench
---


title: Workbench module without taxonomy vocab

text:
# Question
Title: Workbench module without taxonomy vocab
Is there a way to use a workbench module for workflowing purposes without having any taxonomy vocabularies defined?

# Answer
> 1 votes
The Workbench Moderation module allows you to define workflow states for your content, and does not require Taxonomy.

# Answer
> 1 votes
Your question is too vague. Workbench is a Suite of modules: Moderation, Access, Files, Media ...

Workbench Access can work with Taxonomies or Menu hierarchies.

Currently Workbench only works with data whose base type is a `Node` it does not work with custom `Entities` you may use on your site.

---
Tags: taxonomy-terms, workbench
---


title: How to validate a custom widget?

text:
# Question
Title: How to validate a custom widget?
I have created a custom widget that I would like to add some validation to. Specifically, if the widget is marked as required, to check that it actually has a value entered. I figure this should be pretty straight forward but Googling isn't returning any results that I am looking for. Probably using the wrong search terms. If someone can provide a link on how to do this or provide some hints that would be great!

Thanks.

# Answer
> 1 votes
For a form API element, just set `$form['element']['#required'] = TRUE;`

More info: #required

> Indicates whether or not the element is required. This automatically validates for empty fields, and flags inputs as required.

For more control, consider an #element\_validate handler

Note, for a custom element using hook\_element\_info, #validate and #element\_validate callback handlers are supported there in the element definition.

# Answer
> 1 votes
If you created a custom Form API (FAPI) widget, Drupal may not know how to correctly access its data, and thus the default validation (via setting `$form['element']['#required']`) will likely not work.

What you need to do is define your own element validation callback for that specific element. This can be done by setting the `#element_validate` attribute as such:

`$form['element']['#element_validate'][] = 'my_validation_function'`;

There is an example of the actual function implementation at: http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#element\_validate

---
Tags: 7, entities
---


# Question
Title: Cleanest way to write EntityCondition on field from widget
The widget is nodehierarchy\_menu\_links - it has a structure embedded in the node like:

```
[0]
-> [module]
-> [menu_name]
...
-> [pnid]

```

It has more than one value as per the widget system. I have a partial entity query, but want to filter on \[pnid\] i.e. show me all the nodes owned by uid and belonging to a particular parent. Is there an elegant to filter on these sub-items using the basic EntityFieldQuery?

# Answer
> 0 votes
I was trying to find a way to filter on complex parts of the node - ie widget items that were attached as properties.

I didn't find a way. Resolved with just SelectQuery. I manually did the join instead of using node semantics and related node hooks. It would be nice to have findNodeByPnid... - and I can't see a way to build a condition without having to go another layer down into the node and working out how it is built.

Lots of our code has various forms of 'find where parent is' and 'show me the parent of this node' - subtly different enough to make it hard to generalise. Therefore, the code is broken up into parts.

# 1 initiate query

Always adding tag.

```
$query_key = 'associatenode_' . implode('', $node_types);
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title'))
      ->condition('n.type', $node_types, 'IN')
      ->orderBy('title', 'ASC')
      ->addTag($query_key);

```

# 2 Add join

Either calling join function directly or by tag. Further mangle query later.

```
function hottopicsresearch_query_associatenode_hot_topic_research_alter(QueryAlterableInterface $query) {

```

Calls

```
function hottopicsresearch_research_for_topic_query_join($parent_nid, QueryAlterableInterface $query) {
  // Find our menu links
  $query->leftJoin('nodehierarchy_menu_links', 'nh', 'n.nid = nh.nid');

  // Find associated menus. This is used to find the parent menus.
  $query->leftJoin('menu_links', 'menu', 'nh.mlid = menu.mlid');

  // Now find the parent menu
  $query->leftJoin('nodehierarchy_menu_links', 'nh_parent', 'menu.plid = nh_parent.mlid');

  // Grab the actual parent nodes
  $query->leftJoin('node', 'node_parent', 'nh_parent.nid = node_parent.nid');

  // Filter out anything that is not our parent
  $query->condition('nh_parent.nid', $parent_nid, '=');
}

```

---
Tags: 7, entities
---


# Question
Title: Customise Publishing Options based on Role
Is there a simple way to customise the Publishing options so that certain Roles are only able to create content but not publish it. I have tried the Workflow and Workbench modules but they are way too complicated!

# Answer
The Revisioning module automatically generates separate create, edit, and publish permissions by role for all content types for which revison control is enabled. It also integrates with the Rules module. You may find this to be a simpler approach.
> 1 votes

---
Tags: nodes
---


# Question
Title: "Save draft" form button for anonymous users
I am using the Webform module to create a form. I've only just realised that the "Save draft"button is available only for authenticated users, which is a shame! Is there an easy way of making the "Save draft" button available for anonymous users as well?

# Answer
> 2 votes
The condition is on line 1977 of webform.module.

You can remove the `&& $user != 0 condition`, but the comment above is valid. Removing the anonymous user check allows the form state to be saved in the database, with uid=0 and a valid sid.

Removing the same anonymous user check on draft form retrieval, however, does not result in the active draft being returned to the anonymous user.

This functionality would require patching the webform module to allow storage of the $form\_state in $\_SESSION, or in a client-side cookie, which could be read as part of the draft form retrieval process. It would not be difficult to do, but would be a significant change in the webform module.

If you wish to pursue this, open a feature request in the Webform issue queue on Drupal.org, and message me with the link.

---
Tags: webforms
---


# Question
Title: How do I put the copyright / name site in footer
In the four themes I tried before choosing the one I have now, the name of my website was always featured with the copyright in the footer of my webpages, but now all it says is "Copyright © 2013, ."

Is there an easy way for me to adjust the code so it does credit the site after that comma and before the period? I'm not very familiar with code so I'd be ever so grateful for an easy way. I tried searching for the copyright sign and the year in a few pages but they didn't show up so I suspect there are other ways to describe those in code, right? :)

# Answer
> 2 votes
First, make sure your site name is stil configured correctly. You can do this by going to `yoursite.com/admin/config/system/site-information`.

If the site name is there and still does not show up, then the theme you've selected is likely not working correctly. Head over to `yoursite.com/admin/appearance` and click on 'Settings' next to the theme you're using. Browse around and see whether there are any options to set the copyright message.

Failing that, modify the message directly in the template files. You will have likely installed your theme to `/sites/all/themes/theme_name` or `/sites/default/themes/theme_name`. Browse to this folder and look for a file called `page.tpl.php` (it may be in a subdirectory). This file will likely contain the copyright message which you can change right then and there. Alternatively, the copyright message maybe in the `html.tpl.php` file, which should be in the same location as `page.tpl.php`.

# Answer
> 1 votes
A simple solution which might work for you and doesn't require codework: In the admin menu, select "Structure \> Blocks", then add a new block and in the Block body type in the footer text you want, and save. Then in the main Blocks page assign your new block to the "Footer" region. Only downside to this you'll have to update the copyright date once a year :)

---
Tags: 7, nodes
---


# Question
Title: How can I watch videos of the presentations from DrupalCon Sydney for free?
I live too far away from Australia so I was unable to attend DrupalCon Sydney. Is there any way to watch the videos online? I tried looking on Blip.TV (where the videos for other DrupalCons are) but I couldn't find them.

# Answer
For whatever reason, the DrupalCon Sydney videos are on YouTube, not Blip.TV. The link includes instructions for downloading the videos from YouTube, but if you want them all, it's probably easier to use the torrent.
> 4 votes

---
Tags: files
---


# Question
Title: How can I display a "loading" icon while a slow page loads?
I have a custom module whose front-end page is slow to load due to extensive database work (no forms, just a bunch of db queries to display some long tables). I want to add the little "loading" icon (similar to the iphone) while the page is loading, to show users the page is working. I've seen it on some of the Views administration pages, but I can't seem to find the code for it. Is the display code done with jQuery or a drupal module? How do I add the code to my module/page? Thanks in advance!

# Answer
> 0 votes
The loading gif is in modules/contrib/views/images/loading.gif in d7. This is a ball. The one in d6 is views/images/status-active.gif and is the clock.

Views does this in javascript:

```
$(this).addClass('views-throbbing');

```

Therefore, add an 'onclick' event on the link click or use onsubmit if using a form. If you are using ajax you should be able to use ajaxStart() and ajaxComplete() to show the block.

# Answer
> 2 votes
There is Page Throbber module which suits your requirement.

> Page Throbber is a simple utility module which lets the site developer display a spinning "throbber" and a custom message to display when loading up pages which they know will be slow to load.

---
Tags: 7
---


# Question
Title: Undefined property: stdClass::$menu in workbench_access_node_presave()
I'm logged in as user/1 and am using a workbench module. Whenever I unpublish a published revision (using the moderate tab) I am presented with the following errors:

```
Notice: Undefined property: stdClass::$menu in workbench_access_node_presave() (line 667 of /home/mysite/public_html/sites/all/modules/workbench_access/workbench_access.module).
Notice: Undefined property: stdClass::$menu in workbench_access_node_presave() (line 668 of /home/mysite/public_html/sites/all/modules/workbench_access/workbench_access.module).
Notice: Undefined property: stdClass::$menu in workbench_access_node_presave() (line 667 of /home/mysite/public_html/sites/all/modules/workbench_access/workbench_access.module).
Notice: Undefined property: stdClass::$menu in workbench_access_node_presave() (line 668 of /home/mysite/public_html/sites/all/modules/workbench_access/workbench_access.module).

```

There is a green tick next to - The live revision of this content has been unpublished. and then there is a Warning message as well: Currently there is no published revision of this node.

How do I prevent these messages from appearing? What am I doing wrong?

# Answer
> 0 votes
You are the administrator - as the administrator it is good to be able to see errors.

However - lower the error log level in settings.conf.

```
$conf['error_level'] = '0';

```

Discussion on error logs :

> Go to Administer \> Site configuration \> Error reporting (admin/settings/error-reporting). There you have a dropdown list under 'Error reporting' with the two choices you have for the error logging, being: Write errors to the log. Write errors to the log and to the screen.

---
Tags: workbench
---


# Question
Title: node--page.tpl.php not detected in Omega subtheme
I created a `sites/all/themes/mySubtheme/templates/node--page.tpl.php` in a Omega subtheme.

I cleared all caches but it is not detected at all.

I even try with `sites/all/themes/mySubtheme/templates/node.tpl.php` to theme all nodes, just in case that I would have a typo error, but not working.

The base of my subtheme is omega:

```
base theme = 'omega'

```

I've also made sure that the tpl.php file exist in:

`sites/all/themes/omega/templates/node--page.tpl.php`

`sites/all/themes/starterkits/omega-html5/templates/node--page.tpl.php`

`sites/all/themes/starterkits/omega-xhtml/templates/node--page.tpl.php`

# Answer
> 2 votes
No node override templates will be repected unless the *original* node.tpl.php file is also in your theme folder.

Copy the standard template file to node.tpl.php in your theme, clear the caches, and you should be good to go.

# Answer
> 0 votes
Copy the entire templates folder and paste it inside your subtheme template folder.Now try to create a new node--Type.tpl.php . This should work.

---
Tags: theming
---


# Question
Title: How do I add the author's image in a view?
I want to add the player's photo shown in the user profile, in a view that shows the following data.

The view shows a list of nodes. The "Player Name" field shows the author of the node.

How can I achieve this?

# Answer
> 8 votes
You can try using a relationship in your view.

Under advanced in your view -\> Relationships -\> add and choose Content: Author. You should then have the option to add the user picture in your Fields section.

# Answer
> 0 votes
@Q10 absolutely right,

Relationships
Content: Author
(author) User: Profile

but there is another way by hooking user profile to show each and every individual fields
user-profile.tpl.php
For printing fields
Condition: if((arg(0)=='user') && is\_numeric(arg(1)))
{
render your fields
}

---
Tags: views, media, users
---


# Question
Title: Drupal 6 Feeds Module User Import & Ubercart
I've noticed that in Drupal 7 there is a way to map fields for importing users, but I don't see the same option for Drupal 6. Am I missing something? I'm trying to import users that include address fields from a CSV, but I can't see a way to map it all correctly.

I need to import addresses, phone numbers, zip codes, join dates, etc. and make sure they're mapped to the correct member/user fields in Drupal/Ubercart

# Answer
> 0 votes
After searching high and low I finally found a workable solution.

Using user\_import module in conjunction with this little custom module here I was able to import all of customer information from the old site.

It was exactly what I was wanting to do. All I had to do was match up the fields to my CSV file and I was able to get it all added in ot the appropriate uc\_addresses tables.

---
Tags: 6, users, ubercart, feeds, importing-exporting
---


title: Static variable scope in drupal

text:
# Question
Title: Static variable scope in drupal
I have a hook\_user\_load function where I am loading some extra user info into the $users array. I am having trouble storing the info in a static array and would appreciate it if someone could let me know what is wrong in the following function:

```
function mymodule_user_load ($users) {

    static $my_users = array();

    foreach ($users as $uid => $account) {
        // Only handle authenticated users.
        if ($uid > 0) {

            // Have we loaded this user before?
            if (isset($my_users[$uid])) {
                $users[$uid]->info = $my_users[$uid];
            }
            else {
                //Call another function to load user info
                $my_users[$uid] = load_user_info($uid);
                $users[$uid]->info = $my_users[$uid];
            }
        }
    }
}

```

Basically, the variable $my\_users on the first time I load the user profile page, will be an empty array and I have to call the load\_user\_info() function to fill the array with the info. If I refresh the user profile page again, this function will run a second time, and the following `if (isset($my_users[$uid]))` code should evaluate to true and so it won't have to go to the else statement and run the load\_user\_info() function again. However, it is not working. Basically, each time hook\_user\_load runs, the $my\_users variable is empty, meaning it is getting initialized each time. Isn't a static variable supposed to be only initialized once?

Would appreciate any help on this. Thanks.

# Answer
Static variables are initialised **once per page build**. As soon as you refresh the page you'll lose any vars declared in your page build, including static ones.

If you want to persist data between page loads you need to use session storage
> 2 votes

---
Tags: users
---


# Question
Title: Blur text or words in posts for anonymous users
How can selected text, emails etc be **blurred and convert into image** to completely hide it. Like what quora. com does for guest users. How can this be achieved?

# Answer
How about the Blurry module?

> **Overview**
>
> This module can make your text fields blurry.
> 0 votes

---
Tags: javascript
---


# Question
Title: Which table are field instance widget settings stored? Is it ok to update these everytime a node is saved?
I wanted to utilise the Minimum/Maximum values of Integer field instance settings. I'd like to know where these are stored in the database, and whether it's feasible to use `hook_node_save` or presave to update these min/max fields. The site will use feeds to mass import nodes, and I was wondering if it'll be ok to update these values everytime the feed import is run?

Also is there an easy way to grab these min/max values on node view?

# Answer
> 2 votes
You can use `field_info_instance()` to get the details, and `field_update_instance()` to save them:

```
$entity_type = 'node';
$field_name = 'field_name';
$bundle = 'content_type';

// Load
$info = field_info_instance($entity_type, $field_name, $bundle);

// Get
$min = $info['settings']['min'];
$max = $info['settings']['max'];

// Set
$info['settings']['min'] = 1;
$info['settings']['max'] = 10;

// Save
field_update_instance($info);

```

I can't see any problem with updating those values during a mass import, but I can't see the benefit of doing it for every single node save. It would probably be better to run it once at the beginning/end of the import process.

You can use the same code in `hook_node_view()` to retrieve the values for display on the node page if you need them.

---
Tags: 7, entities, feeds
---


# Question
Title: How to add different installation profiles in drupal 7
I have my own custom built theme. I want to add installation profile like many premium themes have. Is this is achievable by any module?

# Answer
> 1 votes
You might be looking for the Profiler Builder module:

> Profiler Builder is an extension of the Profiler installation profile simplifier. This module creates a downloadable tar package that gives you a well made installation profile and associated drush make file based on the site its installed on. This is a fast, simple way of creating a distribution with options that take into account either local host development or drupal.org packaging scripts.

---
Tags: theming, installation
---


# Question
Title: Add a js file and be sure it is executed as last js file?
I need to add a js file and make it to be executed as last js file (after all js that belong to modules)

I create a module for this. But I can't manage the order of modules execution. Don't I? ¿should I add this file in my theme or through a function instead?

# Answer
> 8 votes
Using `drupal_add_js` you can control the order of your JS files by assigning weight through `$options` array.

> **weight**: A number defining the order in which the JavaScript is added to the page relative to other JavaScript with the same 'scope', 'group', and 'every\_page' value.
>
> The exact ordering of JavaScript is as follows:
>
> 1. First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme.
> 2. Then by group.
> 3. Then by the 'every\_page' flag, with TRUE coming before FALSE.
> 4. Then by weight.
> 5. Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal\_add\_js() that happened later in the page request gets added to the page after one for which drupal\_add\_js() happened earlier in the page request.

Code example:

```
drupal_add_js($file_path, array(
  'weight' => 10000, // Something higher than the weight of existing items
  'scope' => 'footer', // Make sure the script tag is rendered in the footer of the page, not the header
  'group' => JS_THEME, // JS_THEME has the highest group weight and will be rendered last
));

```

# Answer
> 3 votes
If you want to guarantee that it is the last thing done, you really need to work outside of the Drupal behaviors. You can still *load* the file wherever you want, but you need to do something slightly different.

Drupal behaviors fire as part of a `$(document).ready()`. The only way to guarantee that your function will be last is to use a later event like `$(window).load()`, eg

```
(function ($, Drupal, undefined) {
  $(window).load(function () {
    do_something_awesome();
  });
})(jQuery, Drupal);

```

---
Tags: 7, javascript
---


# Question
Title: D6 Is it possible to set node reference field and use this value in another field on the same node/add form?
I have two node reference fields in a Content Type. Driver Manager

Each driver belongs to a certain organisational unit. Every organisational unit has a set of managers. I need the organisational unit to retrieve the right selection of managers in the node reference field Manager.

Now I need to select the driver, save the node and edit the node again. Then I can select the manager from the right set of managers (based on the organisational unit token I supply in the node reference field).

Is there any other way I can do this without implementing a 2-step form?

# Answer
These two modules are intended for that purpose and have D6 versions. I think Dependent Fields sounds closer to what you want, but Hierarchical Select Node Reference may work almost as well.

Dependent Fields

> The Dependent Fields module (formerly AHAH Dependent Fields) allows cck based fields to specify another field as a controller field, and react to its changes on the form using AHAH/AJAX without the form re-loading.

Hierarchical Select Node Reference

> This module allows the use of Hierarchical Select form element as a widget for CCK node reference field, both in node add/edit form and in views filter.
> 2 votes

---
Tags: 6, ajax, nodes, tokens
---


# Question
Title: JS Resize function for div containing a a slideview slideshow and set as a page background
This is for a drpal 7 install.

Is there a way to apply the same function they discuss in this thread

https://stackoverflow.com/questions/10373349/height-and-width-of-background-picture-adapt-to-each-screen-size

to a whole div instead of a single image? For example, I have a drupal 7 install. I'm using skeleton theme. I have been requested by the client to have a full screen images slider as a the background in the homepage. I have given the images a 1680px Image style and calling the block from a custom template file for the front-page with $ block = module\_invoke. That's aright but, it obviously doesn't adjust to screen res. If I give the div one of the skeleton's css classes, the whole layout gets messed up.

I'm trying to find an alternative via custom js.

Is that possible to achieve the same behaviour as in the demo in the link, for the slideview block?

Demo- http://so.devilmaycode.it/height-and-width-of-background-picture-adapt-to-each-screen-size/

If so, please indicate how to add the js to the code, where and how. Thank you!

# Answer
> 1 votes
Found two options: cycle2 for which the project is still in development stage: http://drupal.org/sandbox/BenYoung/1832338 (and did not work when following the installation guidelines, since I never got the Cycle2 option in the dropdown and needs jquery 1.7 which apparently causes a lot of trouble)

And one that is actually fully functional Flexi Slider here http://drupal.org/project/flexslider , for which I found also this great tutorial here http://coldfrontlabs.ca/blog/creating-responsive-image-slider-galleries-adaptive-images-drupal-7. Strange that they're so well hidden when adaptive design and full width sliders are so requested now...

Now it works as I wished for it to be, except for one thing I will ask a different question for.

---
Tags: javascript, theming
---


# Question
Title: Users' list view based on current logged in user taxonomy field value
I'm on drupal 7, with views 3.5.

I have added to the user profile, a taxonomy field.

I want to create a view, which will get the users which that taxonomy field has the same value with the current logged in user taxonomy field value.

Is it possible?

# Answer
Suppose your taxonomy field is labelled User Tag and has a machine name field\_user\_tag.

1. Create a view that lists users
2. Add a contextual filter for `User:
User tag (field_user_tag)`
3. Under **WHEN THE FILTER VALUE IS NOT IN THE URL** Select 'Provide a Default Value' and then Select 'PHP Code'
4. Insert the following snippet:

```
global $user;
$term= user_load($user->uid)->field_user_tag;
return $term['und'][0]['tid'];

```

The PHP code grabs the current user. In this context the current user object doesn't have any additional fields loaded. So we need the `user_load` function to get those. The we need to extract the taxonomy id from the relevant array.

This approach works, but may not be the best or most efficient.
> 1 votes

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


title: edit users of assigned domain

text:
# Question
Title: edit users of assigned domain
i need to one role like 'domainAdmin' in a domain can edit only users of the assigned domain not another domains. is this possible with domain access itself or another modules?

# Answer
A good start would be here: http://drupal.org/project/domain\_roles \- This allows you to segment roles by domain. So you could create different roles, then assign those roles to users and by way of other access modules (Content Access could be useful but I'm not certain how it handles user entities) you could then limit the users to only their domains.

FWIW, this used to be done in Drupal 6 by way of the unstable module: http://drupal.org/project/domain\_user\_edit \- Could be worth contacting the maintainer and seeing what you can do to take it over for Drupal 7 and on.
> 1 votes

---
Tags: 7, domain-access
---


# Question
Title: Share same database tables with multisite instances
What I'm trying to do is to make 2 sites one for developing and one for live using which share same instalation and database. I want to see same content like on live site when I developing theme or module when the changes ready I want to push them via git to live server. Is it possible to make something like this. example.com - live developing.example.com -developing

I also found this http://drupal.org/node/22267 but I'm not sure how to setup :)

cheers

# Answer
I understand your intention, but no. This is not the usual approach and has the potential to bring you all sorts of pains later on the line.

Once a project is deployed, you really need 2 databases. Say your live application needs a new feature, you would want to update your "dev" site with live server's data. So ...

1. You pull data from live server. Hint: drush sql-sync makes it as simple as `drush sql-sync @live @dev`.
2. You develop the feature ...
3. Push the code to production ... `drush rsync @dev @live` or whatever you use. (Git is also great for this btw)
4. Now we have to update the db changes and this is where it gets funky. If you have added or altered tables and data you cannot just sync the db because you will overwrite whatever data your users have posted since you pulled. The common way to handle this is having update hooks to insert the changes in your db. Following this approach, the update hook was deployed in step #3. All that is left to do is ..
5. Run live.com/update.php. This will trigger your update hooks and insert changes to db.

A few things to keep in mind that make this procedure dead easy:

Drush in conjunction with drush aliases and multiple settings.php for each environnment will make transferring code and data back and forth a breeze.

Happy coding, cheers
> 5 votes

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


# Question
Title: Setting field values on a per-import basis when using Feeds
A student newspaper I work with is needing some way of importing XML files from InDesign. I'm thinking Feeds/Feeds XPath Parser is the best route for this.

However, one problem with this is that each week the Production Editor will need to import 4-8 XML files, one for each section. "Section" is a taxonomy field in the Drupal "Article" content type, and it's listed nowhere in the XML files they output.

To this end, **is there any way to manually set the values of certain fields when importing, on a per-import basis?**

I'm thinking this would look like a text box that shows up in Feeds UI when uploading the XML file. Feeds Tamper seems like an idea, but it looks like it's more designed to set default values, and less set specific values on a per-import basis.

Any thoughts?

# Answer
> 0 votes
Seems I didn't really need to do anything really differently.

Feeds XPath Parser gives you fields to change XPaths while importing. If you use the syntax:

`string('News')`

...in place of an XPath, it will assign the value ('News', in this case) as the output (Which works fine for taxonomy terms).

# Answer
> 1 votes
There's also hook\_feeds\_after\_parse() which lets you modify what's being saved to to your targets. Something like this should work:

```
function my_module_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {

  if($result->title == 'title-of-feed-importer') {
    foreach($result->items as $item_key => &$item) {
      if ($item_key == "name-of-the-field") {
        $item = 'Value to set';
      }
    }
  }

}

```

---
Tags: importing-exporting, feeds
---


# Question
Title: Conceptual question about taxonomy structure
Imagine i want a directory of different organisations in different locations. Let's say i have

* hospitals
* retirement homes
* yogashops
* health-insurance agencies
* (...)

in

* Boston
* Detroit
* Denver

I would create an overview listing of the cities to link them to the organistaions-categories of each city. These would be links to a view of all organisations of the chosen type in the chosen city.

What i already have is a vocabulary "organisations" and a vocabulary "cities". I have created a view with a contextual filter "organisations" which lists all items of an organisation-term:

organisations/yogashops

But how can i prepend the selection of a specific city?

Do i have to create a vocabulary of organisations for every city? Even if they are the same?

How can i reuse my "organisations"-vocabulary?

EDIT: Would it be an alternative to create a node for each city and then use them as entity reference for the categories?

# Answer
If I understand the question correctly you want to prepend the city name as an argument on the view, so you would have:

> organisations/denver/yogashops

well you could equally have the city appended:

> organisations/yogashops/denver

The question has no mention of Views, but I would recommend that you create a view with the contextual filters of organisation and city:

I recently set up something similar for global dealerships /find-a-dealer/europe/fr
> 5 votes

# Answer
can't you just add a second contextual filter to your view, for cities, and use the thrid url parameter as input ?
> 0 votes

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