# Question
Title: After enabling MySQL replication getting deadlocks when clearing cache
I recently setup my production MySQL server for replication. To do this I enabled `innodb_flush_log_at_trx_commit` and `sync_binlog` and set `bind-address`. A slave server on the opposite corner of the US is now happily replicating the master.

It's been fine, except that every time the cache is cleared (manually, because a module was enabled/disabled, etc) the site becomes unresponsive for about 5 minutes. It reports the following error (though, sometimes the query changes, the error is the same. This is the most common query to show this):

> PDOException: SQLSTATE\[40001\]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {semaphore} WHERE (name = :db\_condition\_placeholder\_0) AND (value = :db\_condition\_placeholder\_1) AND (expire \<= :db\_condition\_placeholder\_2) ; Array ( \[:db\_condition\_placeholder\_0\] =\> variable\_init \[:db\_condition\_placeholder\_1\] =\> 300377225537241be5ddc00.97685038 \[:db\_condition\_placeholder\_2\] =\> 1399996863.3809 ) in lock\_may\_be\_available() (line 181 of /usr/local/www/r/example.com/web/includes/lock.inc).

Clearing the cache now takes much longer. Before it would take 10 seconds at most. Now, it takes 5+ minutes. While I have run into this error occasionally elsewhere (during an hours long batch process with update.php; randomly in other places, though very rare), it's really causing problems when needing to push updates and clear the cache.

Note that the slave server is not actually serving the website at this time; it is only a backup.

```
mysql  Ver 14.14 Distrib 5.5.14, for Linux (x86_64) using readline 5.1
PHP 5.3.8 (cli) (built: Aug 31 2011 16:27:31)
Drupal 7.8

```

And the master server's my.cnf:

```
[mysqld]
datadir = /usr/local/mysql/db
socket  = /usr/local/mysql/mysql.sock
user    = mysql

old_passwords      = 1
key_buffer         = 16M
max_allowed_packet = 16M
thread_stack       = 128K
max_connections    = 1024

log_slow_queries     = 1
slow_query_log_file  = /usr/local/mysql/log/slow.log
long_query_time      = 10
ft_min_word_len      = 2
skip-external-locking

# Query cache configuration
query-cache-type  = 1
query_cache_limit = 2M
query_cache_size  = 16M
thread-cache-size = 8

# InnoDB Buffer Pool
innodb_buffer_pool_size=8G

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links                 = 0
innodb_flush_log_at_trx_commit = 1
innodb_file_per_table
default-storage-engine=InnoDB

# For replication
server-id        = 100
log_bin          = /usr/local/mysql/log/mysql-bin.log
sync_binlog      = 1
expire_logs_days = 10
max_binlog_size  = 100M
bind-address     = example

[mysqld_safe]
socket     = /usr/local/mysql/mysql.sock
log-error  = /var/log/mysqld.log
pid-file   = /var/run/mysqld/mysqld.pid

[client]
socket = /usr/local/mysql/mysql.sock

```

In my searches, I've seen some suggest enabling `inndb_locks_unsafe_for_binlog` though the name itself seems to say that it shouldn't be used along with `sync_binlog`.

# Answer
Following the guide that mikeytown2 linked to in his answer and altering the `semaphore` table with the following query fixed the deadlocks I was experiencing.

```
ALTER TABLE semaphore ENGINE = MEMORY;
ALTER TABLE semaphore DROP PRIMARY KEY;
ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE;
ALTER TABLE semaphore ADD UNIQUE name (name) USING BTREE;
ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;
ALTER TABLE semaphore DROP INDEX expire;
ALTER TABLE semaphore ADD INDEX expire (expire) USING BTREE;

```

But clearing the cache still took around 5 minutes and made the site unresponsive. Then I updated Drupal from 7.8 to 7.28 along with all our modules (most were 2+ years behind) and now clearing the cache takes around 15 to 30 seconds.
> 0 votes

# Answer
Follow this and you should be good to go: Fixes for MySQL Deadlocks in D7
> 2 votes

---
Tags: 7, caching, database
---


# Question
Title: Inserting field or field collection into body field
I've created a content type called "News" with the following fields:

* *Body*
* *Image* (using Insert module to allow user to insert picture into the body)
* *Body Sidebar* (a field collection, surrounded by a with the following fields)

*Body Sidebar* has two fields:

* *BS Title*
* *BS Text*

I want to be able to give the content creators an easy way to insert the sidebar into the body in a similar way they can with the image field. As far as I know the Insert module can't be used to do that.

**Is there any way to allow users to insert the *Body Sidebar* div into the *Body* field? If not, is there a way to do this programmatically?**

Apologies if this is elementary, I'm very new to Drupal.

# Answer
> 1 votes
You might be able to use the EVA: Entity Views Attachment module to attach the data to the node, but I'm not sure.

> "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

# Answer
> 1 votes
You can do it with Block Inject module easily, you can watch the video Demo here.

> You can create any number of regions to inject as well as select as many node types you would like these regions to be injected in. The blocks you assign to these regions will then appear in the middle of the body field of these node types if the number of paragraphs is bigger than 2.

with this module you can achieve your requirement easily by creating a view block with the required field and assign that block to the region it will render your block inside the body field.

# Answer
> 1 votes
There are already some good suggestions here. Additionally, I would like to recommend taking a look at the module field injector field formatter widget maintained by Dave Reid. It enables you, for example, to insert any view list via the views field module and can be set to where exactly the injection should happen. After the first or the second or before the last paragraph. This is the most flexible way in my opinion and enables you to even reuse this in another view showing the content with the injected view in the body again.

# Answer
> 0 votes
I recommend using views if you are not using that module already. Views gives you the ability to render content form 1 or more nodes in a block.

Add the sidebar title and sidebar summary fields to your content type, then create a block that displays these fields using views.

You should only have to create one view, which will render the information if the information is provided by your users.

You can set this view block to appear in the content section on in a sidebar by rearranging you blocks on the block settings page.

# Answer
> 0 votes
just edit the contenttypes node.tpl.php file (like node--news.tpl.php),

if you want that field in the sidebar, use views, create a views-block displaying the two fields with the actual node as contextual filter and put that block in the desired region.

---
Tags: entities, nodes
---


