# Question
Title: Create two views this the same url and different permissions
I would like to build a set of views, all of which use the same url. I also want to set up role based permissions for each one so each users get routed to a different view when they visit the url (the url which all the views share.) Is it possible to build this view system?

My final goal is to have a single navbar link which sends normal users to a view that filters content based on the users NID. Admin users will be sent sent to a view that shows everything.

# Answer
Make the views as blocks and configure each one to display according to the permissions you're interested in, then place all blocks on a single page and link to it. The system will try to load all blocks, but will not show the ones the user doesn't have access to.

One caveat is a privileged user (such as admin) seeing their AND "lower permission" views, but that can be worked around, too.
> 1 votes

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


title: Theme Settings value dissapears

text:
# Question
Title: Theme Settings value dissapears
I am trying to create functionality where administrator can upload header image whenever he wants.

I' using `hook_form_system_theme_settings_alter` in theme-settings.php and altering form like this:

```
 $form['theme_settings']['background_file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Background'),
        '#required' => TRUE,
        '#upload_location' => file_default_scheme() . '://public/backgrounds/',
        '#default_value' => theme_get_setting('background_file'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
    );

```

in `template.php` using hook\_preprocess\_page and doing this in it:

```
$fid = theme_get_setting('background_file');
$loaded = file_load($fid);
$variables['background_url'] = file_create_url($loaded->uri);

```

and trying to reach `$variables['background_url']` from tpl.php file.

When I upload image everything works great, header image is set properly and code has no problem but after a while, I don't really know what happens, for example after 1 day file\_load returns `FALSE`, I just reupload image and everything works fine again.

`theme_get_setting('background_file');` always returns file id without problems.

I am missing something? I can't find source of problem.

Thanks.

# Answer
> 1 votes
I think it's because there is a problem in your template.php. Indeed drupal should save your file only temporarly. You have to save your file permenantly with this code

```
$file = file_load($form_state['values']['background_file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

```

---
Tags: forms
---


# Question
Title: How to add behavior-based onclick to ajax-enabled Form API button?
I have a form with a button:

```
$form['categories_update'] = array(
  '#type' => 'button',
  '#value' => t('Load category-related properties'),
  '#ajax' => array(
    'callback' => '_mymodule_categories_callback',
    'wrapper' => 'categories_properties',
    'method' => 'replace',
    'effect' => 'fade',
    'prevent' => 'submit',
  ),
  '#limit_validation_errors' => array(),
);

```

Now, in Behavior I'm using:

```
(function($) {
  var initialised = false;

  Drupal.behaviors.mymoduleTag = {
    attach: function (context, settings) {

      // Unrelated code

      $('#edit-categories-update', context).on('click', function(){
        console.log('Load category-related prperties clicked');
      });
    }
  };
})(jQuery);

```

And it simply fails to work - no errors in console, but no code executed either.

It works all right when I comment out `'#ajax'` part of a button's definition. Is there a way to have both behavior JS and Form API Ajax working for one button?

I'm using jQuery update module in it's dev version, and I have it set to jQuery 1.8. The button is not inside the wrapper, so it's ID is not affected by AJAX call (verified in browser).

# Answer
> 0 votes
I've done this by creating a function in the js file and then calling the function using the Drupal ajax\_command\_invoke() function.

For example, in the js put this:

```
$.fn.yourmodule_somename = function() {
  console.log('Load category-related prperties clicked');
}

```

And then in the AJAX callback, put this to call that function:

```
$commands[] = ajax_command_invoke(NULL, 'yourmodule_somename');

```

# Answer
> 1 votes
Form API `#ajax` effectively disables behaviors on elements. I can't see this documented, but that's how it works, consistently. So the solution was to change the line:

```
$('#edit-categories-update', context).on('click', function(){

```

and make it

```
$('#edit-categories-update').ajaxSuccess(function() {

```

That way code was not executed on click, but after processing of AJAX triggered by the button succeeded. It's not useful if you want to perform JavaScript *before* AJAX call, but if you need it to happen *after*, or if you *don't care*, it is a sufficient solution. If you need things to happen before AJAX call, use this instead:

```
$('#edit-categories-update').ajaxStart(function() {

```

---
Tags: forms, ajax, javascript
---


# Question
Title: How to add a pane (view content pane) to an existing panel page via a Feature module or programmatically?
I have feature module A that provides content type X and a panel variant for content type X.

I have another feature module B that provides content type Y and a view content pane of three latest items of type Y.

**From feature module B, how can I add a panel pane of the view content pane Y to the panel variant for type X in Feature A?**

Is this possible?

Let me know if that's too abstract or ambiguous, and I'll clarify.

# Answer
> 1 votes
This looks like the start of what can lead into you what I call "Features Hell". :)

It's possible to make features more maintainable and minimize conflicts if you organize them by small groups or single feature components. Here's what I mean:

* You have content types X and Y
* You have, I assume, panelizers for content type X and Y
* You have views with content pane displays that you want to add to a panelizer

This can be done by divided up your features into four different modules.

**foobar\_field\_bases**: contains the fields from content type X and Y under the "Field Bases" component. This stores the global settings of the fields.

**foobar\_content\_types**: contains content types X and Y from the features Content Types component, and the content type fields under the Field Instances component.

**foobar\_views**: contains all your views

**foobar\_panels**: contains all panel-related components such as panel layouts, panel renderers, panelizers, page managers.

It may seem like that's harder to maintain because you have more modules now, but consider your issue. You want to update the panelizer content with a view content pane. All you do is make sure the view is in foobar\_views. If not, recreate foobar\_views with your new view. If it is, update the foobar\_views feature so it contains the new display in the feature module. Then do a feature update on foobar\_panels.

---
Tags: 7, panels, features
---


# Question
Title: Reorganize Language Switcher based on Country/Region
I'm working on a site with 34+ languages and will likely be expanding to more. With this many countries, a simple drop-down list can be difficult for usability. I would like to customize the language switcher so that I can categorize a language by region and country. I have seen this before, have created similar on other non-Drupal sites, but haven't seen anything like it for Drupal.

Example:

* Europe
    + Germany
        - DE
    + Switzerland
        - DE
        - FR

etc.

I'm looking for either a module, or a head start on what I might do short of writing some custom PHP for the project.

# Answer
> 0 votes
You can take a clue from below modules..

> Hierarchical Select module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

> Language Switcher Dropdown is a very simple module that exposes a new block, similar to the default Language Switcher block provided by Locale module. The new block allows site visitors to switch languages using a drop-down select list instead of using hyperlinks.

* You need to build a custom module which displays region \> countries using hierarchical select module
* On Form Submit you need to do below actions which lang drop down does to redirect.

Please find submit handler code below from lang dropdown module..

```
function lang_dropdown_form_submit($form, &$form_state) {

  $language_code = check_plain($form_state['values']['lang_dropdown_select']);
  $type = $form_state['values']['lang_dropdown_type'];
  $tohome = $form_state['values']['lang_dropdown_tohome'];

  $language_codes = locale_language_list('language');
  if (!in_array($language_code, $language_codes)) return;

  $types = language_types_configurable(FALSE);
  if (!in_array($type, $types)) $type = 'language';

  $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
  $languages = language_negotiation_get_switch_links($type, $path);

  $language = $languages->links[$language_code];

  $newpath = (isset($language['href']) && $tohome == 0) ? $language['href'] : '<front>';

  if (!isset($language['query'])) {
    $language['query'] = drupal_get_query_parameters();
  }

  $form_state['redirect'] = array($newpath, $language);

}

```

---
Tags: i18n-l10n
---


# Question
Title: Easy date selector for Views Exposed Date Filter
I'm looking for a solution to put "Easy date selector" on the Views Date Exposed Filter, something like a drop-down or links with predefined date range:

* Posts for today
* Posts for yesterday
* Posts for last week
* Posts for last month
* Custom range

any ideas?

# Answer
A filters set as "Grouped filters" (as opposed to "Single filter", under "Filter type to expose"), lets you provide a predefined list of options.

With Grouped filters, you can setup your fixed list with date filters that are "offset from the current time". For example:

I'm not sure how you'd accomplish the Custom Range. Perhaps something like the Select (or other) module, or a second filter date filter?
> 1 votes

---
Tags: views, datetime
---


# Question
Title: How to find the name of changed file in Forms API
I've a file field attached to a node form. I want to know in the submit handler if the file has been replaced then I'll take some action.

For example I delete the previously uploaded file : abc.txt and then upload a new one "newdoc.txt" in place of it and "Submit".

I don't want to load the node and read it's contents or use hook\_presave and read the value using $node-\>original.

# Answer
I have just verified it... Form submit handler does store old values and new values..

In $form you see old fid in #node property , In $form\_state\['values'\] you see new fid that was uploaded...

By comparing above two in your submit handler you can take action..

```
function my_custom_submit_file_alter_detector($form, &$form_state) {
  dpm($form);
  dpm($form_state);
}

```
> 1 votes

---
Tags: 7, forms
---


title: Multiple dependent select

text:
# Question
Title: Multiple dependent select
I have installed Simple hierarchical select module ,and added category field in one content type and also gave multiple hierarchical taxonomy.

but this module is not responding properly when i click on add content and trying to select items from taxonomy than i am only able to see and select sub term of the first term.

please suggest something.

Thanks

# Answer
Instead use Hierarchical Select module, like anil mentioned report a bug for SHS module.

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: know if the last cron run automatically or manually?
Is there a way to know if the last cron run automatically or manually from the form "run cron" button?

# Answer
I'm not sure why you really want to check this. However, I can think of a few methods:

1. Alter the `admin/reports/status/run-cron` menu router item, and add some flagging to mechanism to detect the call. If the user runs cron through this page, that's definitely a manual "Run Cron" call. Implement `hook_menu_alter`, and change `page callback` (probably file and file\_path aswell) to your own function. In this function, add some flagging mechanism, and run previous `page callback`. It's unlikely that another module will need overwrite the `page callback` so you are almost safe. A little performance hit during menu rebuilds.
2. Add your own cron handler, and check `$_GET['q']`, or better, `$_SERVER['PHP_SELF']`. For `$_SERVER['PHP_SELF']`, if it's `index.php`, that's a manual run. Otherwise it will be `cron.php`, which is likely an automatic call. However one could click the URL containing the token, which is not actually an automatic. I think this is the best method since it does not need to assume other modules does not need to override `page callback`. A little Performance hit in each cron run.
3. Hack the `cron.php` (better yet, copy it to a new file). For example, copy cron.php file to `scron.php`, and make your crontab request that file instead of the the regular cron.php with token. You can then edit the scron.php file, and right after the bootstrapping, add a custom code to flag the cron that the file is about to execute is an automated one. Requires some custom effort that you can't do with a regular hook\_install implementation. Performance wise, this will work almost same since there are no any hooks involved.
> 2 votes

# Answer
I think that if you have dblog enabled, you should be able to check the referrer in the log where it says *"Cron run completed."*.
> 1 votes

---
Tags: cron
---


# Question
Title: Is there a submit handler for custom fields?
I built a custom field, and now I'm adding an image upload to that custom field. The type is managed\_file. When the user saves the content, where can I handle the file after submit?

# Answer
You can use hook\_field\_update in your module where you define your field..

> Define custom update behavior for this module's field data.
>
> This hook is invoked from field\_attach\_update() on the module that defines a field, during the process of updating an entity object (node, taxonomy term, etc.). It is invoked just before the data for this field on the particular entity object is updated into field storage. Only field modules that are storing or tracking information outside the standard field storage mechanism need to implement this hook.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to create an average out of 3 Fivestar Fields?
I want to create a Fivestar-Field which shows the average of 3 other ones.

Something like:

(Field A + Field B + Field C):3 = Field D

A,B and C are Fivestar-Fields which rate something and Field D is the average value out of the three.

I want the average to be showed via the star-widget of fivestar.

Is there a way to do that?

(I use Drupal 7)

# Answer
Yes, You can able to do that using hook\_node\_presave

You can read three field values rating using $node and set using below command

```
$node->field_name_of_your_fourth_field[$node->language][0]['rating'] = $average_value;

```
> 0 votes

---
Tags: rating
---


title: Content type aware in sidebar template

text:
# Question
Title: Content type aware in sidebar template
I've added some image and link content to region-sidebar.tpl.php before it executes the print $content. All good, except now the client wants the images and links specific to content type. (I can't do it all in CSS, otherwise i'd go that route).

How can I test for content type in region-sidebar.tpl.php or have a variable that is set. The region-sidebar.tpl.php doesn't see a variable defined in preprocess\_node.

In region-sidebar.tpl.php I need something like:

```
<?php if ($content):
  if ($mycontent_type == "foo") {
       ?> < add some html stuff here> <?php
  }
  print $content; ?>

```

# Answer
You can get the current node like this:

```
if ($node = menu_get_object()) {
  if ($node->type == 'foo') {
    ...
  }

```

But don't put that logic directly in a template file - move it out to a preprocess function instead.
> 0 votes

---
Tags: theming
---


title: How to set up Views PHP filter?