# Question
Title: Cache is not clearing, deleted template is still loading
I created a new node template named node--artist-page.tpl.php and it worked fine. but then, (i'm brand new at this) when saw i made some errors with it i tried deleting it but Drupal keeps loading it!

i can tell because i echoe'd out an alert saying the 'my new node tpl is running'

in addition to clearing the cache (5 or more times) I even put it in the trash but it still loads!, anyone have any experience like this? or know how to fix?

am really stuck right now.

# Answer
> 0 votes
Make sure you clear your browser cache as well as Drupals. Also it's worth checking you're making the changes in the right template files. You could do this by switching templates in \> admin \> appeRances .

I hope this helps .

# Answer
> 0 votes
that file was in the CSS folder! i knew i'd mistakenly saved one there but then immediately resaved to the template folder. then, deleted the one in the template folder and forgot about the one in the CSS folder.

when i finally removed it (from the CSS folder) then the default template did indeed load, weird

---
Tags: theming, caching
---


# Question
Title: How does Feed import get a list of the CSV fields to map to content type fields?
I am using Feed import to load a CSV file exported from an SQL database into Drupal and I am stuck at the stage where I need to map the CSV field names to the Drupal content type field names.

I think there as to be some stage in the process where in some form or dialog I can input a list of the CSV field headers and proceed to a form which enables me to match the CSV headers to the field names of the content type, but I can't find such a page in the list of pages I have to follow.

I am sure I have followed the Feed Importer creation process properly. Am I missing something, or this capability not included in the Feeds CSV importing system??

# Answer
https://www.isovera.com/blog/using-feeds-module-bulk-import-drupal-7

This is what I used...worked like a charm...you simply need to map field names from CSV file to node fields...

Alex
> 2 votes

# Answer
The checkbox setting "*has header*" or "*has no header*" is important. This tells Feed importer if the first line has to be treaded as field names. In the mapping step of the Feed import settings you tell Feed importer wich field name in the header covers which fields in the given content type. Or you choose *no header*, what means no field names are given. In this case Feed importer tries to import regarding the sorting of the fields in the csv and in your mapping (left and right). IF your CSV data are sorted the same way like the fields you have activated in the mapping settings, it will try to import the fields in order then.

But if you look for a completely automated way, where Feeds automaticly "know" which fields do you mean, I am sorry to say that, but I think this is impossible. There is always a moment in an import process, when you have to manually map or order things. Otherwise an import is impossible. But not from the limits of the module but rather from the logic of how import works.
> 1 votes

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


# Question
Title: how can I override theme_image() on a custom node template, only
Can anyone explain how to override `theme_image()` but only on a specific custom node template? (i.e. `node--artist-page.tpl.php`)

As I understand you shouldn't put things like `theme_image()` in a .tpl file, but the theme devel module it's not offering up any candidate function name overrides except `mythemename_image()`, which would apply to all images on all pages.

# Answer
> 2 votes
As I understood your problem, you need to redefine theme\_image function only for custom template. I found following link for you that can help you to resolve your problem.

How to redefine default theme\_image() function?

Another way is just override theme\_image() function that you don't want to follow:

1. Find the original theme function.
2. Copy and paste it into your template.php file.
3. Change the beginning of the function name from theme\_ to yourthemename\_.
4. Save template.php, clear the site cache, and reload!

Keep us posted with what you figure out.

---
Tags: 7, theming
---


# Question
Title: Using taxonomy filter produces duplicate content in node view
Each "info page" node on my site has a field referencing or more taxonomy terms from the 'info page' vocabulary.

I'm trying to use a node view to make it possible to find any/all content which references a particular taxonomy term. I'm getting duplicates in my node view whenever content has more than one taxonomy term and "Any" taxonomy terms are all searched. Within the returned results, nodes repeat a number of times equal to the number of terms the node references. Eg. a node with 4 different taxonomy terms shows up 4 times in my table of results after searching using the view.

The view is output as an html table and using the filter - Taxonomy:has taxonomy terms (i've selected all terms in my info page vocabulary) and exposed the filter.

The search works fine when any specific, but I get duplicates when searching "Any" terms within the vocabulary.

There are countless articles about how to solve duplication issues in views, none have worked for me so far, so I'm hoping that maybe the issue is with the way my view is setup.

Here's the export http://pastebin.com/P7EkC8KX

# Answer
> 3 votes
Under advanced, click aggregation settings then check Aggregation. Then click Query Settings and check Distinct.

# Answer
> 1 votes
Since you are displaying the output as a table, try editing the table settings so that you group by the taxonomy term. Then in your fields make sure to exclude that field from display if you don't want it duplicated. So you could have the view show:

Taxonomy term 1: -first node title referencing this term -second node title referencing this term -third node title referencing this term

Taxonomy term 2: -first node title referencing this term -second node title referencing this term -third node title referencing this term

Etc.

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


# Question
Title: Need help with Drupal javascript behaviors
I'm a bit lost with this and could do with some help from a Drupal JS veteran.

In my module I'm dynamically generating a settings form based on a CSS file, part of which provides a font select list with real-time updated preview text underneath. There can be any number of these font select lists + preview depending on the contents of the CSS file. The relevant (simplified) markup is something like:

```
<!-- First font select & preview -->
<div id="font-selector-group-1" class="font-selector-group">
  <label for="font-select-1">Font</label>
  <select id="font-select-1" class="font-select" name="font-select-1">
    <option value="arial">Arial</option>
    <option value="verdana">Verdana</option>
    <option value="helvetica">Helvetica</option>
  </select>
  <div id="font-preview-1" class="font-preview">Preview: <span class="">The quick brown fox jumped etc ...</span></div>
</div>

<!-- Second font select & preview -->
<div id="font-selector-group-2" class="font-selector-group">
  <label for="font-select-2">Font</label>
  <select id="font-select-2" class="font-select" name="font-select-2">
    <option value="arial">Arial</option>
    <option value="verdana">Verdana</option>
    <option value="helvetica">Helvetica</option>
  </select>
  <div id="font-preview-2" class="font-preview">Preview: <span class="">The quick brown fox jumped etc ...</span></div>
</div>

<!-- Et cetera ... -->

```

In addition to styling (applying the correct font to) each font option I also want to change the class of `#font-preview-x span` to the selected option value from the relevant `#font-select-x` (i.e. "arial", "verdana" etc), thus showing a real-time preview of what the font will look like.

At present I have all this working OK using something like the following in my form array to change the preview text's class to the correct font class:

```
'#attributes' => array(
  'onchange' => "jQuery('#font-preview-" . $i . " span').removeClass().addClass(jQuery('select[name=\"font-select-" . $i ."\"]').val());",
),

```

This mostly works onchange but not on page load, but on reading up further I gather there is probably a cleaner and better way i.e. using `'#attached'` to attach a Drupal behaviour, and I also shouldn't need to pass in the specific id. With jQuery I should be able to attach event handlers to each font select that update their respective preview text.

Any direction or advice would be much appreciated, as this aspect of Drupal is relatively new to me. Have read the docs and googled around but still am a little lost.

# Answer
In drupal 7, If you need to add JavaScript or CSS to your page where a form may be rendered, there is already a rendered array variable available from the Form API for just that. **drupal\_add\_js()** will not always add the JS to the form as the hook does not always run when the form will be displayed, in certain scenarios like if the page is cached. You should use the **#attached** array on any form element, if you want to add JavaScript or CSS, because this array will rendered in all certain scenarios.

```

$form['#attached']['js']["jQuery('#font-preview-" . $i . " span').removeClass().addClass(jQuery('select[name=\"font-select-" . $i ."\"]').val())"] = array( 'type' => 'inline');

```

For More details you can visit: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#attached
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to print node embed field in field collection
In one of my content type i am using field collection(Title, Image, Body). I am using node embed to embed node titles of certain content type in one of my content type. The issue i am facing is that whenever i am embedding a node it is not showing title instead of it displays \[\[nid: 2\]\].

I am printing individual field collection item, to print body i am using

```
 $section_desc =  $field_section_content_info[$section_content_id]->field_section_body[LANGUAGE_NONE][0]["value"];

```

i want node title to be displayed instead of \[\[nid: 2\]\]. what code should i write to display node title in field collection.

# Answer
> 1 votes
You are accessing the raw value of the body field in your code. I guess the functionality of replacing \[\[nid: 2\]\] comes from a text filter?

Try rendering the field with field\_view\_field instead. In the example below the label is also hidden by defining $display and passing that variable along to field\_view\_field.

```
$display = array('label' => 'hidden');
$section_desc = field_view_field('field_collection', $field_section_content_info[$section_content_id], 'field_section_body', $display);

```

---
Tags: entities
---


# Question
Title: Replace/alter/rename form labels in theme
I installed this Simplenews module, and it gives default field to enter your email to subscribe for newsletter and the fields title is just `'Email:'` and I need to change it to something else.

It looks like it's hardcoded and I could just dig through modules files and edit, but I know this is not recommended.

I was hoping maybe I could just paste in some preprocess function to theme's template.php file and replace 'Email:' with e.g. 'Join Our Mailing List:'.

Path to label is `form.simplenews-subscribe div div label`.

# Answer
Solved!

Put this code to your theme's template.php, where's THEME replace it with your theme's dir name. So then where's `#title = t()` you put in your own custom title for the field. So what it does it alters given forms field, in this case it's `simplenews_block_form` inlcuded in between `THEME_form_simplenews_block_form_alter`

```
function THEME_form_simplenews_block_form_alter(&$form, &$form_state) {
  $form['mail']['#title'] = t('Join Our Mailing List:');
}

```

Clear cache!
> 1 votes

---
Tags: theming, emails
---


title: Passing array from a form to another

text:
# Question
Title: Passing array from a form to another
I have a custom module that has a form like this :

```
    /*
 * Sytems settings form for listing skill
 */
function skillbar_form($form, &$form_state) {

    $form['skill1'] = array(
        '#type' => 'textfield',
        '#title' => t('What's your skill ?'),
        '#default_value' => variable_get('skill1'),
        '#description' => t('Enter your skill'),
    );
    $form['skill2'] = array(
        '#type' => 'textfield',
        '#title' => t('What's your second skill'),
        '#default_value' => variable_get('skill2'),
        '#description' => t('Enter your second skill'),
    );

    return(system_settings_form($form));

}

```

This form will get information from user like (`What's your skill ?`).

**FIRST :** i want to redirect user after submiting this form to another form
**SECOND** : i want to reuse data from first form ("`what's yous skill ?`") and use variable's from first form to creat second form an let user to add their percentage of skill like : `90 %`
Any help would be appreciate it

**EDIT :**

# Answer
You need to use 'rebuild' property of forms here (used in multi-steps form) :

```
 function skillbar_form($form, &$form_state) {
   if (!empty($form_state['storage']['myvalue'])) {
    drupal_set_message(t("You submitted: @name", array('@name' => $form_state['storage']['myvalue'])));
   }
   $form['skill1'] = array(
    '#type' => 'textfield',
    '#title' => t("What's your skill ?"),
    '#default_value' => variable_get('skill1'),
    '#description' => t("Enter your skill"),
   );
   $form['skill2'] = array(
    '#type' => 'textfield',
    '#title' => t("What's your second skill"),
    '#default_value' => variable_get('skill2'),
    '#description' => t('Enter your second skill'),
   );
   $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
   );
   return $form;
  }

 function skillbar_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  $form_state['storage']['myvalue'] = $form_state['values']['skill1'];
  $form_state['redirect'] = ANY_URL;
 }

```
> 2 votes

---
Tags: forms
---


title: Permissions Hook?

text:
# Question
Title: Permissions Hook?
I have a lot of user-generated content that I want to restrict to only be viewed by 'in-network' peers. I was originally trying to use Organic Groups but it's way more functionality than I need and I couldn't use it across all the entities I wanted to. Also, I could never get the og\_subgroups module to work right, and there's a hierarchical element to the rules, too.

If I just want to implement my own permissions logic, I'd use `hook_node_grants`, right? Is there an equivalent for entities or other objects?

# Answer
> 0 votes
You can use following code snippet that allow users(particular role/roles) to access nodes based on content type.

```
  function HOOK_node_access($node, $op, $account){
    if (is_string($node))
        return NODE_ACCESS_IGNORE;

    if ($node->type == 'my_type' && $op == 'view'){
        $allowed_roles = array(
            'authenticated user'
        );
        $access_allow = array_intersect($allowed_roles, array_values($account->roles));
        if ($access_allow)
            return NODE_ACCESS_ALLOW;
        else
            return NODE_ACCESS_DENY;
    }
    return NODE_ACCESS_IGNORE;
}

```

# Answer
> 0 votes
Ok this is a somewhat shameful self promotion. I too had a similar requirement but I was not willing to implement any expensive hooks just to hide some nodes.

Try this sandbox module: https://drupal.org/sandbox/ayesh/2274655

It allows you to select one or more node types and one or more roles to *allow* access to them. It doesn't support any fancy UIs or per-operation permissions but this would be a good starting point I think.

Works in individual node pages, search pages (non-admins won't see results from private node types), term pages, views, etc.

---
Tags: entities, users
---


# Question
Title: Add some custom fields in Views exposed filters and preserve their data to Url (GET)
I have a Views list of Boats and every Content Type 'boat' has a location. So I have created an exposed form that already contains a location `<select>`, and when changed, the boats are successfully filtered by the location selected. I want to put other inputs in this form, like:

* Check in Date
* Check out Date
* Number of visitors

But these data are not filters, they are just input that can be used in the next step (explained later).

1. Is there a simple way to add these custom fields in the exposed filter form (or look like being inside it somehow)?
2. How to retrieve this information, so when a specific boat is selected (that's the next step) the number of visitors,check in/out dates, etc will be shown in a similar form (Webform) which finally sends a mail..

Thanks in advance!

PS: I am a newbie on both Drupal and Drupal Answers! I've searched but I am confused whether I should create a custom module or use an existing one that I currently am unaware of.

# Answer
I think I found it! I got to the the Views' theme folder and did what exactly I show here!

Then the data-passing through different pages needs some script and is done!
> 0 votes

---
Tags: 7, views
---


title: Dynamic theme CSS editing for designer?

text:
# Question
Title: Dynamic theme CSS editing for designer?
I am working on a theme with a designer.

A Drupal theme typically stores a style.css on file system which can be access via SFTP, which may not be an easy interface for a designer.

Is it possible to provide a editable theme CSS for designer (something like editing style.css in Wordpress)?

# Answer
> 1 votes
You can try CSS Injector.

Project page says:

> Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme -- for example, a 'nighttime' color scheme could be added during certain hours. The CSS is added using Drupal's standard drupal\_add\_css() function and respects page caching, etc.

---
Tags: 7, theming
---


title: Where to find regions

text:
# Question
Title: Where to find regions
Now I have created regions.
Where I can find it to put block in it.
I have search module to put so that I can render it.

# Answer
You can't put *module* in region. You put **blocks** in regions.

Go to http://example.com/admin/structure/block to see regions and blocks assigned to them. Of course substitute *example.com* with your real domain name.
> 1 votes

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


title: Time field in EntityForm

text:
# Question
Title: Time field in EntityForm
How can I add a field in my entity form that allows the user to add time. When I use date, I can add time field but there is always a date field.

I don't want the user to add date field, just the time (for time in and time out). And also, I will use the value of that field in my query.

# Answer
> 1 votes
As per your requirement Timefield module will be the best choice(considering that you are using Drupal 7)

> Timefield is a Field API field for storing simple non-timezone time values, with an optional end time, utilizing a simple JQuery timepicker widget for input. Normally, you will want to use a Date field for all date/time values; however, this field is for use when you don't want to implement a Date field or have time values that are not dependent on the Gregorian Calendar, i.e., when Year, Month granularity is irrelevant.

---
Tags: datetime
---


# Question
Title: Commerce Paypal Payment Standard Currency Conversion
I have integrated paypal payment standard using commerce paypal module in my website. I have 2 currencies my default currency is AED. Now I have 1500 AED in a cart When I am proceeding to checkout on paypal its showing 1500 USD. Isn't it possible that the amount converts in equivalent USD automatically ??

# Answer
> 2 votes
The PayPal Payments Standard module only supports the currencies PayPal specifically identifies in its API documentation as supported currencies. When it encounters an unsupported currency, it converts it to whatever currency you have set as the default currency in the configuration of the related payment method rule. Since the default conversion rate is 1:1, that's why this is being passed to PayPal as 1500 USD.

I don't know to what extent PayPal supports the Dirham. If your account does, then it could be you need to patch the PayPal module to support payment transactions in AED. Otherwise you're going to need to use the Commerce Multicurrency module to set an actual conversion rate between the AED and the PayPal supported currency you want to receive payment / maintain a balance in.

# Answer
> 2 votes
I done this successfully, you have to follow these steps

In Currency settings go to Currency conversion then select Synchronize rates on save. Then check the option "Synchronize all rates of this currency" below at your own currency. Then unchecked the option "Synchronize this conversion rate" below at USD and save settings.

after that add product to your cart and continue to checkout you will find appropriate converted currency in Paypal payment form.

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: How to dump a single table from database using drush?
I'm aware of mysqldump utility, but is there any way of dumping a single table from database using drush (e.g. for sql-dump, sql-sync)?

# Answer
You can use **--tables-list** option on drush command to dump specific tables.

```
drush sql-dump --tables-list=node,system > exportdb.sql

```

Above command will only make sql-dump for **node** and **system** tables.

Source
> 40 votes

---
Tags: drush
---


title: Create custom page in theme templates

text:
# Question
Title: Create custom page in theme templates
i am currently working on a custom theme and i would like to know if it is possible to create a custom page which would include some php and would be visible after enabling the theme? or is it maybe better to create pages using drupal front end way and then packing it in installation profile ?

# Answer
Yes, Drupal supports custom pages. This is accomplished in Drupal 7 using a variety of php templates.

Your template must follow naming conventions to be picked up and processed.

For example, to use a template on a specific node with node ID 5, of type 'article', you'd name it `node--5.tpl.php` but if you wanted to use it on all articles, you'd use `node--article.tpl.php`.
> 0 votes

# Answer
Yes, Drupal supports custom pages.
But with different naming conventions
Follow this link of drupal.org
https://drupal.org/node/1089656
> 1 votes

# Answer
Yes custom pages are their.
Like we want to create different home page rather than page.tpl.php
Just copy page.tpl.php and paste it in your theme (remember to copy it not to cut it)
Then change the name to **page--front.tpl.php** Its in drupal 7
for drupal 6 its **page-front.tpl.php**
> 0 votes

---
Tags: theming
---


# Question
Title: How can I delete taxonomy terms for a specific node type?
I had a taxonomy vocabulary (Tags) shared across all of my content types including those like forum and blog that could be user created. I'd like to remove the terms / Tags from all node types except story. Story can only be created by site authors. Is there an acceptable way to do this?

I tried deleting the tag field from the content type. However, it does just that. The field isn't part of the type, but the terms remain assigned to the existing nodes.

If I were going to do this programmatically with a MySQL script, are there tables other than `taxonomy_index`, `field_data_taxonomy_vocabulary_`, and `field_revision_taxonomy_vocabulary_` that I'd need to delete rows from? It seems like I could generate a list of nids I want to remove terms from, and then delete the corresponding rows from those 3 tables.

Thanks in advance for any help. I'd be happy to provide additional information.

# Answer
> 2 votes
> The field isn't part of the type, but the terms remain assigned to the existing nodes.

That doesn't sound right; to the best of my knowledge removing the field from a content type will (normally) remove all data attached to nodes of that type. They get moved to a `field_deleted_*` table and then purged on a cron job.

It might indicate there's a problem somewhere in your installation, or it might just be 'one of those things'.

The 3 tables you mentioned are the only places you'll need to delete data from, but you'll also need to flush the caches after the purge (or at least truncate `cache_field`)

# Answer
> 1 votes
Deleting the taxonomy field from the content type didn't remove the taxonomy terms from the nodes. Therefore, I wrote a PHP script to generate MySQL code to programmatically delete the terms after removing the taxonomy field from the nodes via the admin menu.

```
<?php

// put your database name here
$database = '';

// put your vocabulary table suffix here
// will be appeneded to table names like `field_data_taxonomy_` and `field_revision_taxonomy_`
$vocabulary = 'vocabulary_2';

$connection = mysql_connect(HOST, USER, PASS);
$nids = array();
$fp = fopen('taxonomy_clean.sql', 'w');

if (!$connection)
{
    echo 'Unable to connect to database: ' . mysql_error();
    exit;
}

if (!mysql_select_db($database))
{
    echo 'Unable to select ' . $database . ': ' . mysql_error();
    exit;
}

// get nid from all nodes except story type
$result = mysql_query('select * from ' . $database . '.node where type != \'story\' order by nid asc;');

while ($row = mysql_fetch_assoc($result))
{
    $nid = $row['nid'];
    $nids[] = $nid;
}

echo PHP_EOL, count($nids), ' nids', PHP_EOL;

// remove the taxonomy terms from the nodes
$taxonomy_index = 'DELETE FROM ' . $database . '.taxonomy_index WHERE nid IN (' . implode(',', $nids) . ');';

$field_data_taxonomy_vocabulary = 'DELETE FROM ' . $database . '.field_data_taxonomy_' . $vocabulary . ' WHERE entity_id IN (' . implode(',', $nids) . ');';

$field_revision_taxonomy_vocabulary = 'DELETE FROM ' . $database . '.field_revision_taxonomy_' . $vocabulary . ' WHERE entity_id IN (' . implode(',', $nids) . ');';

// write the MySQL script to disk
fwrite($fp, $taxonomy_index . PHP_EOL . PHP_EOL);
fwrite($fp, $field_data_taxonomy_vocabulary . PHP_EOL . PHP_EOL);
fwrite($fp, $field_revision_taxonomy_vocabulary . PHP_EOL . PHP_EOL);

fclose($fp);

?>

```

The script worked fine with PHP 5.4, and will generate `taxonomy_clean.sql`. I used `mysql` via the command line to run `taxonomy_clean.sql`. I cleared the cache after and everything worked fine.

# Answer
> 0 votes
You can do it using Drush **field-delete**,

Delete a field and its instances.

Examples:

```
 field-delete city                         Delete the city field and any instances it might have.
 field-delete city --bundle=article        Delete the city instance on the article bundle

Arguments:
 field_name                                Name of field to delete.

Options:
 --bundle                                  Only delete the instance attached to this bundle. If omitted, admin can choose to delete one instance or whole
                                           field.
 --entity_type                             Disambiguate a particular bundle from identically named bundles. Usually not needed.

```

Original Source

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


title: Add unlimited fields to block module

text:
# Question
Title: Add unlimited fields to block module
I'm creating a module which adds a block. In that block, I want users to be able to add as many (text) fields as they need. I know you can set up content-types to allow users to add as many fields as they need, but how can I implement this into a block module?

Long story short: is it possible to add a text field with an unlimited amount of fields to a block (module) the same way it can be done in content types?

# Answer
> 0 votes
You might be looking for Node Block module.

With this module you can make your block fieldable, like your content-types.

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

Check out this quick Demo Video

---
Tags: 7, blocks
---


# Question
Title: How do I create custom regions in a theme?
I want to add a new area which will be site wide. Describe the process of getting this new region into my theme, if possible generalize it for adding any new, custom region.

# Answer
You define regions in your theme .info file. See: Structure of the .info file

You then need to put the relevant template tags in your page.tpl.php file.

So for example if you defined the region `sidebar` in your themes .info file, you would then add: `<?php print render($page['sidebar']); ?>` to the relevant place in your page.tpl.php.
> 68 votes

# Answer
One other point: Don't miss the required regions!

```
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom

```

More on this can be found at http://drupal.org/update/themes/6/7#closure.

To clarify on this point: If you define your own regions, you need to define all that you are using, including those that are required. In other words, you cannot just define additional regions: If you define any, you must define them all.
> 20 votes

# Answer
Creating a region for a Drupal 7 theme is not different from creating a region for a Drupal 6 region; the differences between Drupal 7 and the previous versions are essentially:

* The regions are not defined using a `mytheme_regions()` function as it was done in Drupal 5, but they are defined in mytheme.info using `regions[]` directives, which is what is done also with Drupal 6 themes.
* The regions are rendered using the Drupal function `render()`, instead of printing the content of a variable.

The default Drupal 7 regions are the following ones:

```
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer

```

Drupal 7 core themes now include a region named 'highlighted' which uses the same display as the mission statement area in Drupal 6; they also include a region named 'help', that by default has the same content of the `$help` variable used by Drupal 6.
> 9 votes

# Answer
The theme regions are defined in your theme .info file — see docs. Just add a line with `regions[corner] = Corner` to get a Corner region.

Then you need to edit the page.tpl.php file and add `<php print render($corner); ?>` where you want the region to show up. If your theme doesn't have a page.tpl.php, copy from the base theme or from the system module.

Common pitfalls:

* If the theme.info file had no regions declared, it was using Drupal default regions. If you want to add, you will have to re-declare the default regions. You can, of course, remove any region but please support the required regions. See the docs again.
* Changes to the .info file or adding new files to the theme (like page.tpl.php) will only be noticed after you clear caches.
* Omega, a very popular base theme, won't need any change in page.tpl.php, just the .info file. But you will have to visit the theme settings in the UI and assign your region to a zone.
> 4 votes

# Answer
Follow the below steps to create custom region in your theme:

1. Go to your theme.info file and add this line.

```
regions[machine_name_of_your_region] = Name of your region

```
2. Although you can also call region blocks in the node template as well, you will generally add the region to the theme's page template. This is usually page.tpl.php, or if you have custom template files for different pages, edit those ones too. The new region will appear only on the pages built around the template you add the new region to. Paste it wherever you want your new region to appear.

```
<?php if ($page['machine_name_of_your_region']): ?>
  <div id="sidebar-first" class="column sidebar"><div class="section">
  <?php print render($page['machine_name_of_your_region']); ?>
  </div></div> <!-- /.section, /#sidebar-first -->
 <?php endif; ?>

```
3. Configuration - Performance - Clear all caches
> 2 votes

# Answer
## Create a New region in Theme

You Just need to define it in two files.

* Theme.info
* Page.tpl.php

### Theme.info

```
;;;;;;;;;;;;;;;;;;;;;
;; Regions
;;;;;;;;;;;;;;;;;;;;;

regions[navigation]      = 'Navigation'
regions[header]          = 'Top Bar'
regions[highlighted]     = 'Highlighted'
regions[new_region_name] = 'Region Name' ;; Add New Region

```

### Page.tpl.php

Now render this region

```
  <?php if ($page['new_region']): ?>
      <div class="new_region_class">
        <?php print render($page['new_region']); ?>
     </div>
  <?php endif; ?>

```

Now Clear all cache, Here you go, you have a new region in your theme. You can see it at your block configuration page.

For more visit http://drupal.org/node/171205
> 0 votes

---
Tags: theming
---


# Question
Title: How to make a image url active in Views Table
I've got a table with a column for images. The field display is link (see screenshot). For some reason it doesn't display as an active link. Any ideas on how to accomplish that?

# Answer
> 0 votes
I assume that this is a file field and that you chose `URL to File` as the field formatter. You would then need to scroll down and expand `Rewrite results`, tick the box for `Output this field as a link`, and in the box for `Link path` you need to enter the views token replacement for your field name, which you can find by expanding the section below titled `Replacement patterns`—in your case it is likely to be `[field_scan]`

Once you enter that, you should have what you are calling "active link" which in more precise terms would be called an hyperlink or anchor tag.

---
Tags: views, uri, theming
---


title: How to run a rule for a specific user?

text:
# Question
Title: How to run a rule for a specific user?
I want to redirect a specific user when he logs in.

There are 4 users.

Each one must go to a different url.

Under the rule I have What do I need to put in for the conditions?

# Answer
using "Text comparison" for the condition worked.

So I created a rule for each specific user.

But rather look to the other answer
> -2 votes

# Answer
There are many other methods to do it, but I prefer this method,

Try this on your Rules module.

> Events: **User has logged in.**
>
> Condition: **User has role**
>
> Actions: **Page redirect**
> -1 votes

---
Tags: rules
---


# Question
Title: Display comma-separated list of taxonomy terms?
In my `node.tpl.php` template, I want to print out a list of taxonomy terms (the taxonomy is called "channels."). If I use:

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

```

It works, obviously, but the best I can do to get them inline is to use CSS to float them left. I would like them to be separated by commas. Any ideas?

# Answer
You could try theming the field using `field.tpl.php` or `theme_field()`.

As an example (using `field.tpl.php`):

1. Copy `field.tpl.php` to your theme directory from "modules/field/theme"
2. Make a copy of that file and rename it to `field--field-channel.tpl.php`
3. Edit the file however you like.

As a quick/dirty example for this to work, `field--field-channel.tpl.php` could look like:

```
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php if (!$label_hidden) : ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>: </div>
  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item) : ?>
      <div style="display:inline;" class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>
        <?php
          print render($item);
          // Add comma if not last item
          if ($delta < (count($items) - 1)) {
            print ',';
          }
        ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>

```

There are probably multiple ways to accomplish this using the .tpl file, but this is just one option. I recommend adding a class to the DIV instead of a style and make the changes in your stylesheet instead of using inline styles.
> 12 votes

# Answer
The Text Formatter module is now available for Drupal 7, and lets you do this without custom theme work.

> This module provides a field display formatter to render field values as HTML or comma-separated lists. This can currently be used on all core field types (text, long text, number, list, and taxonomy reference etc..) and some contributed fields. (see below).
>
> For multi-value fields, each field value becomes a list item. For long text fields, each line becomes a list item.
> 12 votes

# Answer
Here's one way to use the `theme_field` approach (add it to your `template.php` file):

```
/**
 * Implements theme_field()
 *
 * Make field items a comma separated unordered list
 */
function THEMENAME_field__NAME_OF_FIELD__NAME_OF_CONTENT_TYPE($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
  }

  // Render the items as a comma separated inline list
  $output .= '<ul class="field-items"' . $variables['content_attributes'] . '>';
  for ($i=0; $i < count($variables['items']); $i++) {
    $output .= '<li>'. drupal_render($variables['items'][$i]);
    $output .= ($i == count($variables['items'])-1) ? '</li>' : ', </li>';
  }
  $output .= '</ul>';

  return $output;
}

```
> 7 votes

# Answer
You can do this easily just in CSS:

```
.field-type-taxonomy-term-reference .field-items .field-item {
  display: inline-block;
  *display: inline;
  *zoom: 1;
}
.field-type-taxonomy-term-reference .field-items .field-item:after {
  content: ", ";
}
.field-type-taxonomy-term-reference .field-items .field-item:last-child:after {
  content: "";
}

```
> 5 votes

# Answer
Use a preprocess function: http://planken.org/2009/08/03/create-comma-separated-taxonomy-term-list-drupal
> 2 votes

# Answer
```
<?php
if ($node->taxonomy) {
    foreach($node->taxonomy as $term) {
        if ($term->vid == 3) { // the id of the vocabulary
            $my_terms[] = l(
                t($term->name),
                'taxonomy/term/' . $term->tid
            );
        }
    }
}

if ($my_terms) { ?>
    <div class="clear-block">
        <div class="terms">
            <?php print implode(", ", $my_terms); ?>
        </div>
    </div>
<?php } ?>

```
> 0 votes

# Answer
Even easier for delimiter and the wrapper, you use the Taxonomy Formatter module: http://drupal.org/project/taxonomy\_formatter

More details from project page:

> This is a small module written to provide a custom formatter for taxonomy items. The default formatters both output the terms wrapped in divs. This module adds a new formatter that allows you to specify the element type, the wrapper type, classes for both, the separator used, and if they link to the term pages or not. This gives much more customizable layout options.
> 0 votes

---
Tags: theming, taxonomy-terms, nodes, 7
---


# Question
Title: Views Autocomplete search multiple values
I'm trying to have a search filter that searches on 2 values and works with autocomplete list.

This is what I've done:

* Installed the module Views filters populate.
* added two filters "CNK" and "Naam" (both not exposed) and added them to a OR filter group. I used the operator "Contains any word" for both fields.
* Created a filter "Global: populate filters", added the two fields into this and exposed it.

My filter criteria looks like this:

But I don't have the option for autocomplete. How can I do this the best way?

# Answer
You can use Views autocomplete filter module to have auto-complete feature on views exposed filters.

> It works for node titles or cck text fields.
>
> The autocomplete results are actually the view results, so they are view related.

Check out this Demo video.
> 2 votes

---
Tags: views, ajax
---


title: How to copy a forum thread?

text:
# Question
Title: How to copy a forum thread?
I want to move a forum thread with all the posts from one server to another. What is the most convenient way to do so?

# Answer
> 0 votes
You can try using Bundle Copy Module...

> Has export/import support for:
>
> * Node types
> * Taxonomy
> * User
> * Field API fields
> * Field groups
>
> You can find the export/import links for the supported entities on following paths:
>
> * Nodes: admin/structure/types
> * Taxonomy: admin/structure/taxonomy
> * Users: admin/config/people/accounts

---
Tags: 7, nodes
---


# Question
Title: how to grant a user to only access the performance area of the configuration screen drupal 7
I would like to give my content editors the ability to flush the website Drupal cache. I can't seem to give them this privilege without also giving them the privilege to do everything in the configuration tab. Can I only give them permissions to clear the cache? (Obviously this in addition to editing content) I am using Drupal 7.

Thanks!

# Answer
you can write a simple custom module to do this for you. as you can see.with hook\_menu\_alter you can alter all menu in drupal. And by overriding it's access callback you can have your custom function to grant access to your users. Here is a sample code that check if user has an 'editor' role.then it return true and user can access performance.

```
function MYMODULE_menu_alter(&$items) {
  $items['admin/config/development/performance']['access callback'] = '_accesscheck';
}

function _accesscheck(){
  global $user;
  if(in_array('editor', $user->roles)){
     return TRUE;
  }
  return FALSE;
}

```
> 3 votes

# Answer
You can try Flush page cache module, using this module you can set permission for granting clear-cache options to certain **Roles**.

> Features
>
> * Many button placement options including: in the page footer, with a block, or if you use the Administration Menu module, a link is included there as well.
> * The ability to define specific cache objects to be cleared when flushing page caches.
> * Varnish integration, which also purges the cached page from Varnish.
> 0 votes

---
Tags: users, caching, configuration
---


# Question
Title: Parent and subordinary weights and relations like in menu and taxonomy system module
It seems that there is no module in the contribution repository which simulates the behaviour like this of terms in given vocabulary or menu items in a given menu from system modules in Drupal 7. (?) Wouldn't it be an interesting use-case to achieve something like entity trees simultaniously this way, like a task and sub task management, with a given weight and relation to each other to build parent and subordinary relations between them? I know about many reference and relation modules and asked already some specific questions about them and their limits here but I can't find an entry point where I could start to contribute on this special scenario. I can easely drag and drop taxonomy terms or menu items and give them an "order" and sub "order" in their hierarchy already from core and the system "knows" about this order. Not only of one level, also for more levels. It is not visually only. So I can build paths based on that relations. It seems that this is not possible to make with entities and any reference or relation modules out there ? Am I right or is my question asked the wrong way around?

# Answer
Couldn't you do this with the Relation module, views and Rules?
> 1 votes

---
Tags: 7, entities
---


title: Dynamic arguments in an AJAX link

text:
# Question
Title: Dynamic arguments in an AJAX link
I have a link that uses Drupal's `use-ajax` CSS class to AJAX-load some node teasers. The callback for the link uses arguments to set a range in the Entity Field Query used to return the teasers:

```
function marketplace_ajax_list_menu() {
  $items = array();
  $items['marketplace_ajax_list_callback/%/%/%'] = array(
    'page callback' => 'marketplace_ajax_list_response',
    'page arguments' => array(1, 2, 3),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function marketplace_ajax_list_response($type='ajax', $collection_nid, $start, $page_limit) {
  if ($type == 'ajax') {
    $output = marketplace_ajax_list_collection_latest_content($collection_nid, $start, $page_limit);
    $commands = array();
    $commands[] = ajax_command_append('#ajax-target', $output);
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }
}

function marketplace_ajax_list_collection_latest_content($collection_nid, $start=0, $page_limit=10) {
  $q = new \EntityFieldQuery();
  $q->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', array('story', 'reader'))
      ->propertyCondition('status', 1)
      ->fieldOrderBy('field_date', 'value', 'DESC')
      ->fieldCondition('field_ref_collection', 'nid', $collection_nid, '=');

  // Get the matching items within the range
  $q->range($start, $page_limit);
  $result = $q->execute();
  $nids = array_keys($result['node']);

  // Make node teasers
  $nodes = node_load_multiple($nids);
  $teasers = node_view_multiple($nodes);
  $build = render($teasers);

  return $build;
}

```

When the node teasers are appended to the list, I have a jQuery function that updates the arguments in the AJAX link in order to update the range used in the query:

```
(function ($) {
  var page = 1;
  var page_limit = 10;
  var collection_nid = 12345;

  Drupal.behaviors.marketplace_ajax_list = {
    attach: function(context, settings) {
      page++;
      var link = '/marketplace_ajax_list_callback/nojs/' + collection_nid +'/' + (page_limit * page) + '/' + page_limit;
      $moreBtn.attr('href', link); // $moreBtn is the AJAX link
    }
  };
})(jQuery);

```

The link's href changes correctly, with the updated arguments, but the new arguments aren't used in the callback's query - the same arguments are used each time, so the same items appear on each click.

If I take the value that jQuery sets in the href and open the link in another tab, I see the correct items.

So I think the issue has to do with the AJAX behavior getting attached to the link and that's not updated each time the function runs. Is there a command I can add to make that happen?

# Answer
> 2 votes
Solved! I found this post - https://drupal.stackexchange.com/a/52788/260 \- which answered a very similar question, and that changed everything. This issue is essentially a duplicate of that one.

The fix here in my case was to not just change the link's href but to also update the Drupal.ajax object, like this:

```
Drupal.ajax['load-more'].options.url = link;

```

"load-more" is the ID of the AJAX link.

---
Tags: ajax, javascript
---


title: How to Button a Rules Link URL

text:
# Question
Title: How to Button a Rules Link URL
I'm using Rules Link, via a Views block set in a user Panel page. At the moment it sits ready for a users click response to trigger an event and works fine in its approach.

Prior to major Theming/CSS, I would like to have the generic 'Blue' URL text link show as a graphic button (ie generic 'bootstrap' style), can anyone advise the quickest way to change this so I can get a feel of the layout and look. I presume it's a CSS template addition, can someone give me some tips (I'm using Bootstrap) Thanks in advance for any help.

# Answer
> 1 votes
After study, I used the above css with a 'btn btn-primary btn-block' in the Other of my View (where the Rule itself goes) in the CSS information properties. It for now gave me a working button, but it does need some further CSS, but I have my answer.

Additionally, I added :

```
/* Rules Link Post unvisited link */
.rules-link-post-classified
a:link {
    color: #FFFFFF;
}
a:hover {
    text-decoration: none;
}
a:active {
    text-decoration: none;
}

```

into my theme.css (using currently the Tweme Bootstrap). As I wanted white text on a blue button, and then I used the above css with a 'btn btn-primary btn-block' in the other of my View in the CSS information properties.

Furthermore, I didn't want the 'hover' underline to show on the link when the user moved over it to click, so I used the text-decoration as 'none' to remove it under the 'a:hover' with 'a:active' elements above.
BINGO!

There maybe more functional CSS ways in the file.css, but hey we're learning!

---
Tags: rules, theming, navigation
---


# Question
Title: How to setup a csv-file to import image-paths into an image-field via Feeds-module?
I import a csv-file via Feeds-module and got stuck with the images for a node. All the other fields are importet as wanted, except the path for the image-field. The images are already uploaded to the directory below...

An example for a row value of a path: sites/all/default/files/images/name.JPG

After the import, the image field is just empty:

Any help would be highly appreciated! Thanks in advance...

# Answer
You need to specify the full HTTP path. It's possible that something like a file schema might work (`public://images/name.JPG`), but in my extensive use with Feeds we import file fields (mostly images but also mp3, pdf, etc) by specifying the full HTTP path that the file can be found at, e.g.: `http://example.com/sites/default/files/images/name.JPG`.
> 7 votes

# Answer
For local path, what worked for me was putting the file under sites/default/files of the drupal project it is in. The value of import file would **public://filename.ext**
> 0 votes

---
Tags: 7, feeds, media, importing-exporting
---


title: Show children of a Taxonomy Term

text:
# Question
Title: Show children of a Taxonomy Term
I make use of the view: "taxonomy term". Is there an easy way to also show the children of a term, next to the nodes beloging to this term?

Example:

```
Cars
- Volvo
--- Family_cars
--- Sports_cars
- Honda
--- Parts
--- ...
Trucks
- ...

```

When you see the "cars" page I want to show all articles about cars (but not about Volvo, Honda, ...) AND I want to show the children (Volvo, Honda, ...) When you click one of these I want to show all the articles belonging with them, again with their children.

# Answer
If I understood you correctly, you want to display nodes that have a term, but not the nodes that have a child term.

You also want to display the child terms.

There are some different ways of handling this, since you are using the default view, you should get a View already that displays the correct nodes - so all you are missing is the terms.

The best way to deal with this, is not through Views, but a module called Taxonomy menu. It will create a menu with the same structure of a vocabulary which can expend, to show child menus. As with menus you get use the block system to add them on the term pages. Beware of a bug with the menu system though see the issue.

A quick fix is to add this in your settings file:

```
$conf['menu_default_active_menus'] = array(
  'navigation',
  'management',
  'user-menu',
  'main-menu',
  'your-menu-here',
);

```
> 2 votes

# Answer
1.taxonomy/term/x -- where x is the term id to show, a number.

2.to show children nodes you need to add a depth variable. The syntax is: taxonomy/term/x/y -- where x is the term id to show, and y is the depth to go below x.

3.to show all children nodes. The syntax is: taxonomy/term/x/all -- where x is the term id to show.
> 0 votes

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


# Question
Title: Show all child nodes of a taxonomy term D7
Ok, so I've been ripping my hair off for the past 2 days now. I'm developing a web-site with a car catalog which contains the following hierarchy (taxonomy hierarchy):

```
-brand1
--model1
--model2
--model3
-brand2
--model1
--model2
--model3

```

...and so on.

What I'm trying to achieve is when a user selects a parent term (brand), they'll see all the nodes from all the children terms. Currently a parent term doesn't display anything.

I already Googled my problem but none of the solutions seem to work for me (or it's possible I'm doing something wrong).

My configuration is as follows: Drupal 7.2x Views 3.7 Taxonomy Menu 1.4 module - used for generating menu trees from vocabularies. Pathauto 1.2

I use views to display the whole vocabulary - and it works as intended.

Can some one please give me a step-by-step guide on how to achieve this? Especially if it involves Views, as I'm still a noob with Views.

Is it possible the Taxonomy Menu module is causing trouble?

# Answer
Actually there's a very easy (built-in) method...

1. Go to `admin/structure/views`, find the view named *Taxonomy term*, and enable it
2. Go to `admin/structure/views/view/taxonomy_term/edit`
3. Click *Advanced* (on the right)
4. Click *Content: Has taxonomy term ID (with depth)*
5. Select a *Depth* of 1 or more
6. Save all your changes

Now, assuming the term id of *Brand 1* is 1, when you visit `www.yoursite.com/taxonomy/term/1`, you should see all the child nodes listed. You can also create path aliases to make paths like `taxonomy/term/1` more "pretty".

Hope that helps...

:)
> 13 votes

# Answer
1. `taxonomy/term/x` -- where x is the term id to show, a number.
2. to show children nodes you need to add a depth variable. The syntax is: `taxonomy/term/x/y` -- where x is the term id to show, and y is the depth to go below x.
3. to show all children nodes. The syntax is: `taxonomy/term/x/all` -- where x is the term id to show.
> 0 votes

---
Tags: 7, views, nodes
---


# Question
Title: Pages displaying blank ONLY when Theme Developer module turned on
i have a situation where the theme developer module, when turned on, is causing some pages to display as the white page (of death). it's probably because i've been doing tutorials, learning how to override theme functions and probably at one point had some errors. but there errors have been cleared up, but the pages display as blank pages ONLY when that module is turned on. it's as if it has it's own cache???,

anyone know how to remedy that?, i need module to work.

# Answer
This might be due to version compatibility with Simplehtmldom module.

Download this library and install in your sites/libraries files.

This is taken from modules page,

> **NOTE**: Currently, Theme Developer does not work with the latest version of simplehtmldom API. You must use simplehtml API version 7.x-1.12 if you want Theme Developer to function properly.

OR if that is not the case you can try putting this snippet end of the settings.php file, this snippet will show error message on the browser while loading page instead of **WSOD**. and you can put your error message here in question and elaborate it.

```
  error_reporting(E_ALL);
  ini_set('display_errors', TRUE);
  ini_set('display_startup_errors', TRUE);

```
> 0 votes

---
Tags: 7, theming
---


title: two-stage user activation from database

text:
# Question
Title: two-stage user activation from database
I'm trying to create a system where, say for a school or other organizations, I can load a ton of users into a database at once, so that they are grouped separately from other databases of users. However, I then want it so that when the user logs in for the first time, it will ask them to fill in all the remaining fields that aren't loaded from the original database, such as a password and email.

is there an easy way to do a two-stage user creation like this?

# Answer
> 0 votes
Always best to include the Drupal version you are making use of, for the purpose of the answer will assume its Drupal 7;

So there are two parts to this;

1) The user data upload to drupal; you could make use of the Migrate module; I would think in the very least you would need to set the username and a temporary password to facilitate the first time login instance.

2) To force the user to fill in his details you could make use of the hook\_user\_login in a custom module implementation to validate that the user's details have been filled in.

---
Tags: database, users
---


title: How to limit posts per hour?

text:
# Question
Title: How to limit posts per hour?
In order to fight spammers, I'd like to limit the number of threads and posts that authenticated users can create per hour. What is the easiest way to do so?

# Answer
You can use Node limit module to limit the users form creating nodes.

This is Form project page,

> * **Per-role node limits**
> * **Per-user node limits**
> * **Per-time interval node limits**
> * Any combination of the above
> * Drupal 6 & 7 compatibility Requires no programming on the part of the administrator

Also look into Honey pot module.

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site (read more here). These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

Taken form project page:

> The module currently supports enabling for all forms on the site, or particular forms like user registration or password reset forms, webforms, contact forms, **node forms, and comment forms**.

demo
> 1 votes

# Answer
Flood control module in addition to the modules mentioned in this duplicate question

From module page

> This project is intended to add an administration interface for hidden flood control variables in Drupal 7, like the login attempt limiters and any future hidden variables.
> 1 votes

---
Tags: 7, advertising
---


title: Views alphabetical pager

text:
# Question
Title: Views alphabetical pager
I need the exact config as displayed in the image above. I need to have the entire alphabet showing and I need the title of content to be displayed below the Letter it belongs to. Can we get a detailed explanation on how that can be achieved?

# Answer
> 3 votes
This is achievable using just the views module (albeit in a somewhat contorted configuration), with a little CSS3 for layout. I will assume that the field you are displaying is simply node title, although it could be any field or combination of fields.

**First**, you create the page grouped by the first letter of the title field. To do this, create a page view named "Alphabetical Index" that uses Unformatted list of fields and add `Content:title` field with `Link this field to the original piece of content` ticked. Now add a second `Content:title` field, this time tick `Exclude from display`, expand `Rewrite results` and tick `Trim this field to a maximum length` and for the length enter `1`. Now edit the `Settings` of your `Unformatted list` and Select your excluded title field as `Grouping field Nr.1` (should be the second `Content:title` in the dropdown) and tick `Use rendered output to group rows`. This should give you a single-column list of linked titles, grouped by the first letter. Use something like the following CSS3 in your theme to get it to wrap in a responsive multicolumn type of way:

```
  .view-alphabetical-index .view-content {

  /* Multi-column */

  -webkit-column-count:auto; /* Chrome, Safari, Opera */
  -moz-column-count:auto; /* Firefox */
  column-count:auto;

  -moz-column-width:220px; /* Firefox */
  -webkit-column-width:220px; /* Safari and Chrome */
  column-width:220px;

  -webkit-column-gap:40px; /* Chrome, Safari, Opera */
  -moz-column-gap:40px; /* Firefox */
  column-gap:40px;

  -webkit-column-rule:2px outset #e1e2e4; /* Chrome, Safari, Opera */
  -moz-column-rule:2px outset #e1e2e4; /* Firefox */
  column-rule:2px outset #e1e2e4;
}

```

This should give you the list you are after. Now we need to plop in an alphabetical pager at the top somehow . . .

**Next**, you make an alphabetical pager that restricts your list to only one letter at the URL `yourview/a`, `yourview/x`, etc. To do this, you create a contextual filter on your first `Content:title` field and all the way at the bottom expand the `More` section and put it into `Glossary mode` and enter `1` for the `Character limit`.

Getting the pager at the top has already been covered in Create alphabetical pager

In order to have all items show at the base URL, I had to edit the contextual filter to `Provide default value` *Type*: `Fixed value` and type `all` into the box for`Fixed value`. Then I had to create a clone of the view with a page URL set to something after the original view, and add an attachment to this cloned view with a glossary mode pager contextual filter that has its `When the filter value is NOT available` set to `Display a summary`, `Sort by: Alphabetical` then load that attachment into the header of the original view using `Global:View area`.

---
Tags: views, paging
---


title: Saving a Form with Custom Button

text:
# Question
Title: Saving a Form with Custom Button
I am trying to create a custom button that modifies a field in a form then saves the form in the same way as the default save button. The following code creates the button but I am having trouble finding where/how to perform the operation that clicking the default save button executes, with validation and updating every field before executing my submit code.

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

     if ($form_id == 'submission_node_form') {
         $form['actions']['final_submit'] = array(
            '#type'   => 'submit',
            '#value'  => t('Submit'),
            '#submit' => array('mymodule_form_final_submit')
         );
     }

}

function mymodule_form_final_submit($form, &$form_state) {

}

```

# Answer
A simple way is calling drupal\_form\_submit in your custom module

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

  drupal_form_submit('submission_node_form', $form_state);

}

```
> 1 votes

---
Tags: nodes, forms
---


# Question
Title: How do I get rid of "Body:" as highlighted bellow?
what can be done to get rid of highlighted section from the top of content?

# Answer
> 1 votes
* Login as Administrator
* Go to admin/structure/types
* Click on Manage Fields next to above content content type..

* Click on Mange Display
* Hide Body label like shown below..

---
Tags: theming, nodes
---


# Question
Title: Question about template_preprocess functions
i noticed there exists a template\_preprocess\_field function on the Drupal website, but i added in my template.php files just this...

```
function mytheme_preprocess_field(&$variables, $hook) {
   kpr($variables);
}

```

my question is, is the drupal function running too? in the system somewhere as well as my preprocess function?,

they seem to both be running. any insight would be helpful, thanks

# Answer
> 1 votes
Yes definitely it will go to parent function too because this is concept of overriding. But final impact would be of your override function.

Say example:

// Parent Function: First go to this fucntion

```
function template_preprocess_field(&$variables, $hook) {
   print "Parent Function";
   $variables['test_variable'] = "Parent data";
   ....
}

```