text:
# Question
Title: How to set up Views PHP filter?
I'm trying to use Views PHP filter feature to remove rows which don't contain some data (I can't just use "Hide if empty" feature, because the module returns a string even if there is no real value.

I'm using this string for a filter, however, if doesn't work - instead of filtering, view returns all values.

```
return isset($data->_field_data['nid']['entity']->field_poloha_obce_pol[und][0][geometry]);

```

I tried to inspire myself from some of the similar issues here, but it seems to me, that everything should be correct.

I also tested this exact code as PHP field and it returns expected value.

# Answer
> 1 votes
Try

```
 return empty($data->_field_data['nid']['entity']->field_poloha_obce_pol['und'][0]);

```

---
Tags: views
---


title: multidimensional tableselect

text:
# Question
Title: multidimensional tableselect
Is it possible to create a multidimensional tableselect (table with checkboxes)? Why? I would like to show a tableselect of all menu links to delete one or more but a nested tableselect.

So if they want to delete a link, all child-links will be selected to. I know i can just delete all children with a query, but for the user I want to visualise which part of the tree will be deleted.

Output ex.: =\> CB = checkbox

* CB link1
    + CB link 2
    + CB link 3
        - CB link 4
    + CB link 5
* CB link 6
* CB link 7
    + CB link 8

... and so on.

# Answer
> 0 votes
If you are looking to delete children as well with parent menu items seems like Delete menu options address this issue..

Project page says

> On the 'Delete menu item' confirmation page you can choose to delete child menu items and decide if the linking nodes should be deleted as well. When the checkbox 'Delete all children of this menu.' is checked, all child menu items of the parent menu item to delete, will be deleted as well. When the checkbox 'Delete nodes of the deleted menu items (only orphaned nodes).' is checked, the nodes to which the child menu items link will be deleted too. When other menu items link to same nodes or aliases as the nodes which were set out to be deleted, those nodes will not be deleted.

---
Tags: forms
---


title: Removing Site Map Module

text:
# Question
Title: Removing Site Map Module
I'm trying to remove the Site Map module from my website, however when I disable it in the modules section the page that it generates http://mywebsite.com/sitemap remains unaffected.

My first thought was; maybe the website cache needs clearing and or cron job needs to run. After doing both of those things, nothing has changed. I'm still left with the page on my site that I no longer want.

Does anyone know how I can get rid of this? I've even tried deleting the modules folder to no avail.

The module's definitely disabled.

>

# Answer
It sounds like you might have another module also implementing that path.

To check, install the Devel module (if you haven't already), and go to /devel/php. Put in this code:

```
foreach (module_implements('menu') as $module) {
  $items = module_invoke($module, 'menu');
  if (isset($items['sitemap'])) {
    print $module;
  }
}

```

And submit the form. If another module is directly responsible for the /sitemap path (i.e. it's not a redirect or something else), its name will be printed to the screen.
> 5 votes

---
Tags: 7
---


# Question
Title: View poll *results* as anonymous user doesn't allow access
Has anyone come across this problem before? When an anonymous user tries to view the current poll results (from the current poll block) they get an ACCESS DENIED error. However, if they view the poll (not the results) they can see it just fine.

For example:

http://cypress.supportedns.com/~actionin/node/11/results (Access denied)

http://cypress.supportedns.com/~actionin/node/11/ (No problem)

In the permissions administrative page, I gave the Anonymous User access to view results, so I'm not sure what's going on. Any ideas? Thanks in advance.

# Answer
> 1 votes
Stumbled upon the same problem when I wanted to redirect some anonymous users to see only the results of a poll depending on what email address pattern they entered in a form before. So I thought sending them to `node/%nid/results` would be fine and somehow it also worked AS LONG AS for testing purpose I didn't vote before (as other anonymous user with allowed email address pattern). Then the IP got stored somehow and when accessing the poll node you automatically get the results view presented WHILE AT THE SAME TIME the `node/%nid/results` URL gets unavailable.

# Answer
> 0 votes
I'm not sure what this issue is, but I was able to GET AROUND IT by changing the code in the poll.module file, specifically in the poll\_block\_latest\_poll\_view function. I just removed the '/results' string from the URL.

# Answer
> -1 votes
I dont know the problem but when I check this url I get the results

so you can use hook menu alter to change permission

---
Tags: 7, polls
---


title: attach image to poll choice

text:
# Question
Title: attach image to poll choice
I have a polls module that comes with drupal 7 enabled, But I need to attach an image filed to a choice, so when users add a choice to pull they get to add an image to it not to the node itself. is there a way to add this image?

# Answer
I just got Advanced Poll with the sandbox module Advanced Poll Field Image to do the trick!
> 1 votes

# Answer
We solved this task by adding a field collection to the poll content type and then mapping the field collection items to the answer options via `hook_form_after_build()`.

So when you create a poll and add three answers you then have to add three images in the field collection in the same order as the answers were added.

By that field collection approach you can also add a text field and other additional content to the poll. Maybe the frontend mapping also works via `poll-vote.tpl.php` and by grabbing the node id from the URL and then loading the node and the field collection items within.

Tried Advanced Poll as well but it seems kind of buggy and outdated.
> 1 votes

---
Tags: 7, media, polls
---


title: Line break in Page / Node Titles

text:
# Question
Title: Line break in Page / Node Titles
Is there some way we can use `<br>` or javascript line breaks in Node, Page and/or Block Title fields?

# Answer
> 0 votes
When I need that - or something similar - I mostly type something like 'title|subtitle' right in the title field. Then right before rendering, I replace all '|' chars with breaks.

And recently, someone wanted bold & line breaks in titles, so I added a textarea with WYSIWYG and auto-filled the real title field ( that I put hidden ) with a stripped down version of what was in the textarea.

So basically, I use work-arounds. Just a thought.

To solve your problem for Blocks, you can always use the Bean module. That way, you can make different 'types' of Blocks, all fieldable. And then implement the method I used with the WYSIWYG.

# Answer
> 1 votes
I have found there is good reason why Drupal restricts html in titles. If you need a subtitle, it is best to create an additional field in the content type, then position it using the Display Suite module.

# Answer
> -3 votes
Try css, change title width for pages you want to have breaks.

---
Tags: theming
---


# Question
Title: Remove default installation profiles with drupal core
Is there a way to remove the core installation profiles that come with drupal without the need of hacking core? i.e. is there a hook that can run to alter this list?

The reason why this is required is that we are making a custom install profile for use with aegir, and do not want the default core drupal 'minimal' and 'standard' install profiles as options for the users to create new sites.

Perhaps this could be a hook in aegir?

Has anyone found an elegant solution to this?

# Answer
Build a simple module for your Aegir instance that implements `hook_form_alter()` to hide the Standard/Minimal profile options.
> 3 votes

# Answer
You need to add `exclusive = 1` line in the .info file of your profile.
> 4 votes

# Answer
This is how I did it and let me know please if there is smarter way.

1. From the core I learned that the install is using maintenance theme or 'seven' if none defined. So I created a new 'my\_install' sub-theme. Seven theme is its base theme. I replaced the logo.png with my site's logo, created template.php and added hook\_form\_alter() to it to unset the Standard and Minimum profiles:

```
function my_install_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'install_select_profile_form') {
    $form['profile']['My profile']['#attributes'] = array('checked' => 'checked');
    unset($form['profile']['Standard']);
    unset($form['profile']['Minimal']);
  }
}

```
2. Now to make install to use *my\_install* theme I changed `settings.php` and `default.settings.php` by adding to both

```
$conf['maintenance_theme'] = 'my_install';

```

that is it.
> 1 votes

---
Tags: 7, hooks, aegir, distributions
---


# Question
Title: Any imageslider for my homepage. am using drupal 5.21 on my website
Any imageslider for my homepage? am using drupal 5.21 on my website.

# Answer
> 0 votes
You can try using Jquery slideshow module which support Drupal 5.x

Project page says

> This module creates a javascript slideshow using the Cycle plugin for Jquery. The slideshow is created from multiple imagefields of a node. There are settings to change the type and speed of transitions. Settings also exist to use Imagecache presets for the images.

---
Tags: media, javascript
---


# Question
Title: Cannot access the site after changing admin password
I have drupal 7 site hosted on bluehost.

After I changed the admin password, I got an error. I then tried to access the site, and I was able to do that, but it was very slow.

Now, I can't access the site as an administrator. It becomes even more weird: If I delete all history and cookies from the server, I can access the site; I can also login as an authenticated user.

When I try to log in as administrator, I get a white page or a "500 internal server" error. (It depends on the browser; I tried Chrome, FF and IE.) After I do that, I cannot access the site even as guest or authenticated user; only when I delete all the history and cookies, I can access the site as guest or authenticated user.

How can I fix this?

This is the error log the bluehost Representative gave me:

> \[15-Apr-2014 14:48:49 Europe/Helsinki\] PHP Fatal error: Call to undefined function intel\_path\_filter\_type\_to\_arg() in /public\_html/includes/menu.inc on line 814

Is it possiable this module has something to do with the issue? https://drupal.org/project/intel

I think I disable the google analytic api module. Maybe the problem is related to one of the Drupal SEO modules?

I am really not sure, and cannot connect my site..

Yesterday the site worked great! Restoring the site to yesterdays backup did not help - this is the weirdest thing!

# Answer
> 1 votes
The problem was related to one of the two below (or both):

* The error from the intel module
* The session cache / cache

Currently the site is live and working great, but the Intel module is active currently and I don't know if to disable it or not.

The second thing we did (me and the nice guy that helped me) is to clear the cache and sessions cahce - which was problematic for me since I did not had access as admin. We used update.php after allowing every user to access it on the setting.php file (changed false to true), and clear the cache through the mysql query on the 'my php admin'.

Here are the steps:

1. enter my php admin
2. choose database
3. go to mysql tab
4. on the query: UPDATE system SET status='0' WHERE name='intel';
5. then need to flash the cache - run the query:

TRUNCATE TABLE sessions;
TRUNCATE TABLE cache;
TRUNCATE TABLE cache\_bootstrap;
TRUNCATE TABLE cache\_block;
TRUNCATE TABLE cache\_field;
TRUNCATE TABLE cache\_form;
TRUNCATE TABLE cache\_image;
TRUNCATE TABLE cache\_menu;
TRUNCATE TABLE cache\_page;
TRUNCATE TABLE cache\_path;
TRUNCATE TABLE cache\_update;
TRUNCATE TABLE cache\_views;

I will be happy to get feedback on this solution. The site is currently working - so problem solved. But, I don't know if I still can't disable the intel module and if I can change the admin password. I don't want to cause the problem again.

---
Tags: users
---


# Question
Title: is the a module similar to data_export_import that includes user roles?
I am using the Data Export Import module to migrate data from my live site to my dev site. It works fine in all cases except user roles. For some reason, many (but sometimes not all) users lose the user roles that are assigned to them. Is there a more advanced module that can handle an export-import of nodes and user (preserving node references and NIDs) which also migrates user roles?

If not, I am considering writing some rules to save and reset the roles as stated here:

Programmatically assign user role

# Answer
> 0 votes
I have never used **Data Export Import**, so I don't know whether it has special features or functions that you need for your use case.

For the use case of exporting *everything* (except file and media attachements) from my live site to my dev site, I use **Backup and Migrate**.

What it does is not in any way "advanced". It just mirrors the entire database, including content (nodes etc.), users and taxonomy terms. All references including NIDs are preserved, and user roles are also preserved.

There is nothing in your question that suggests that **Backup and Migrate** may not serve your use-case, but I may have overlooked something.

---
Tags: 7, users, importing-exporting
---


# Question
Title: How do you update a Live drupal server without overwriting the contents?
I have a site that is live and people are actively putting in content. However, I have had to make some changes in the development environment, which has taken me a couple of weeks to do. The changes required new modules to be installed and old ones to be removed, which of course changed the database contents and structure.

My question is how do I upload this site back to the live environment and update the database without overwriting the new content new users that have been added over the last two weeks?

# Answer
Thomas Zahreddin is right. But depending on what has changed ("has taken me a couple of weeks ... "), there are more things to consider.

1. Did you add/change content types. Try to export and import them. Make sure you are not losing contents.
2. Did you add/change views? You can safely export and import them.
3. Module Updates. Test them on current data. There's always a chance that user data breaks an update.
4. Module configuration changes. If it's not too much, take notes and redo them. Else try the features and strong arm modules. Another option is to figure out the exact variable names and write the values into the `settings.php`.
5. You have additional content in the dev system. Here things get really hairy. You can try the deployment module or node export. But they are no silver bullets.

If you don't have trivial case, I sugest to test your procedure beforehand. And of course take backups of files and data before you start on the live system. (Backup and Migrate comes in handy here.)
> 3 votes

# Answer
You've got to check what you want to change:

* contenttype or bundle -\> insert the new contenttype|bundle, export and import the nodes, or change the contenttype|bundle in the database for this records
* name of single fields and there occurance in contenttypes |bundles -\> e.g. with admin interface or
* values in fields -\> hardest task: you can do this via SQL in the database (probably) or with a module like migrate
> 1 votes

# Answer
I have the same procedure to handle at work when updating Drupal websites. The biggest problem is that Drupal does not really do a great job at keeping content and logics apart in its database.

The answers given by Thomas Zagreddin and BetaRide would suffice at giving you a best chance at completing the migration successfully. There is really no holy grail on this subject.

I would like to give you a development tip though which saves me a lot of trouble keeping our websites up to date: Try to keep your logics as much as possible in your code (modules / themes). Like, try to avoid creating Views as much as possible. Sometimes you will have to, but that will require another database update...

**Use Source Control Management!**

If you are able to keep everything down to the code (of course, you wont always be able to do this), you can simply use a SCM like Git, SubVersion or Mercury to update your source, and in worst case scenario revert to a previous version of your source if your update is not working out as planned.

And, of course, as addressed in the previous answers: **backup, backup, backup, backup...**
> 1 votes

# Answer
For most of the changes you can use Features Module This module can change only the changes, what have you done on the local environment .

Otherwise you can use this beautiful module Backup and Migrate Just install this module online first then take the backup of whole existing content or database, then deploy this on local. Then make change on local what you want, again take backup of your local and then deploy it on online.
> 0 votes

# Answer
I just had the same problem. To solve it I noted that the only content I had in live that was not in dev was new user details. I simply went in to the People tab of admin and copied the people details across to dev. In dev I just typed them in without any kind of automation. So the next time I upload from dev the people details will naturally be right and will not be overwritten.
> 0 votes

---
Tags: 7, database, updating, migrations
---


# Question
Title: Unique values between multiple views on same page
I have a page that has several views on it. I would like the views to show unique values.

For example, let's say I have a view that shows a few teasers for a content type. This view has four displays, each with unique filter criteria. But, the filter criteria may result in the same node being found in multiple displays:

* Display 1: nids = 1, 2, 3, 4
* Display 2: nids = 1, 3, 5, 7
* Display 3: nids = 2, 4, 6, 8
* Display 4: nids = 3, 6, 9, 12

I would like to eliminate the duplicates before the limiting occurs:

* Display 1: nids = 1, 2, 3, 4
* Display 2: nids = 5, 7, 9, 11
* Display 3: nids = 6, 8, 10, 12
* Display 4: nids = 15, 18, 21, 24

Is this possible?

# Answer
You can implement a `hook_views_query_alter()`, and manually invoke a view, and then add an additional filter with `$view->add_where()`:, eg:

```
/**
 * Implements hook_views_query_alter().
 */
function mymodule_views_query_alter(&$view, &$query) {
  if (request_path() == 'some/path' && $view->name == 'myview') {
    $nids = array();

    $view1 = views_get_view('myview');

    if ($view->current_display == 'mydisplay2') {
      $view1->preview('mydisplay1');
    }
    else if ($view->current_display == 'mydisplay3') {
      $view1->preview('mydisplay2');
    }
    else if ($view->current_display == 'mydisplay4') {
      $view1->preview('mydisplay3');
    }

    if (!empty($view1->result)) {
      foreach ($view1->result as $index => $result) {
        $nids[] = $result->nid;
      }
    }

    if (!empty($nids)) {
      $query->add_where(0, 'node.nid', $nids, 'NOT IN');
    }
  }
}

```

The order of the if/else checking should be the same as the order of the views on your page.
> 0 votes

---
Tags: views
---


title: Overwrite login page

text:
# Question
Title: Overwrite login page
I'm trying to overwrite the **FULL LOGIN PAGE**, not only the login form!

I've tried this

```
function your_themename_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'your_themename') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'your_themename_preprocess_user_login'
  ),
 );
return $items;
}

```

and this:

```
function YOURTHEME_theme() {
  return array(
    'user_login' => array(
      'template' => 'user-login',
      'variables' => array('form' => NULL), ## you may remove this line in this case
    )
  );
}
function YOURTHEME_preprocess_user_login(&$variables) {
    $variables['form'] = drupal_build_form('user_login', user_login(array(),$form_state)); ## I have to build the user login myself.
}

```

but that's only working for my login form. I have a website with all same layout pages but only the login is different. How can I disable regions and edit css from my login page?

**UPDATE**:

Now I changed the name of the template to `page--user--login.tpl` and when I put `<p>test</p>` in my the template I see `test` in my browser. But when I type nothing I see the login form but also my sidebar/footer. How can I remove them?

# Answer
> 2 votes
The normal method for creating a custom `page--user--login.tpl.php` is *not* to create an empty file, but to *copy* the `page.tpl.php` supplied with the theme you're using into the `templates/`-directory of your sub-theme, rename it `page--user--login.tpl.php`, and edit the copy.

For instance, to remove the footer, just locate the markup in your copied `page--user--login.tpl.php` that is used to template the footer, and delete it!

```
<div id="footer-wrapper"><div class="section">

  <?php if ($page['footer_firstcolumn'] || $page['footer_secondcolumn'] || $page['footer_thirdcolumn'] || $page['footer_fourthcolumn']): ?>
    <div id="footer-columns" class="clearfix">
      <?php print render($page['footer_firstcolumn']); ?>
      <?php print render($page['footer_secondcolumn']); ?>
      <?php print render($page['footer_thirdcolumn']); ?>
      <?php print render($page['footer_fourthcolumn']); ?>
    </div> <!-- /#footer-columns -->
  <?php endif; ?>

  <?php if ($page['footer']): ?>
    <div id="footer" class="clearfix">
      <?php print render($page['footer']); ?>
    </div> <!-- /#footer -->
  <?php endif; ?>

</div></div> <!-- /.section, /#footer-wrapper -->

```

The block above is an example of how this may look like (this is from a copy of *Bartik*), if you copy it from another theme, it may look different.

But to get rid of it, you pull it into your favourite text editor and delete all of it.

---
Tags: theming, users
---


# Question
Title: Add field formatter settings to all field formats
I would like to be able to modify the display of any field formatter. To to this I think the best approach is to add settings to all field display formats. Alternatively, I could create my own field formatter that applies to all field types and then show the default display formats within my own display settings.

For example say I want to have a field display settings checkbox that enables a div around the display of any field.

# Answer
> 1 votes
I've managed to work this out.

hook\_field\_formatter\_info\_alter() isn't properly implemented in Drupal 7. There is however the field\_formatter\_settings module which exposes two hooks:

* hook\_field\_formatter\_settings\_form\_alter()
* hook\_field\_formatter\_settings\_summary\_alter()

https://drupal.org/project/field\_formatter\_settings

Using the dependent modules (e.g. field\_delimiter) as examples I was able to achieve what I needed.

---
Tags: entities
---


title: Images are locked by .htaccess

text:
# Question
Title: Images are locked by .htaccess
I just uploaded a new website to a one.com hosting. From the start I had some trouble with the .htaccess file, after I was finally able to get everything to work, I ran into another problem.

None of the images appear to be loading, when I browse directly to an image, I get this message

> Internal Server Error
>
> The server encountered an internal error or misconfiguration and was unable to complete your request.
>
> Please contact the server administrator, support@one.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
>
> More information about this error may be available in the server error log.

My .htaccess file is the default one with clean urls enabled.

# Answer
An .htaccess can cause Internal Server Errors that are unrelated to PHP. Bad directives in the file (eg, syntax errors) and using restricted directives (eg, doing an Option + that has been denied by the main Apache configuration) are two likely culprits. I see the later very frequently with shared hosting.

The only way to really debug this is to find the Apache error log. This varies from system to system. On my CentOS machines, they are at

```
/var/logs/httpd/error_log

```

If this isn't your location, do a `find error_log` to track it down. You may need to be root to read this file.
> 3 votes

# Answer
Internal server error shouldn't have anything to do with .htaccess. It's the kind of error that happens when PHP (what Drupal is built on) comes across an error so bad, that it can't continue executing.

It's hard to say what's going wrong, but you should be able to see a hint in your web server's (most likely Apache) error log.
> 0 votes

# Answer
In the `.htacsess` put before `Options +FollowSymLinks` a #. It should be `#Options +FollowSymLinks`
> 0 votes

---
Tags: .htaccess
---


# Question
Title: Is there a 'text or user reference' module?
Currently, I'm planning on using a text field for full names (added fields `field_profile_full_name` and `field_profile_partner`) on user entities, so that one user can link to another. However, I might not get matching entries in autocomplete (which rules out user references). What I want is this:

1. A match to text entered in `field_profile_partner` is found in `field_profile_full_name`: return/use the text in `field_profile_full_name`.
2. A match is not found: use the text the user entered in `field_profile_partner`, without creating a new user.

I know that a 'text or node reference' module exists for Drupal 6 and 7, but I've been unable to find a module that does the same thing for user references. Does such a module exist or will I have to clone and adapt 'text or node reference'? Can I configure entityreference to give me this functionality?

**Note:** I know that I could write a custom form and autocomplete page to handle this, but the functionality needs to be on the user account/registration form. If this can be done in `hook_form_alter`, please provide it as I've had no luck getting that hook to work whenever I implement it on anything.

# Answer
The Entity reference module will relate any Drupal entities. These include:

* Nodes
* Users
* Taxonomy Terms

So should be perfect for your needs.
> 1 votes

---
Tags: 7, users, entities, forms
---


# Question
Title: 404 page not found error even though the page exists
On my Drupal 7 website, I'm getting a 404 page not found error on the front page: http://mydomain.com even though I can view the page just fine. Google Webmaster tools wouldn't validate my site; w3 website validator stops with 404 error.

I looked at my error logs in the database, and noticed that this is coming from node/1 which doesn't exist anymore. I set my home page to a different node, node/133.

This doesn't make sense to me. Either a page exists or it doesn't!

# Answer
> 1 votes
I finally resolved this after a lot of hair-pulling and gnashing of teeth by adding a URL alias from node/133 to node/1. Google Webtools now validates, and do does w3 link validator.

I discovered the solution by looking in the error logs: \- admin/reports/page-not-found

I noticed that the specific page throwing the error was node/1 . Neither google Webmaster Tools, nor the validator helped as they reported only the 404 on the main domain name.

---
Tags: path-aliases, http-request, google-search-console
---


# Question
Title: Making content and functions maintainable in the long run
I've been playing around with drupal for a couple of weeks now and one subsisting doubt remains in my mind: what is the correct, 'Drupal' way to add your custom content? For basic text and links, a WYSIWYG editor that I've downloaded seems to be only about adequate (as it is a bit sluggish).

Because I want to extend website functionalities, like user input, I've been using `.tpl.php` files to modify content on specific nodes/blocks. For example, in some arbitrary file along the lines of`mytheme/templates/page--block--5.tpl.php` there is code that prints to that page, like so

`<?php print render($page['content']); ?>
<div>
<?php my code here... ?>
</div>`

But this isn't great for the future of this project as it's essentially hard-coding. Given that I will probably one day have several people uploading content or pass it on to a different admin, what's the right way to add more advanced features for maintainability?

# Answer
In the Drupal world, this is what we refer to as Site Building. Site building is the process of using contributed modules to help you achieve something without throwing a bunch of code into a template (big no-no for the most part).

For example, you can use Views for building dynamic lists of content, Display Suite and Panels for node layouts, Webform to capture user input, Radioactivity to rank popular content, the list goes on and on. Unless you're doing something very specific, you can usually find a module that can assist you in building out features on your site.
> 0 votes

# Answer
I'm not quite sure what you mean.

Block content can be held in the DB. `.tpl.php` files are as the name suggests used for templates. E.g. block.tpl.php is the template for all blocks.

If you have 2 distinct type of template for blocks then you could certainly create a block-alternate.tpl.php but there is certainly no need to create specific templates per block.

If you want to alter user input then add fields to your custom content types, or maybe look at the Webform module.
> 0 votes

---
Tags: theming
---


title: tabs not showing

text:
# Question
Title: tabs not showing
I know this question have been answered many times but i realy do not know what i'm doing wrong. I want a config page of my module with 2 tabs in it. But it won't show a thing. here is the hook\_menu();

```
function drupangelsToolbar_menu() {
    $items = array();
    $items['admin/config/drupangelsToolbar'] = array(
        'title' => 'drupangels toolbar module settings',
        'description' => 'configuration of your drupangels toolbar',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('drupangelsToolbar_admin'),
        'access arguments' => array('administer drupangelsToolbar settings'),
        'type' => MENU_NORMAL_ITEM,
          );
    $items['admin/config/drupangelsToolbar/add'] = array(
        'title' => 'add',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'weight' => 0
         );
    $items['admin/config/drupangelsToolbar/delete'] = array(
    'title' => 'delete',
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('drupangelsToolbarTab3_admin'),
        'weight' => 2
        );
    return $items;
}

```

this is the hook\_admin()

```
function drupangelsToolbar_admin() {
    drupangelsToolbarTab1_admin();
    drupangelsToolbarTab3_admin();
}

```

in drupangelsToolbarTab1\_admin() and drupangelsToolbarTab3\_admin() I built the forms, ending with return system\_settings\_form($form);

What am I dong wrong ?? thanks in advance!

# Answer
> 0 votes
Couple of things wrong:

add needs a callback. E.g:

```
$items['admin/config/drupangelsToolbar/add'] = array(
    'title' => 'add',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 0,
    'page callback' => 'my_callback_function',
);

```

Otherwise it has no action when it is clicked.

add and delete both need either an "access callback" or "access arguments". E.g:

```
$items['admin/config/drupangelsToolbar/add'] = array(
    'title' => 'add',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 0,
    'page callback' => 'my_callback_function',
    'access callback' => TRUE,
);
$items['admin/config/drupangelsToolbar/delete'] = array(
    'title' => 'delete',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('drupangelsToolbarTab3_admin'),
    'weight' => 2,
    'access callback' => TRUE,
);

```

Without this Drupal does not know whether or not to grant access to your tab so that is why they are not appearing.

---
Tags: forms, routes
---


title: Change specific block look & feel

text:
# Question
Title: Change specific block look & feel
I have a block like this:

```
<section id="block-locale-language" class="block block-locale clearfix" data-thmr="thmr_23">
<h2 class="block-title">Languages</h2>
<ul class="language-switcher-locale-url" data-thmr="thmr_8"><li class="nl first"><a href="/nl/user/1" class="language-link" lang="nl" data-thmr="thmr_9">Nederlands</a></li>
    <li class="en active"><a href="/user/1" class="language-link active" lang="en" data-thmr="thmr_10">English</a></li>
    <li class="fr last"><a href="/fr/user/1" class="language-link" lang="fr" data-thmr="thmr_11">Français</a></li>
</ul>

```

(From the language switcher module)

But now I would like to have something like this:

```
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
  Action <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
  <li><a href="#">Action</a></li>
  <li><a href="#">Another action</a></li>
  <li><a href="#">Something else here</a></li>
  <li class="divider"></li>
  <li><a href="#">Separated link</a></li>
</ul>

```

Where do I have to change this?

# Answer
> 1 votes
Create a template file in your theme.

```
block--locale.tpl.php

```

---
Tags: blocks, theming, i18n-l10n
---


# Question
Title: Image not responsive in one content type. Can anyone help me resolve this?
I'm hoping someone might be able to help me. Yesterday, i noticed that the main image on my photo gallery content stopped behaving responsively. For example: http://thesalinepost.com/photo-gallery/saline-sweeps-tecumseh-home-opening-doubleheader Now, the same image style is working correctly on article content http://thesalinepost.com/article/saline-rowers-kick-spring-season-spring-lake-michigan And on it's working on announcement and events content.

# Answer
Because you a style rule somewhere...

```
.node-openpublish-photo-gallery .field-name-field-op-main-image {
   width: 620px;
}

```

They appear to be different content types...

node-openpublish-photo-gallery (not working)

node-openpublish-article (working)
> 0 votes

---
Tags: theming
---


# Question
Title: How to manually or programmatically delete a field?
I tried creating a field, but my server crapped out halfway with an Internal Server Error due to some spambot attack...

Now, when I try to add the field again, I am getting:

> The machine-readable name is already in use. It must be unique.

I guess some tables were populated in the db. How can I remove these easily?

# Answer
You can also use drush to run `field_delete_field()`. Just run:

```
drush eval 'field_delete_field("yourfield")'

```
> 27 votes

# Answer
Wow creating a field takes like 2 seconds ... but if it crapped out, i guess it crapped out.

Since you dont know "where" it crapped out basically you'll have to look for the tables to be sure you clean out whatever IS there ...

* `Drop` the tables `field_data_FIELD_THE_NAME_YOU_GAVE_IT` and `field_revision_FIELD_THE_NAME_YOU_GAVE_IT`.
* Also in `field_config` and `field_config_instance` look for `name` keys (and the `bundle` keys) for the field + bundles you tied the named field to. Delete those entries in those 2 tables as well.
* Clear your site cache.
> 4 votes

---
Tags: 7, entities
---


title: Create navigation through taxonomy

text:
# Question
Title: Create navigation through taxonomy
We have an taxonomy with "news" and "articles" parent terms and structure with different child terms.

What we need, is simple navigation through this taxonomy **without menus**, but with pages: so at the "Article" page are presented child terms of "Article", once an term is selected user is redirected to the page with child terms of this term **and** list of items in current term + path to this term (like Articles \> Child term 1 \> Child term 2 etc for easier navigation).

Such navigation system is typical for many CMSs, but I couldn't find nothing like this in Drupal 7.

Is there a module or guide to implement such navigation?

# Answer
> 0 votes
The only way we found to do this:

1. Use Taxonomy menu block module to create multiple blocks based on taxonomy. Not Taxonomy menu module since it doesn't allow to create multiple blocks per one vocabulary.
2. Set Pathauto to generate taxonomy pages by the template \[term:root:url:path\]/\[term:name\], where "url:path" is the alias manually entered for every parent term.
3. Override taxonomy pages with views.
4. Show Taxonomy menu blocks in main region of pages filtered by taxonomy pages url:path aliases.
5. Some CSS to place the blocks in right place.

This method is good enough, however it doesn't allow any connection between Taxonomy menu block and the content: feature we really need. For example, it's impossible to mark with bold the item in Taxonomy menu block displayed at this moment. We plan to rewrite the whole taxonomy pages template with our own php code to implement the menu and additional conditions of the currrently displayed content (may be with ajax) in future.

Thanks for no good answer.

# Answer
> 2 votes
Taxonomy menu module suits your need.

> Transforms your taxonomy vocabularies into menus with ease!

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


# Question
Title: Contextual filters with multiple taxonomy vocabularies
I have vocabulary "City":

* New York
* London

and vocabulary "Places" i.e.:

* restaurants
* cafes

The menu link is, e.g. `mysite.com/london`.

When a user click on a tag, e.g. `cafes`, I want the term city term to stay them same in the url `mysite.com/london`, but to add the places term on the end, e.g.: `mysite.com/london/cafes` in London, so that it only shows cafes. I.e. not `mysite.com/cafes`, which will show cafes anywhere in the world.

How can I do this please?

# Answer
I think you will need the following setup to work. I'd test this extensively, as it seems somewhat fragile.

a) Prefix your city taxonomy path alias pattern to something like 'cities/\[term-name\]'. You can't create a view page with a path that starts with an argument.

b) Add another view (you may want to disable the default tax term view or alter the default taxonomy term view ) with 2 contextual filters, 1) Content: Has taxonomy term ID set to provide default value (raw path using 2 component and alias) restricted to the city vocab. and 2) Content: Has taxonomy term ID set to provide default value (raw path using 2 component and alias) restricted to the places vocab.