// Child Function: Override values using child function

```
function mytheme_preprocess_field(&$variables, $hook) {
   print "Child Function";
   $variables['test_variable'] = "Child data"; // Override value here
   ....
}

```

Now this **$test\_variable** contains **"Child data"** value not *"Parent data"* because it is overrided.

I hope it would help you to understand basic concept of overriding.

---
Tags: theming
---


# Question
Title: Is there a replacement for comment driven?
The comment driven module and similarly the comment alter module are dead or dieing and have no ports to drupal 7. Anyone know if there is a module that could replace either of these?

# Answer
> 1 votes
I have found a replacement for my uses of comment driven. Its called Node Changes, and allows changes to nodes to be recorded as comments.

> This module stores the changes of a node into a field attached to comments allowing to display a kind-of activity stream on the node much like on drupal.org issues just with a lot less custom code.

# Answer
> 0 votes
Try Comment Alter Module which makes it possible to alter (change values of) fields on a node when leaving a comment. However, unlike those modules which have the available fields hard-coded, this module allows you to edit any field on a content type and check "Enable altering this field from comments"!

> This can be used to create a tracker similar to Case Tracker or other support or project management modules.

---
Tags: 7, comments
---


# Question
Title: Page Navigation issue after executing a jQuery
Using JSinjector, i included a jQuery and made use of a function. I wrote a query inorder to display the external link within a certain div section (within our site). My code goes here