These contextual filters will share these settings: in the validation criteria, Filter value type set to 'Term name converted to Term ID' and tick the 'Transform dashes to URL to spaces in term name filter values' checkbox.

For the second contextual filter, set 'Action to take in filter value does not validate' to "Show all", which will allow you show all results when viewing 'cities/london'.

Note, using this technique can be problematic if you anticipate any of your terms containing apostrophes, b/c the path alias for a term with an apostrophe can be name-s-something and this won't be converted to a term id.

c) Then, you'll need to alter the link generated by your existing unordered list of places view. Not sure how to go about this in the UI alone. If you share your exported view code, I'll take a look. If you can, you could create a view field template file to retrieve arg(0) and arg(1) and then use those results to generate the link in the template file.
> 2 votes

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


# Question
Title: Filter by content type and shared taxonomy terms
I want to classify my content within the following categories:

* Technology
* International Politics
* Education
* Religion
* Sports

They are shared among my content types (e.g. news, page).
I want to create listing pages filtering by category, something like "news/international-politics" (notice the clean URL).

What is the best way to achieve this?

I've kind of done it with a shared taxonomy and a view per content type with an argument, but then I can't use the taxonomy links and have to build them by hand (cleaning the taxonomy name), but it's not a very clean solution.

# Answer
> 1 votes
## To create the view

1. Create a view with appropriate fields/whatever.
2. Add the first argument *Node: Type*.
3. Add the second argument *Taxonomy: Term*.
4. For the second argument select *Transform spaces to dashes in URL*.

## To create the listing page

### Option 1

Bite the bullet and create the page in code. You just need to iterate over the content types and terms, creating the links as you go.

### Option 2

Create a normal view that lists the taxonomy terms. Use link rewriting in the view to output a link that's contains the term name and content type, and is easily identifiable. Eg. `custom_term_list/news/International Politics`. Use custom\_url\_rewrite\_outbound() to translate this to `/news/international-politics`. Gotta be careful not to slow the site down here.

### Option 3

Use a *terms as nodes* paradigm. (I think this would work.) Create a content type for which each node will refer to a term. This can be done with taxonomy\_node, nat (Node Auto Term), or even content\_taxonomy (and maybe others for all I know). Add a computed\_field that calculates the name of the term with spaces turned to dashes (or whatever). Then it would be easy to make the listing. If you want the node term to be created automatically when a term's created, then you'll need to use one of the first two modules mentioned.

Those are the only approaches I can think of to create listing pages. I think I'd just go for the first one.

# Answer
> 0 votes
I found a way to do it using distinct vocabularies per content type togheter with nat and tvi.

# Answer
> 0 votes
It took me days to work this out but the answer is in this video

Hierarchical Views Catalog using Taxonomy

https://www.youtube.com/watch?v=y1jqu8JnLbU#t=511

**In Views Use The Rewrite results Output this field as a link**

Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/\[name\]" that way your catalog names are clickable :)

---
Tags: taxonomy-terms
---


title: Logout my account on other computer