```
 (function ($) {
       Drupal.behaviors.YOURTHEMENAME = {
              attach: function(context, settings) {
              $('.div-classname a').click(function(){
              var url = $(this).attr('href');
              var height = $('#div-id-name').height();
              var width = $('#div-id-name').width();
              $('#div-id-name').replaceWith( "'<object data="+url+" width="+width+" height="+height+"/>'" );
               return false;
             });
           }
         };
         })(jQuery);

```

In concise, the above query does the functionality - " whatever the hyperlinks within the div class (div-classname) when clicked the corresponding website opens within the div with id (as div-id-name). Previously, div-id-name region has a content but when the hyperlink is clicked, jquery executes now the content (within the div-id-name) is replaced with the corresponding site.

Everything goes well the query works..

But my problem here is after the content is replaced with the corresponding link, now when i press the back button - rather than loading the previous page or the website's home page it redirects to the browser's home page (i.e., either google.com or whatever).

What might be the problem? Is there any thing link configuration issues? or do I need to include any code (query)..

I m using Drupal 7

# Answer
Disable the click function for the more links div.

```
$('.div-classname a').on('click',function(){.....});

$('.more-link a').off('click');

```

This is the perfect solution.
> 0 votes

---
Tags: javascript, 7
---


# Question
Title: Transforming the external link with in the site
sorry if the title is not apt, I'm new to Drupal. Here I'm working in drupal 7 the site has a news feed module, automatically updates the contents (links). When these links are clicked the corresponding links will be opened in the new tab or in the same tab (closing our actual site). So to avoid this, I would like display the corresponding link's page with in our drupal site. so that our drupal site will be active and the corresponding newsfeed link will be opened within our site (like wise displaying the web page in an iframe)