text:
# Question
Title: Logout my account on other computer
I was using a computer somewhere to login my site as admin, but forgot to logout. How can I logout my account from another computer?

# Answer
I think you can just remove the relevant entries from the sessions table:

```
db_delete('sessions')->condition('uid', $your_user_id)->execute();

```

That should log the user out everywhere.
> 7 votes

# Answer
I wrote up a small drush command to do this:

```
$ drush help session-delete
Delete user sessions from the database.
Examples:
 drush session-delete all                  Delete all sessions.
 drush session-delete 64                   Delete sessions for user id 64.
Aliases: sess-del

```

Technically, this just deletes the session and doesn't do a proper logout. Those are nearly identical, though, under most circumstances.

This patch hasn't been committed, so you would need to download drush extras and apply it, or just extract the file from the patch and add it to your local commands.
> 4 votes

---
Tags: users
---


# Question
Title: Horizontal Tabs rendered as rendering collapsible fields
Although I have set up the a Content Type's display to use Horizontal Tabs

It's rendering as collapsible fields:

Does anyone have ideas on how to correct this?

# Answer
In commons\_origins theme's template.php file, fieldset default functions are overridden("function commons\_origins\_fieldset"), pls comment or remove it to have display as tabs. Or clone this theme as custom theme in sites/all/themes folder and create as new theme by removing this function.
> 1 votes

---
Tags: 7, entities
---


title: How to use theming in other module

text:
# Question
Title: How to use theming in other module
Currently I am building a module by reusing the 'page callback' function in an other module. The data array are successfully rendered. However The presentation is poor.

I suspect that after page callback it doesn't successfully load the theme (probably css?), but I don't know how to do that.

------update------

Here is the code. I add node\_add\_page from node module to a new menu named 'node/add/add-art'. The data is rendered successfully, however the format is broken. Is it possible to not only reuse the data process function, but also reuse the theme it is using?

```
$items['node/add/add-art'] = array(
  'title' => 'Add art work',
  'parent' => 'admin/commerce/manage-products/actions',
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'page callback' => 'node_add_page',
  'access callback' => TRUE,
  'file' => 'node.pages.inc',
  'file path' => drupal_get_path('module', 'node'),
);

```

# Answer
You should use the drupal\_get\_form() to render the node form. For **art** content type.

```
$items['node/add/add-art'] = array(
  'title' => 'Add art work',
  'parent' => 'admin/commerce/manage-products/actions',
  'type' => MENU_LOCAL_TASK | MENU_NORMAL_ITEM,
  'page callback' => 'drupal_get_form',
  'page arguments' => array('art_node_form'),
  'access callback' => TRUE,
  'file' => drupal_get_path('module', 'node') . '/node.pages.inc'
);

```
> 0 votes

---
Tags: theming
---


# Question
Title: How do I set 'Locale settings' fieldset, in the user profile form, to uncollapsible?
After running a `dpm($form)` via `hook_form_FORM_ID_alter` I couldn't see the 'Local settings' in the form defintion of the user profile form. I did a search for 'locale settings' on all the code and found the value I need to alter (I think) on line 2016 of `system.module`. So I tried:

```
function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['timezone']['#collapsible'] == FALSE;
}

```

Cleared the cache. Fieldset is still collapsible?

# Answer
Found it! The point is that your hook\_form\_alter is called before system\_form\_alter, so you don't see the timezone. You need to reorder the implementation of hooks with hook\_module\_implements\_alter

Here is the full code:

```
function CUSTOM_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['CUSTOM_MODULE'];
    unset($implementations['CUSTOM_MODULE']);
    $implementations['CUSTOM_MODULE'] = $group;
  }
}

function CUSTOM_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  $form['timezone']['#collapsible'] = FALSE;
}

```

Credits to this post.
> 1 votes

# Answer
I know this doesn't precisely answer the question, but I just used this by itself in my theme's template.php with no problem:

```
function MY_THEME_form_user_profile_form_alter(&$form, &$form_state) {
  $form['timezone']['#collapsible'] = FALSE;
}

```
> 0 votes

---
Tags: users
---


# Question
Title: How do I create a page (with a url) that displays only views blocks
I have been using views to create all of my pages. I am wondering if there is a way to set up a page (with url) that is initially blank. I want to use context to place view blocks on this page based on user roles. If a context is not matched, then the url should act as though the page does not exist (would I need a rule for this?) How can I build this?

# Answer
> 1 votes
One way of solving your issue is by installing the following modules:

* Empty Page

> The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.
* Path Access

> The Path Access module gives site administrators an additional layer of access control to all pages of a Drupal site.
* Chain Menu Access API \- required by Path Access module

> Chain Menu Access API allows your module to chain its own menu access callback functions into other modules' menu router entries.

After installing all the above modules, try to implement the following steps:

* Add new empty page from `admin/structure/empty-page/add`.
* locate blocks you need to display on the created page using Context with **Path** condition and **Blocks** reaction.
* Now from Access Path settings `admin/config/people/pathaccess` specify who should access the created page and who should not per user role.

I hope this will help you.

# Answer
> 0 votes
Try using the Page manager part of the Ctools module to create pages like this, you might need to expand this further but it should give you a starting point

---
Tags: views, blocks, rules, 7
---


# Question
Title: Theme are different between different user
I grant permission of menu \['node/add'\] to a certain role of users (which was only accessible by admin previously). Turns out that, these two types of users have different views of this menu (As you can see from the following two screen shots).

How can I theme the page for these two users in the same way? Or How can I change the theme for the non admin user?

-----------update-----------

If I don't want to use admin theme, where should I add my own theme?

# Answer
1. Go to /admin/people/permissions
2. Enable the "View the administration theme" permission for the appropriate role.
3. Save the form.

Users with that role will now see the admin theme (as set at /admin/appearance) wherever applicable.
> 2 votes

# Answer
If you want to *disable* the special admin theme for the admin users, navigate to *Administration » Appearance* (path: `/admin/appearance`).

A bit down on the page, there is a box with the title "Administration theme" that let you choose the theme for the admin users. Choose "Default theme" to always use the same theme as the rest of the site. After changing this setting, click "Save configuration".
> 0 votes

---
Tags: theming
---


# Question
Title: Scrape articles from one Drupal site to other?
Let's say I have already a Drupal website that has lots of articles and etc. And now I want to build another Drupal website under different domain, and when new article is added to the old site it would be somehow automatically scraped to the new website too?

Both sites are separate and not running under same database nor single installation.

I didn't find a module yet which would do what I need. It has to scrape articles into views lists and also somehow scrape views slideshows content and should be put in sidebars also somehow via views, I didn't find a solution yet, so that's why I asked here.

# Answer
You do not need to install a module for this. This sort of thing is provided by the Drupal core. It is called an "Aggregator" and you find it as one of the core modules with the following description:

> Aggregates syndicated content (RSS, RDF, and Atom feeds).

It is not enabled by default. You need to enable it.

Here is a rundown of the UI:

* administer your list of news feeds. **Admin → Configuration → Web Services → Feed aggregator**
* add a new feed. **Admin → Configuration → Web Services → Feed aggregator → Add feed**
* add a new category. **Admin → Configuration → Web Services → Feed aggregator → Add category**
* configure global settings for the news aggregator. **Admin → Configuration → Web Services → Feed aggregator → Settings**
* control access to the aggregator module. **Admin → People → Permissions**
* set permissions to access new feeds for user roles such as anonymous users. **Admin → People → Permissions**
* view the Aggregator page. **Admin → Configuration → Web Services → Feed aggregator**
* update the feed manually. **Admin → Configuration → Web Services → Feed aggregator**

You need to set up cron to update the feed automatically.

If the site you want to use as the source for your feed is running Drupal 7, the export feed is already in place. The URL should be `http://example.com/rss.xml`.

Near the bottom of the page of any Drupal 7 (unless you've taken steps to remove it), there should be a symbool like this:

If you click on it, you should be able to inspect your outgoing feed (provided your browser knows about RSS feeds).

You can of course use this to aggregate content imported from more than one site, but it will also work fine if you just to import content from your own, old site.
> 7 votes

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


# Question
Title: Google Rich Snippets and Facebook Open Metagraph
I want to implement support for Google Rich Snippets to show author info and fivestar ratings in Google's search engine results pages. I also want to be able to support Facebook's Open Graph to have Facebook pick the correct image when a node with an image is "liked" or embedded on Facebook.

Looks like I can use Schema.org, microdata or RDFx modules. I also came across a post suggesting to just use a preprocess hook.

The schema.org module doesn't seem to support fivestar ratings. Microdata is relatively new and I'm a bit confused about the RDFX module.

Does anyone have experience with this?

# Answer
> 2 votes
In the answer above, there are modules indicated. However, in my experience, they won't work with fivestar, for they are only generic. So, what I usually do in such cases, is to:

1. Create a template for that node type, like *node--type.tpl.php*
2. Create a preprocess function in your theme's *template.php* file, implementing hook\_preprocess\_HOOK(). This will translate to an actual function name like *mytheme\_preprocess\_node(&Svariables)*.
3. In that function, use the *$variables\['node'\]* to get the data from the fivestar widget field.
4. Format and prepare that data for output, and add your custom variables to the *$variables* array.
5. Use the variables you provided in your preprocess function to insert the correct markup in your node file to correspond to the opengraph / rich snippets format.

Some notes:

1. Use devel module and *dpm()* function to dump the *$variables* in preprocess function and the data in the template file.
2. Use the google markup tool and the facebook markup tool to test your markup.
3. The logic is, prepare variables in preprocess, and put them in markup in template file. Try not to have computations (business logic) in the template file itself, use preprocess for it.

# Answer
> 0 votes
http://drupal.org/project/opengraph\_meta -\> it will take the image associated with node or you can specify a default

http://drupal.org/project/richsnippets -\>Google Rich Snippets

---
Tags: social-network, 7, rdf
---


# Question
Title: What's the purpose of the FLOOD table in my Drupal 7 database?
I want to improve the performance of my Drupal website, which is why I am trying to remove unwanted tables.

What's the purpose of the *flood* table?

# Answer
> 7 votes
It is not a good practice to remove the core tables of drupal.You can uninstall your unwanted modules .

FYI, flood table is used to control the number of events, like contacting someone. event is the name of the event (for eg. contact) hostname is the hostname of the visitor and timestamp is the timestamp of the event. By sotring these in the flood it's easy to count how many users your hostname contacted in the last hour. As all hostname based mechanisms, this is flawed as well, but binding to a session would be even more trouble -- too easy to circumvent.

Taken from this comment by chx: http://drupal.org/node/164983#comment-589458

# Answer
> 3 votes
Dont delete the Flood table. You can try to throw away gears from your car, if you are top-notch specialist, and know for sure, that your car will need no breaks (in some cases, people will have that one-time ride, hopefully no one gets hurt besides themselves).

Flood table is used to store data about bruteforce login attempts, blocking such people. So its does not contain lots of data unless someone is trying to break you. And if someone is, then you do want that table :)