I tried of using iframes, but couldn't get what i wanted. I came across a module 'Fences' which looks good, but i couldn't know completely about the usage of fences module.

Can any one list out how to solve the issue.

# Answer
Using iframes is not a good option. Besides, I suggest to start using jQuery and update the function for the specific 'div'. We can add jQuery using JSinjector module, Navigate to JSinjector as Configuration/development/JSinjector.

Hope It would work fine in such a kind of issues.
> 0 votes

---
Tags: feeds
---


# Question
Title: Drupal add fieldset inside form and wrap all form elements under that fieldset
I want to add fieldset tag inside form tag. Also i want to wrap all the form element under this fieldset. I'm using the following function to change the form design and html.

MY CODE:

```
function change_password_form($form, &$form_state) {
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }
  $form['#account'] = $GLOBALS['user'];
  $form['fieldset']['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE,
  );
  return $form;
}

```

CURRENT OUTPUT :

```
<form action="/projects/drupal/hpedu/change-password" method="post" id="change-password-form" accept-charset="UTF-8">
<div>
<div class="form-item form-type-password form-item-current-pass">
  <label for="edit-current-pass">Current password <span class="form-required" title="This field is required.">*</span></label>
 <input type="password" id="edit-current-pass" name="current_pass" size="25" maxlength="128" class="form-text required">
</div>
<div class="form-actions"><input type="submit" id="edit-submit" name="op" value="Submit" class="form-submit"></div><input type="hidden" name="form_build_id" value="form-pGcx3HehTZlOkicX1gaBrr5eBjv8iT6iccQvCN8uXTU">
<input type="hidden" name="form_token" value="1qygden7YqhLlXvjiC8-ypYDXhOKwW_brUB4BdXlKNU">
<input type="hidden" name="form_id" value="change_password_form">
</div>
</form>

```