On a higher level, modules use tables to write data. So, if you drop or clear a table, that will break the site in some cases, and cause it being slower in some (emptying the caches, for instance, will cause them being rebuilt).

The right way to minimize the amount of tables, is to uninstall the modules you dont need, via Drupal's uninstall interface on the modules page. From my experience, however, what can really slow Drupal, is when you have lots of content and lots and visitors, and lots of views. Otherwise, trying to break your site by deleting some service table is useless. You can as well try to make your boat lighter by throwing your life jacket overboard. Wont really lighten the boat, but will make yourself problems.

---
Tags: 7
---


# Question
Title: When using Rules, does a page refresh happen immediately if the event is set to 'Drupal is initializing'
I have several views pages set up on my site that filter the content that is shown to normal visitors. In general, these views will show users content that they have created. However, when an admin user visits one of these pages, I want them to see all of the content (created by everyone.) Currently, I have a rule set up which will redirect all admin users to a different url which has a different view (with access restricted to admin users and no filters) Functionally, this does want I want (all users click on the same menu link, but eventually reach different pages.)

I am wondering, does the rules redirect event happen before the first view is loaded? I want for the redirect to happen as soon as possible to save server resources and load time. So, If the redirect happens after the page is created, it would be better for me to change my navigation strategy.

# Answer
> 0 votes
You have not specified the exact condition you are using. If you are using 'When content is viewed by an authenticated user' condition, then yes, views are being loaded in node load hooks, and they are already there by that time. The good news is that if these are cached, it will lighten things up, and the amount of admins is always limited, so a non-issue performance-wise.

But, if you really wanted to make one view show to one user and another to another, this is what you can do:

1. Create a separate block for each view display.
2. Put these blocks on the page.
3. Apply conditions for blocks that will show them for specific roles. Advanced to admins, and usual for non-admins, or all else.

And voila - you will have a solution without redirects and overhead.

---
Tags: 7, views, rules
---


# Question
Title: Change content of $page['content'] variable
I have overwritten my login page with a file named `page--user--login.tpl.php`. Now I have this:

```
<div class="main-container container">
  <div class="row-fluid">
    <section<?php print $content_column_class; ?>>
      <a id="main-content"></a>
        <h1>Xmed.be Stocksolutions</h1>
        <p>"We help you Xchange your stock"</p>
      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>
        <ul class="action-links"><?php print render($action_links); ?></ul>
      <?php endif; ?>
      <?php print render($page['content']); ?>
      <a href="user/register">NO ACCOUNT? REGISTER</a>
      <a href="user/password">FORGOT PASSWORD?</a>
    </section>
  </div>
</div>

```

As you can see I added two links at the end (register and password). But I would like them to be inside $page\['content'\], so that they are in the section. How can I edit the $content variable, loop through it or something?

UPDATE:

Now I've added in my template.php:

```
function hook_form_user_login_alter(&$form, &$form_state, $form_id) {
    var_dump('test');
}

```

But I'm not getting test around my form (also looked in html).

I've also already tried:

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

```

But no result or something ...

# Answer
> 3 votes
You can use hook\_page\_alter to add them into the content array:

```
function YOUR_MODULE_page_alter(&$page) {

  // Check if this is the correct page.
  if(!isset($page['content']['system_main']['#form_id']) || $page['content']['system_main']['#form_id'] != 'user_login') return;

  // Add links.
  $page['content']['system_main']['register'] = array(
    '#markup' => '<p><a href="user/register">NO ACCOUNT? REGISTER</a></p>',
    '#weight' => 20
  );
  $page['content']['system_main']['password'] = array(
    '#markup' => '<p><a href="user/password">FORGOT PASSWORD?</a></p>',
    '#weight' => 21
  );

}

```

Another option here would be to use hook\_form\_alter instead. Although hook\_form\_FORM\_ID\_alter may well be the most efficient option as it will only run for this specific form removing any overhead from other pages.

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


# Question
Title: Why drupal_realpath('public://') returns an incorrect path?
I am calling `drupal_realpath('public://')` inside a module function.

Why am I getting a path like sites/all/modules/current\_module/sites/default/files from `drupal_realpath('public://')`?

# Answer
> 8 votes
`drupal_realpath()` has been deprecated and shouldn't be used; since you have a stream wrapper URI you should be able to get the correct path like this:

```
$uri = 'public://';
if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  $path = $wrapper->realpath();
}

```

Also make sure that your public path is correct in the UI (at admin/config/media/file-system)

# Answer
> 2 votes
In addition to Clive's anwser using:

```
$path = $wrapper->getExternalUrl();

```

Instead of using:

```
$path = $wrapper->realpath();

```

Worked for me, I had the same problem with the wrong path.

# Answer
> 0 votes
Drupal uses PHP's file stream and the path is configured in this location

```
admin/config/media/file-system

```

You can change it to where ever you want

---
Tags: 7, files
---


# Question
Title: Drupal7: Private/Password Protected Section in a Drupal Website
What would be the best way to do this In a Drupal7 Website:
I want to add to an already existing Public Drupal Website an 'Internal Section' that can be viewed only by Login (Password Protected). This 'private/internal' Website will have 60+ info. pages, its own menu hierarchy, and any content that relates to it will also be private (private directory for images and files) Thank you.

Boutros.

# Answer
Drupal has only a very course access control structure for *viewing* content. For the any user role, you can set permission to 'access content' (Drupal 6) or 'view published content' (Drupal 7), but that's about it.

Most inportant, out of the box, Drupal does *not* have any setting that let you set the permission "access content/view published content" for a particular content type. It is all or nothing. I.e. if you untick "access content/view published content" for the anonymous user, *no* content on your site will be available to those that are not logged in.

Assuming that you're looking for more fine-grained access control, (where only a *section* of your website is private) you need to install a *node access control* module. Many such modules exist. There is a page at the Drupal.org wiki giving an overview of node access modules. You may start by reading that and try to find a suitable module.

To make a recommendation, I'll say that the one named Content Access seems to match your requirements. It lets you control access per role and per content type. I use this module to create premium or private content for logged in users on my sites.

To use it, install and enable it. Create a new content type for the private pages - let's say you call it "Private page". Then (assuming Drupal 7) navigate to *Administration » Structure » Content types* and click "edit" for the "Private page". There is now a tab "Access control" that lets you control all types of access (Including "View") for this content type only.

As for menus, Drupal will usually manage this for you. Any menu items that leads to content that is inaccessible, will not be visible for the roles that are not allowed to see it.
> 3 votes

---
Tags: users
---


# Question
Title: Error 500 (Internal Server Error) After Clearing Cache
I truncated **cache\_block** and **cache\_bootstrap** tables in Drupal database (I don't know if its okay to truncate cache tables) and after that my site went down.

I am getting **HTTP Error 500** that says

> The website encountered an error while retrieving www.drupalwebsite.com. It may be down for maintenance or configured incorrectly.

Before truncating those tables, my site was working fine. Is there any way to get it back to working??

---

> UPDATE -

***I cleared all other cache tables too...***

***WEBSERVER LOGS -***

> \[Thu Dec 27 02:51:24 2012\] \[warn\] \[client \*IP\_Address\*\] mod\_fcgid: stderr: PHP Fatal error: Call to undefined function ctools\_include() in /var/www/vhosts/\*my\_site\_name\*/drupal/sites/all/modules/views/views.module on line 62

# Answer
Somehow your site has entered a broken state since the Views module depends on ctools but it's not enabled.

What you need to do to fix it is to:

1. Enable the ctools module in the database, by running the following SQL `UPDATE system SET status = 1 WHERE name = 'ctools';`
2. Truncate all the cache tables in your database.
3. (Might not be needed) run `$ drush rr`, requires drush and the registry rebuild extension.
4. Run `$ drush cc all` requires drush.

Going through the above list should fix your site. Messing with your sites cache table can be a bit dangerous if you don't know what you are doing since drupal caches what modules it needs to load for performance.

You can read more about and download drush and registry rebuild on drupal.org.
> 7 votes

# Answer
I found this tool extremely useful in resoling similar problems. Just on your server, wget boomshadow.net/tools-utils/fixperms.sh Then, sh ./fixperms.sh -a USER-NAME
> 0 votes

---
Tags: caching
---


title: Non blocking drupal_http_request

text:
# Question
Title: Non blocking drupal_http_request
I am trying to integrate with a third party API using REST. I want to make a few calls to the API without waiting for the result to be back (The calls are action calls ie they perform some operation in the third party software and hence I don't need to wait in Drupal).

In short I want to make a non blocking http call in php. (**similar to asynchronous call in java-script.**)

Please let me know if this is possible.

Note : I know of httprl module. But it is not of much use as I do not want to make calls in parallel. I rather want to make a non-blocking call and then carry on with my Drupal specific actions.

# Answer
No, that's not possible with `drupal_http_request()`.

You'll need to use httprl, curl\_multi, or something like that.
> 5 votes

# Answer
Yes, you can use the Queue API

e.g hook\_cron\_queue\_info

Basically add the item to a queue to be processed later via cron.

Note, just on mobile at the moment but can update with more details later.
> 3 votes

# Answer
Seems like Background Process module address this problem..

Project page clearly says

**Background process way: non-blocking/a-synchronous** (limited to 5 concurrent connections)

```
<?php
$r = array();
for ($i = 0; $i < 10; $i++) {
  $r[] = background_process_http_request('http://www.example.com/stuff/' . $i, array('postpone' => TRUE));
}
background_process_http_request_process($r, array('limit' => 5));
print_r($r);
?>