EXPECTED OUTPUT :

```
<form action="/projects/drupal/hpedu/change-password" method="post" id="change-password-form" accept-charset="UTF-8">
<fieldset class="myclass"> <!-- This Fieldset , which i want to add -->
<div>
<div class="form-item form-type-password form-item-current-pass">
  <label for="edit-current-pass">Current password <span class="form-required" title="This field is required.">*</span></label>
 <input type="password" id="edit-current-pass" name="current_pass" size="25" maxlength="128" class="form-text required">
</div>
<div class="form-actions"><input type="submit" id="edit-submit" name="op" value="Submit" class="form-submit"></div><input type="hidden" name="form_build_id" value="form-pGcx3HehTZlOkicX1gaBrr5eBjv8iT6iccQvCN8uXTU">
<input type="hidden" name="form_token" value="1qygden7YqhLlXvjiC8-ypYDXhOKwW_brUB4BdXlKNU">
<input type="hidden" name="form_id" value="change_password_form">
</div>
</fieldset>  <!-- This Fieldset , which i want to add -->
</form>

```

Any help would be greatly appreciated.

# Answer
It should be something like this.

```
function change_password_form($form, &$form_state) {
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }

  $form['#account'] = $GLOBALS['user'];

  // To make the fieldset define #type as fieldset
  $form['fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Password Info'),
    '#collapsible' => TRUE, // Added
    '#collapsed' => FALSE,  // Added
  );

  $form['fieldset']['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE,
  );

  return $form;
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: why doesn't system_menu() return the option I am expecting
If you go to this website: https://api.drupal.org/api/drupal/modules%21system%21system.module/function/system\_menu/7

You will see what system\_menu is supposed to output. My Drupal 7 has a jquery update under the development menu in the configuration tab. Why doesn't the jquery update option show up? Is there another function that I should be looking at?

Thanks!

# Answer
> 0 votes
It's hard to know what you mean, but at a guess you're expecting `system_menu()` to be responsible for *all* of the paths you can visit in the system, and therefore you're expecting to see a listing of all paths in that function?

If so, that's not quite how it works. Drupal is extended by way of a hook system, one of those being `hook_menu()`, which allows modules to define menu items and page callbacks.

So in the case of jQuery Update, this is its implementation of `hook_menu()`:

```
function jquery_update_menu() {
  $items['admin/config/development/jquery_update'] = array(
    'title' => 'jQuery update',
    'description' => 'Configure settings related to the jQuery upgrade, the library path and compression.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('jquery_update_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

```

And that's where the jQuery Update admin menu item and link come from.

---
Tags: 7, hooks, configuration
---


title: Translate "Link text" in View

text:
# Question
Title: Translate "Link text" in View
I have the following text/token in one of my field's "Link text" field.

"Download \[file:name\]"

How do I translate "Download"

Here is a screenshot:

https://www.dropbox.com/s/lwquchykaymh20j/Screenshot%202014-05-28%2023.15.14.png

# Answer
If you have the **Locale** module enabled, you can translate the string on the page *admin/config/regional/translate/translate* \- just search for Download and the string should appear in the translatable strings.

In order to translate the string you have to open the actual page once to let drupal register the translatable string.
> 0 votes

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


title: Search field for views

text:
# Question
Title: Search field for views
How do I implement a search filter/field for my view? Lets say I have a view with a list of names/titles and there's a lot of them, so users could use search to filter through?

# Answer
> 1 votes
While creating a filter in a view you can expose the actual field to the use. In case of a title field you would create a filter for the field **Content: Title** and enable the checkbox *Expose this filter for visitors, to allow them change it*.

Screenhot

After saving your view the filter would appear above your view. Depending on your search requirements you can also change the search-operator to several options. In case of a "Live search" on a big list of entries i would prefer to set the view to use *Ajax* in the *Advanced* settings of the view.

---
Tags: 7, search, views
---


# Question
Title: How to change or update select list of field which is already filled with values
How to change or update select list of field which is already filled with values. When I try to remove or edit value the options, I got: "Allowed values list: some values are being removed while currently in use."

# Answer
That's quite a daunting task - in order to keep consistency of existing values already stored in your database you can either change all of the nodes containing the value you want to change or add a new option to the select-field.

Changing a lot of options at once could be done by a views-bulk-operation and the operator *Change value* (not sure, if it's called this way - but it exists ;)).

If i run in such a situation i often write an update\_hook to change all values of the field in the db (do not forget to change revision table also) and change the select values afterwards.
> 1 votes

---
Tags: entities
---


# Question
Title: how to add the radio button intead of checkbox in tableselect drupal 7
How can I add the yes/no radio button instead of check box in the table-select module?

# Answer
As per Adding checkboxes to a table, you need to set `#multiple` on the element:

```
$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);

```
> 1 votes

---
Tags: forms
---


# Question
Title: Exclude nodes present in panel from view pane
I have a panel page where a user selects nodes (using IPE) to be displayed, the page also contains a view pane, which must not contain those same nodes.

How do I get the view to exclude the nodes present in the panel?

# Answer
> 1 votes
We had the same issue on a page with a lots of news and user customizable **Top News** \- we used the module views\_exclude\_previous module and it worked fine for this case.

---
Tags: views, panels
---


# Question
Title: Apache Solr Search, add taxonomy field in search results
I'm really bumping my head on this.

I *simply* need to add tids from a term reference field on nodes returned by a solr search result.

It's a unique term reference.

I looked for the field in solr console and it's 'im\_field\_arbo'.

I followed this and that and came to this :

1.

```
    function MYMODULE_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
      if(isset($entity->field_arbo)) {
        $document->addField('im_field_arbo', $entity->field_arbo['und'][0]['tid']);
      }
    }

```

This doesn't throw back any errors.

2.

Then, to retrieve it, I tried either **hook\_apachesolr\_query\_alter**, **hook\_apachesolr\_query\_prepare** with :

```
    $query->addParam('im', 'im_field_arbo');

```

and **hook\_apachesolr\_modify\_query** with :

```
    $params['im'] .= ',im_field_arbo';

```

---

Still, no trace of my field in my search results.

Any help ? Thx very much.

---

## Update

I think my field is well indexed : `_apachesolr_index_document_build_node` works like a charm.

**Now the question is : "How do I get them back in search results ?"**

# Answer
To show the field you have added to your Solr index you first need to add it to the search result. Add this to template.php

```
function template_preprocess_search_result(&$variables) {
  $variables['im_field_arbo'] = $variables['result']['fields']['im_field_arbo'];
}

```

Then in your `search-result.tpl.php` you can access the field like this:

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

```
> 2 votes

# Answer
Try this,

```
/**
 * Implements hook_apachesolr_process_results().
 */
function mymodule_apachesolr_process_results(&$results) {
  foreach ($results as $key => &$result) {
    $result['foo'] = $result['node']->im_field_arbo;
  }
}

```

Call this variable in you search-result.tpl.php e.g.

```
<?php print $result['foo']; ?>

```

I think this code will work with the combination of:

```
function mymodule_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('fl', 'im_field_arbo');
}

function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type) {
  // I think you should do a foreach here, since you are using multi-valued field.
  foreach ($entity->field_arbo[LANGUAGE_NONE] as $key => $val) {
    $tid = $val['tid'];
    // The 1st letter indicates the data type and the last letter is
    // 'm' for multi-valued.
    $document->addField('im_field_arbo', $tid);
  }
}

```

I hope it helps.
> 0 votes

---
Tags: 7, entities, search
---


title: Use tokens for cck field default value

text:
# Question
Title: Use tokens for cck field default value
Is there any module or code hack to use tokens to set cck field default values ? i have a content type with contact details fieldset, this fieldset have some fields to collect data from current logged in user.

# Answer
Indeed: Field default token.

> This module enables to use tokens as field default values.

See the related core discussion if you're interested.
> 1 votes

---
Tags: 7, nodes, entities, tokens
---


title: Unset fields as required for a Form

text:
# Question
Title: Unset fields as required for a Form
In my drupal-based project, we make a difference between laptop users and tablet users: Laptop users **can skip some fields when registering**, whereas tablet users have to fill in all of them. The trick is easily done by **hiding or showing those fields from the signup form** with jQuery and Modernizr. And I say trick, because it works, despite some of those hidden fields being marked as `required`, they are still allowed to signup without filling on them.

The problem comes when users forget their password and request a link to create a new one. When they get to the screen of *"Enter new password and confirm it"*, users who have initially signed up via laptop (i.e., not filling on some of the `required` fields), cannot continue because they get the error **"Fields X and Y cannot be left blank"**, or sth similar.

I want to **disable these 2 fields from being `required` for Drupal** (not from the signup form, where I have already "hidden" them), but I am not sure how to proceed. Where should I do this?

# Answer
I would suggest, you use **hook\_form\_alter()** and then check for laptop users. If laptop users are on form then make **#required** false for these two fields.

**Example:**

```
$form['title']['#required'] = FALSE;

```

**Note:** FYI Avoid using *unset()* in such type of scenario either set the *#access* property or *#required* property to FALSE. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.
> 0 votes

---
Tags: forms
---


# Question
Title: How to make user profiles of specific role as public in drupal 7?
I am working on a project and the problem I am facing is,

There are 2 user roles Doctor and Patient. What I want to accomplish is profile of users with role of "Doctor" is accessible by all including anonymous and profile of users with role "Patient" is accessible by user himself and all the users with role of "Doctor". Rest no one can access the profile of "Patient" role.

Any help is much appreciated. Thanks in advance.

# Answer
You are looking for Profile2 module.

> * With profile2 user account settings and user profiles are conceptually different things, e.g. with the "Profile pages" module enabled users get two separate menu links "My account" and "My profile".
> * Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
> * **Profile2 supports private profile fields, which are only shown to the user owning the profile and to administrators**

Check out this Demo video.
> 1 votes

---
Tags: users
---


# Question
Title: How can I show the root taxonomy term in a view field in Drupal 7?
I have a **view** with a taxonomy term field called Location in Drupal 7 and I want to show the **first / root level of the term hierarchy** in each view item field, aka the Country level.

My Location field in **not mandatory**, so I also want to show items with no Location. Meaning that I should mark all my term relationships as **not required**.

I have tried using **relationship** to the taxonomy term, and to the parent of the taxonomy term. And then a parent filter on the parent of the taxonomy term with value = empty. By this way I managed to show the root level of my taxonomy field only, but not items with no Location. As trying to make my relationship on taxonomy term not required, throws an exception. I guess this is due to the fact that then it tries to find the parent of the term and if it the term is empty, it throws the exception.

Any suggestions on how could I show the root term (Country) and, at the same time, items with no Location?

# Answer
> 0 votes
In the 'Fields' section of the view add your taxonomy field (Location). Select the Formatter that you want and then in the settings of the field, in the fieldset 'Multiple field settings' change the 'Display' option from 'all' to '1'.

Enjoy

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


# Question
Title: I want to send the username of the person submitting the form along with form data
I wanted to know how to get the username for whoever submits a form so I can pass it to `db_insert` along with form data.

Sorry, I'm new to Drupal and php. I'm just try to learn.

Yes, it is custom code. Here is the form. I have based it on tutorials I've found so far.

```
function input_simple_form($form, &$form_submit) {

$form['color'] = array(
    '#title' => t('color:'),
    '#type' => 'textfield',
    '#required' => TRUE,
            '#description' => t('What is your favorite color?'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div><br>',
    );
$form['TV_Show'] = array(
    '#title' => t('TV_Show:'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('What is favorite TV show?'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div><br>',
    );

$form['input'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('input_simple_form_submit'),
    );

return $form;
}

```

Then I send the data to database:

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

// Display a message upon successful submission.
drupal_set_message(t("Added @color @TV_Show", array('@color' => $form_state['values']['color'], '@Name' => $form_state['values']['TV_Show'])));
$id = db_insert("TestForm")
->fields(array(
    'color' => $form_state['values']['color'],
    'TV_Show' => $form_state['values']['TV_Show'],
    'SubmitBy' => $user->name,
    ))
->execute();
}

```

I'm not sure how to pass `$user` to the submit function. Hope that helps.

# Answer
> 2 votes
You *don't* pass `$user` to the submit function.

Instead, you add a declaration of the global `$user` object to the start of the submit function to bring it into scope. Like this:

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

  // Display a message upon successful submission.
  drupal_set_message(t("Added @color @TV_Show", array(
    '@color' => $form_state['values']['color'],
    '@Name' => $form_state['values']['TV_Show'],
  )));
  $id = db_insert("TestForm")
    ->fields(array(
      'color' => $form_state['values']['color'],
      'TV_Show' => $form_state['values']['TV_Show'],
      'SubmitBy' => $user->name,
    ))
    ->execute();
}

```

# Answer
> 1 votes
You can always get the user object using global keyword:

```
global $user;
$uid = $user->uid;
$username = $user->name;

```

# Answer
> 0 votes
In your custom code, you need to use

```
global $user;
$username = $user->name;

```

Regards,

K.

---
Tags: forms
---


# Question
Title: Is it possible to have different frontpage page--front.tpl.php based on user´s device (mobile/desktop)?
I am using the Detect\_Mobile module in order to detect whether the user is coming from a mobile/tablet device or not. I would not like to use other modules as Mobile switch or Mobile tools because those are too big modules for my needs and also have cache bugs that appear when visiting again the frontpage, anyway that is not the point now.

I already detect the user´s device by using the Detect\_Mobile library and module and I know it works because when I access the site by mobile I am redirecting the site to a different website so as testing I am using the next code in my `template.php` from my theme:

```
    <?php

    include 'sites/all/libraries/Mobile_Detect/Mobile_Detect.php';
    $detect = new Mobile_Detect();

    if (drupal_is_front_page()) {

     $GLOBALS['conf']['cache'] = FALSE; /*otherwise 2nd time shows desktop frontpage on mobile*/

        if ($detect->isMobile() or $detect->isTablet()) {
            header("Location: "); /*for testing goal*/
        exit;
       }
    }

    ?>

```

So the previous code works because the site gets redirected to another site address when the user´s access is by mobile/tablet but the point is that I don't want to redirect the site to another link like this: header("Location: /mobile.php");
What I want is to have 2 frontpages templates loaded based on user´s device:

`page--front.tpl.php` =\> normal(desktop) frontpage and loaded by default `page--frontmob.tpl.php` =\> mobile/tablet frontpage and loaded when user´s device is mobile/tablet

Then I dont know if what I want is possible to do in Drupal but after reading some other examples like:

https://stackoverflow.com/questions/8840051/how-to-redirect-mobile-visitors-from-drupal-site-to-mobile-site-on-other-domain

> Your best bet would be to write a small module and implement hook\_init() which happens before the page is even built.
>
> function MYMODULE\_init() { include("PATH/TO/Mobile\_Detect.php");
>
> $detect = new Mobile\_Detect(); if ($detect-\>isMobile()) { header('Location: http://newdomain.com/'); drupal\_exit(); } }

And also this: http://example.com/serving-different-pagetplphp-different-browser-types-ie-ie6-your-drupal-theme

```
<?php
include('browser_detection.php');
if ((browser_detection('browser') == 'ie' ) &&
            (browser_detection('number') >= 5 ) &&
            (browser_detection('number') < 7  )) {
  include "page-ie.tpl.php";
  return;
} else {
  include "page-normal.tpl.php";
  return;
}
?>

```

Then I came out with the following code in my template.php of my theme:

```
<?php

        include 'sites/all/libraries/Mobile_Detect/Mobile_Detect.php';
        $detect = new Mobile_Detect();

        if (drupal_is_front_page()) {

         $GLOBALS['conf']['cache'] = FALSE; /*otherwise 2nd time shows desktop frontpage on mobile*/

            if ($detect->isMobile() or $detect->isTablet()) {
                include 'sites/all/themes/mytheme/page--frontmob.tpl.php';
            return;
        } else {
            include 'sites/all/themes/mytheme/page--front.tpl.php';
            return;
            }
        }

        ?>

```

But what the previous code does is calling both of the frontpages templates do both are showing on frontpage when loading the site: page--frontmob.tpl.php and page--front.tpl.php without caring the if statement about devices... so it feels like one page is embeding another page.... and still shows the next errors:

```
Notice: Undefined variable: logo in include() (line 14 of /sites/all/themes/mytheme/page--front.tpl.php).
Notice: Undefined variable: page in include() (line 26 of /sites/all/themes/myclassiclive/page--front.tpl.php).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in theme_get_registry() (line 277 of /includes/theme.inc).

```

So please help!!! I really have tried already many times to solve this problem but without success... I am new in Drupal.. so I guess the code I am using has something wrong...

I would appreciate so much for your soon help to fix that code or either use it in a different way... REMEMBER I am using Mobile\_Detect(working fine) and REMEMBER I have not a different THEME for mobile that´s why I am not using Mobile switch or other similar modules but I have just 2 different frontpages templates on my theme based on user´s device... so:

```
mytheme/page--front.tpl.php
mytheme/page--frontmob.tpl.php

```

Rest of the sites pages works as desktop based on `page.tpl.php`.

Or should I do a small module(using hook\_boot/hook\_init) in order to be able to replace `mytheme/page--front.tpl.php` for `mytheme/page--frontmob.tpl.php` when detecting the mobile/tablet device? as here was suggested for somebody else with a little similar situation?

I there is NO a solution for this then I guess I have to use the redirection option with `header("Location: http://www.example.com/mobile.php");`

# Answer
This is possible. You can use `template_preprocess_page()`. If you have the Devel module enabled you can `dpm($variables)` in the hook. Within the variables array is the `theme_hook_suggestions` element with a bunch of values which loads the template files upon output. So within `template_preprocess_page` you can add your device detection snippet and modify the element to load your template files. This article explains how to work with template suggestions and manipulate them to your needs.
> 2 votes

# Answer
You can use the Theme Key module. You can achieve features like:

* individually-styled channels
* a front-page / "splash" screen
* a date/time-selected Christmas theme
* **mobile themes for different auto-detected mobile devices**
* special themes for "limited" or "old" browsers
* content, user, or role -specific themes
* indicating your environment (production, staging, testing, sandbox, … )
* testing your redesign safely on a live server
* ...

ThemeKey should play well with internal and external page caches, like Boost or Varnish, even for anonymous users.

We use it in my company for a high-traffic site and works ok.

In your case, you can create a subtheme that is almost equal to the main theme and make your customizations there.
> 0 votes

---
Tags: theming, hooks
---