```
> 2 votes

---
Tags: 7
---


title: html mail not send

text:
# Question
Title: html mail not send
I want sent email with Html tags, I install mailsystem and htmlmail modules, according to some tutorial that I read I provide `tpl` .

anyway The main problem is when I select `HTMLMailSysytem` in `Site-wide default MailSystemInterface class` no email sending, but when I put it in `DefaultMailSystem` mail sent, I try to find out why this happened in my custom module I try

```
$result = drupal_mail('cdigitdev', 'message_key', $to, user_preferred_language($user), array('body' => $body, 'subject' => $subject, 'headers' => array('Cc' => $header_cc, 'Bcc' => $header_bcc,'Content-Type' => 'text/html; charset=UTF-8; format=flowed'), $from, TRUE));
  ym($result);

```

The result is

But I didn't receive any email !!!!

I think this is related to mail server that when I try to send html server drupal(php) tell it is sended but I did not receive any thing , is it right?

# Answer
> 1 votes
For reasons I won't get in to, you should use an SMTP module and route your emails through a real email account. Check the SMTP Authentication Support module. Details from project page:

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.

Otherwise your emails can (and will) get blocked as spam.

---
Tags: emails
---


# Question
Title: Redirect from edit page and prepopulate form
I would like to redirect user from node edit page to node add page but with prepopulated form. So all fields of the form would be pre-filled with copies of values of node edited before. Is there a way how to get these values and fill them in the form?

# Answer
Finally I did my own way. I hooked node-edit page so it redirects user to node-add page but adds id of the node into url.

for example: when nid = 3 node-edit page after submit redirects user to node/add/3

Then I check, using current\_path(), whether is there the nid after last slash in my node-add form or not. If there is no nid then user creates new node, if there is nid, user came from node-edit page and I load all node's fields by nid and prefil the form.

I was wondering if there aren't some troubles but the only problem I can think of is when I would like to use the url to do something more than just sending this nid.
> 0 votes

# Answer
You can try using Node Clone module...

Project page says

> The module provides two mechanisms to clone current content. The default pre-populates the form for adding a new node, but nothing is saved to the DB until that form is submitted. With the alternative save/edit method, a copy of the current node is saved to the DB, and then presented in the edit form. When using the save/edit mode, the admin can set whether a confirmation screen is required, and in all cases you can set whether to reset the publishing options on a per-content-type basis.
> 0 votes

# Answer
The best way i can think of is to create a custom module, **hook\_form\_alter the node-edit form** and change the #default\_value of the form fields/elements you care about.

So in the defualt\_value attribute of this you could implement a custom function that brings the data you need or hardcode the values.
> 0 votes

---
Tags: forms
---


# Question
Title: How Can I change the machine name of product type
How can I change the machine name of product type (in drupal commerce ) after it created and has several content , as example I has `tv` porduct type I want to change it to `LCDTV` , How can I change it?

# Answer
You can alter the machine name through the database to change the product type. See table `commerce_product_type` and alter the 'type' column.

Make proper adjustments in `commerce_product` for products using the old type. You could execute something like the following SQL query

```
UPDATE commerce_product SET type = REPLACE(type, "tv", "lcdtv");

```

Be sure to test this on a local or development version of the site.

UPDATE: As mentioned by Clive, you also have to update field data/revision tables.

You'd want to run `UPDATE field_table_name SET bundle = REPLACE(bundle, "tv", "lcdtv");` on any field\_data\_\* or field\_revision\_\* table that relates to your product type.
> 2 votes

---
Tags: commerce
---


title: Which hook for a warning message?

text:
# Question
Title: Which hook for a warning message?
Which Hook should I use to simply print a message if a configuration is not done yet?

The only idea i've got was hook\_node\_view, but maybe someone knows something better ?

# Answer
> 3 votes
Traditionally that's what `hook_requirements()` is for

> Check installation requirements **and do status reporting**.

Emphasis mine.

It's how modules declare that they are missing a required Javascript library, for example.

It hooks your module into the status report at /admin/reports/status.

Drupal doesn't have a mechanism for displaying messages in response to a requirement failure; so if you need to show something to the user, `hook_node_view()` makes as much sense as anything else IMO.

Actually that's not strictly true (I didn't read the docs properly)...`hook_requirements()` does already handle that in one way or another. From the docs relating to the 'runtime' phase:

> any requirement with a severity of REQUIREMENT\_ERROR severity will result in a notice on the administration configuration page.

So if your users have access to the admin config page you *can* use this hook to automatically display them a message. But if the message needs to be on a different page, you'll have to take a different route with the advice in @FreeRadical's answer.

# Answer
> 2 votes
If you want to check installation requirements and report on any failures *during installation* or any of the other phases where it is applicable, it is `hook_requirements()` \- already adequately covered by Clive.

But if you just want to print a warning message to the user/admin about some tasks (such as setting some variables), e.g.:

```
drupal_set_message(t('You've selected X and Y. These are mutually exclusive.'), 'warning');

```

... you can call this function from more or less *anywhere* inside one of the functions in your module where you do some check and want to output a warning because the check indicates that something should be done before proceeding. It doesn't have to be a hook. But obviously the function containing the call need to be executed for the message to show. However, placing it inside the same function as the function that performs the check usually takes care of that.

For instance, if the message is used to tell the admin that his choces are mutually exclusive, I have it inside settings submit handler (e.g. `MYMODULE_admin_settings_submit`). since I usually do this type of sanity checks in the submit handler.

PS: Calling `drupal_set_message()` just appends the message to an array that is shown on the next page load.

---
Tags: hooks, status-messages
---


# Question
Title: PHP code for Block visibility by Vocabulary ID
I need to show a block for terms of a certain vocabulery. Drupal.org has this snippit for Drupal 6, but I cant find anything for Drupal 7.

http://drupal.org/node/69076

Im looking at PHP in the block visibility settings as Im assuming its the best way, but id be happy with any other solution. Thanks

# Answer
> 4 votes
If you want to do this on the term pages you should be able to use this code from Drupal.org. Just replace the function call taxonomy\_get\_term with taxonomy\_term\_load.

The code is copied below:

```
 <?php
  $desired_vocab = 1; // put here the vocabulary ID you're interested in

  if ( ((arg(0) == 'taxonomy')
    && (arg(1) == 'term')
    && is_numeric(arg(2))
    && ($term = taxonomy_term_load(arg(2)))
    && ($term->vid == $desired_vocab )) ) {
      return TRUE;
  }
?>

```

# Answer
> 1 votes
It's always better to avoid placing PHP in the database. I suggest you use the module Block Visibility by Term.

---
Tags: 7, blocks
---


# Question
Title: Is there a callback for the managed_file form element, called on succesful upload?
Is there a Javascript/PHP callback for the managed\_file form element that is invoked when the file is successfully uploaded? (I mean when the "Upload" button is clicked, not when the form is submitted.)

```
$form['video'] = array(
    '#title' => t('Video'),
    '#type' => 'managed_file',
    '#default_value' => variable_get('image_example_image_fid', ''),
    '#upload_location' => 'public://temp_managed/',
);

```

I have tried:

* #file\_value\_callbacks, but this seems to be a preprocess
* #process, but it also seems to happen during the page load

# Answer
For the PHP side, use #upload\_validators as described in Form API docs. They are fired after upload, just like you want them to be. In Drupal everything that's supposed to happen between user's input and actual form save, happens in validators. Pretty weird, but that's the way it is.

For an JavaScript part, element's description says:

> The #managed\_file element is expanded into a set of FAPI elements including two '#submit' buttons one for Upload one for Remove, a '#file' element and a handful of '#hidden' and '#markup' elements to handle progress indication and displaying of already uploaded files.

Thus, while it does not have any '#ajax' property, you can try to access it's internals with your own custom code. Notably, successful file upload makes delete button visible. But internals can be refactored without notice, so be careful about that.
> 2 votes

# Answer
PHP: hook\_field\_widget\_form\_alter() is what ImageInfo Cache uses to get the file right after it has been uploaded on the PHP side. I use this to add a #process callback which then adds a callback to the #submit button. All of this to generate image styles in a background process right after the image was uploaded.

If you want a more barbaric way `file_get_contents("php://input")` & `$_POST` will give you access to everything needed. This is not advised & a bad idea. More info about the PHP wrapper.
> 1 votes

---
Tags: 7, forms, ajax, javascript
---


# Question
Title: Captcha on the user_login_form and user_pass form?
just checked on my site and it seems that certain login forms do not have captcha. specifically the form named:

1. user-login-form
2. user-pass

I put in user\_login\_form in the captcha page to make it show up, but it doesnt seem like that is working. am i grabbing the correct form id from the NAME attribute in the form tag?

# Answer
> 1 votes
You should add captcha to 1. user\_login and 2. user\_login\_block(instead of user\_login\_form)

as shown below:

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