# Question
Title: drupal 7: hook intercept url file requests located within the "Public File System Path"
For Drupal 7 when going to: admin/config/media/file-system you can set up both a Public and Private File System Path.

Is it possible for files that are within the "Public File System Path" that when they are directly accessed via url that a hook could intercept that file request and decide based on the users role whether to allow or send them to a goto like `(drupal_goto('user', array('query' => array('destination' => $pre_alias)));)`

I know that the `hook_file_download` can intercept file requests for private files but if possible I don't want to have to spend this extra time setting up a private area.

# Answer
> 3 votes
Not as standard, no.

Drupal's .htaccess file has these conditions in it for the main index.php rewrite:

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

```

Which basically means requests for physical, existing files are passed through without Drupal's involvement.

To change that behaviour you'd need to override those conditions, either in the root .htaccess or one underneath the files folder itself. For nginx you'd be doing basically the same thing, except the vhost's config file would be the place for the rewrite logic.

Then you'd need to implement a menu callback at the path `files` which dealt with all incoming requests for files. That callback would invoke a custom hook, which your module(s) would consume to make decisions about whether or not that particular file should be downloadable. If so, you'd invoke a file pass through, if not a 403.

Long story short, it's not a good idea - you'll put a large amount more strain on your server with all those extra bootstraps (every CSS file, every image, every everything). What you're describing *is* the private file system, it would be much more palatable to use that.

The public file system is designed to be just that - public.

---
Tags: files
---


# Question
Title: Are there any modules that can export and import nodes while preserving node id's?
Our website uses VBO + Views Admin screen for the `admin/people` screen. Today one of the user admins deleted some old user accounts, by checking the checkbox next to the names and selecting the "Delete" option from the Actions dropdown. What he didn't know (+ I didn't know) was that by using the "Delete" option he also inadvertently deleted all the content created by those users as well.

I've got a backup of all the nodes that have been deleted, however I'm at a bit of a loss on what's the best option to restore these. The site has 10+ content types, and loads of custom fields (field\_x\_revision + field\_x\_data tables!! for each field). I need to preserve those node ID's. I'm going to be doing this locally and the once I've got a completely merged database I'm going to put it back on the live site.

Are there any drupal modules that can export nodes and also import them (and preserve the old node id's)?

# Answer
If your backup contains the previously existing users, you could try to recreate your production site locally... Here are the steps I would follow (never tested though):

* install a local drupal site with your backup (files should be restored as well) in the production site, via VBO
* put your production site in maintenance mode
* target all the new / updated nodes since the incident
* export them via Node Export
* reimport them locally (the nids should be preserved thanks to NodeExport and UUID)
* reinstall your local db in production
> 1 votes

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


# Question
Title: How to show warning and list of related content
I'm working with Drupal and I wanted to show users that the included URL in post has already been submitted when they click preview

# Answer
> 1 votes
Use the Unique field module:

> This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.

---
Tags: nodes, entities
---


# Question
Title: Does aggregating JS/CSS interfere with my drupal_add_js()?
I want to use `drupal_add_js` and `drupal_add_css` on a per-page basis so I have added a 'scripts' text field to my basic content type and have set the Format Type to PHP.

It works beautifully until I turn js/css aggregation back on; then, none of the files I specified are loaded. Why?

1. Because Drupal is still using the previously aggregated files (despite me flushing the cache many times).
2. Because of some more sinister issue that will prevent me from adding my CSS/JavaScript in this manner.

I see other people doing the same thing here: https://drupal.org/node/290982.

# Answer
> 2 votes
Yes, drupal will definitely miss your custom JS scripts in it's js aggregation build phase, if you're loading JS on different pages. This is because by the time a user (or you) hits the other pages, the aggregated js file has already run previously, and created the cached JS file it thinks is all it needs. It uses this cache file until the cache is cleared or the crontab is run.

A couple of options are to either:

1. try using the drupal\_add\_html\_head() function to add the js when ever you want, or,
2. write some js to detect what library is needed (perhaps based on a data attribute element in the markup), and then conditionally load the other js via the getScript method.

Good luck.

# Answer
> 0 votes
Try AdvAgg. It has some useful things that help to understand what is going on. In this case I would add ?advagg-debug=1 to the end of the url and then look in watchdog for the corresponding advagg\_debug entry.

---
Tags: 7, css-js-aggregation
---


# Question
Title: unable to get custom service to return result using services module
I'm learning about web services and implementing it in drupal 6 and am trying to use Services module with its REST server for implementing a web service to add a user.

Since there is an existing functionality for all CRUD operation for users, I am trying to implement my custom code to register a user by using a HTTP POST of the respective data using REST as a part of the challenge. I implemented custom user resource in my module (awesomeness.module) and got it to show up in the list of resources with the respective operation (Create).

```
/**
 * Implements hook_services_resources().
 */
function awesomeness_services_resources() {
  return array(
    'awesome_registrant' => array(
      'operations' => array(
        'create' => array(
          'file' => array('type' => 'inc', 'module' => 'awesomeness'),
          'callback' => '_create_registrant_from_awesomeness',
          'help' => 'Creates or updates user from the
                     json data initiated by the Awesomeness request.',
          'access callback' => '_create_registrant_from_awesomeness_permissions',
          'access arguments' => array('dummy'),
          'access callback file' => array('type' => 'inc', 'module' => 'awesomeness'),
          'args' => array(
            array(
              'name' => 'user_data',
              'type' => 'string',
              'description' => 'The json data of User posted
                                by Awesomeness to register information.',
              'optional' => FALSE,
              'source' => 'data',
            ),
          ),
        ),
      ),
    ),
  );
}

```

The corresponding callbacks for the request and access in awesomeness.inc are as below

```
/**
 * Callback function to create or registrant from the web service request
 */
function _create_registrant_from_awesomeness($user_data) {
  watchdog('AwesomeWebservice', "I am called");
  $user_info = var_export($user_data, TRUE);
  watchdog('AwesomeWebservice', $user_info);
  return "Is called";
}

/**
 * Access callback for the registration Web service.
 */
function _create_registrant_from_awesomeness_permissions($access = TRUE) {
  // any logic on access restriction goes here, currently
  // setting true to check that calls can be made as an anonymous user
  return TRUE;
}

```

I created an endpoint and enabled Create for `awesome_registrant` and made the POST request with POSTER add-on for firefox set the Content type as `application/x-www-form-urlencoded` and the following json data in content body `{"username":"awesomeuser@kungfupandafan.com","password":"epicawesomeness"}`.

However I merely get a response code of 200 and nothing more where I expect the callback to return "Is called".

Enabling the debug mode shows only the Server info object but not the controller or the data about the return value unlike the core services like node retrieve.

Also for sake of clarification application/x-www-form-urlencoded is enabled for the REST web server. Any help on what I might have missed or where I have erred would be greatly appreciated.

# Answer
> 0 votes
Finally figured it out and boy was it bad. The endpoint I was supposed to hit was `http://mysite.com/myawesomeendpoint/awesomeregistrant` but instead I hit `http://mysite.com/myawesomeendpoint`. Hope this helps some one.

---
Tags: 6, services
---


# Question
Title: Search and Replace Scanner not publishing nodes after search?
I'm using the handy Search and Replace Scanner module to do a basic sitewide search. It's working well... except that it's not publishing the nodes after the it does the replace. It's making new unpublished revisions. This is quite annoying because then I have to go to all 50+ nodes that were changed and publish them all.

Is there any way around this? Ideally, I'd like the nodes to just be published after the replace.

# Answer
It's a node setup thing. Adjusted Workflow/Revision settings to auto-publish, and we're all good.
> 1 votes

---
Tags: search, nodes
---


title: Field Collection Adding Values

text:
# Question
Title: Field Collection Adding Values
I'm confused by the field\_collection API. I created a Field Collection and attached it to a node (in the GUI) but I can't figure out how to code an update/addition to the field collection. This is my scenario:

I have a node (request) that has product information and quantities. When users go to a product page they see a link to "Add to Request". This link should add the product (nid) to the node request. The difficulty lies in the fact that I need quantity information as well, hence the Field Collection. I added a quantities field and grouped it with the product field.

**Node Type: request
Request ID: $requestid
Product ID: $productid
Field Collection = field\_request\_collection (Unlimited values)
Field Collection Field = field\_products (Entity Reference, Max 1)
Field Collection Field = field\_product\_quantities (Integer, Max 1, Default 1)
**

My function looks like this (the values for $requestid and $productid are passed in the URL of the link: /my\_request/5/12):

```
function _my_module_request_update($requestid,$productid) {
$nload = node_load($requestid);
$field_collection_item_value = $nload->field_request_collection[LANGUAGE_NONE][0]['value'];
$field_collection_item = entity_load('field_collection_item', array($field_collection_item_value));
$field_collection_item->field_products[LANGUAGE_NONE][0]['value'] = intval($productid);
$field_collection_item->save();
}

```

The error I'm getting with the above code is:

> PHP Fatal error: Call to a member function `save()` on a non-object

Keep in mind that I'm attempting to ADD Field Collection values NOT replace them. Please help, thanks!

# Answer
> 4 votes
Something like this ought to do the trick:

```
$nload = node_load($requestid);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_request_collection'));
$field_collection_item->setHostEntity('node', $nload);
$field_collection_item->field_products[LANGUAGE_NONE][0]['target_id'] = intval($productid);
$field_collection_item->save();

$nload->field_request_collection[LANGUAGE_NONE][]['value'] = $field_collection_item->item_id;

```

---
Tags: entities
---


# Question
Title: Drupal 7: pull out just the Twitter job as its own Cron job so that we could run it every minute
Drupal 7: We are using the twitter module and it adds a job to Cron so that every time Cron is run it checks Twitter for the configured tweeter account and downloads to the Drupal Twitter table any new tweets since that last time Cron was run. Our customer wants to have close to real-time display of these tweets and we did not want to have Cron run every minute since we are concerned about the performance hit so instead we run it every 5 minutes.

Is their any way to pull out just the Twitter job as its own Cron job so that we could run it every minute which might not impact performance?

# Answer
There are a couple of different cron managers available, personally I use Elysia Cron

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

But there's also Ultimate Cron which I understand is very good too

> Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

Either of those will let you isolate the Twitter cron job to be run more frequently than the normal one.
> 1 votes

# Answer
For improved control over the granularity of cron jobs, you might look at Elysia Cron which would allow you to vary the scheduling on a task by task basis.

There is also Cron Control if you are in a clustered environment which would allow you to dedicate a particular server for cron jobs, taking the load off the other servers.
> 1 votes

---
Tags: cron, social-network
---


# Question
Title: Display webservice response in a paged table
I have data I am receiving from a webservice call that I would like to display in a paged Drupal table. How can I do this? Can I use theme('table') and attach a pager to it somehow?

# Answer
You need a generic array pager for paging data that isn't available in your Drupal database. There's a community documentation page available providing information about the subject.

From the page Paging non-SQL data:

With the following function, you can use the Drupal core pager with any array with only two lines of code:

```

/**
 * An generic array pager for Drupal.
 * For Drupal 5 and 6, the default limit is 10. For Drupal 7 it is 9.
 */
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

```

The usage is as simple as:

```

  $output = '';
  $tree = taxonomy_get_tree($vocab->vid);
  $tree = pager_array_splice($tree, 5);
  // Do something with the 5 terms
  $output .= theme('pager', array('quantity' => 5));

```
> 1 votes

# Answer
Why not use Views to pull out the fields and use the table display? The pager is automatically built in.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to disable a block on a certain view?
I want to disable two blocks for a certain view. I have tried "Show block on specific pages \>\> All pages except those listed" using the machine name and the view URL with no luck; I tried Drupal Context still no luck. May you please assist?

I have looked at Exclude a block from specific parts of the website with the Context module, but the answers there didn't help.

These are the details for the view I am using.

# Answer
> 1 votes
If the view path is `/all-albums` then try entering `all-albums` in the block under *Show block on specific pages: All pages except those listed*, not the full url or the machine name.

# Answer
> 1 votes
You do not have to use context menu for this thing.It comes out of the box Here it goes which may help you

Use "All pages except those listed" and put the view url let say you do not want to show it on view page with url as abc and other view page with url as pqr ,so after selecting " All pages except those listed " radio option in the text area below it out the both views page url as follows

```
abc
pqr

```

try clearing the cache,though it should not be the reason its not working.

---
Tags: views, blocks
---


# Question
Title: How can I show contextual links on my node's full content view mode?
I need to be able to display my contextual links in the node full content view mode. How can I achieve this? Maybe something in my node.tpl?

# Answer
if you want to show contextual link on a node view try out this code on your custom module file.

```
function mymodulename_node_view_alter(&$build) {
  $node = $build['#node'];
  if (!empty($node->nid)) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }
}

```
> 1 votes

---
Tags: navigation
---


# Question
Title: Display (and pass) a custom user field in php
In Drupal 7, I've added some custom fields in Account Settings\>Manage Fields. One of them is field\_company\_name. I'd like to be able to display this field and pass it to an external php function.

I can easily display the $user fields for the current user. For example:

```
<?php
global $user;
echo 'Current User: ';
print_r($user->name);
echo '<br/>User ID: ';
print_r($user->uid);
echo '<br/>Email Address: ';
print_r($user->mail);
echo '<br/>'
?>

```

How to I get at field\_company\_name for this same user?

# Answer
You need to load the user object up fully with `user_load()`, so the fields get attached:

```
$account = user_load($GLOBALS['user']->uid);

```

Then use `field_get_items()` to extract the field data:

```
if ($items = field_get_items('user', $account, 'field_company_name')) {
  $company_name = $items[0]['value'];
}

```
> 2 votes

---
Tags: entities
---


# Question
Title: How to detect if "Show end date" is checked?
Trying to find a way to get the value of the checkbox "Show end date" on a date field on drupal 7.

Is it stored somewhere in the database? Can't find it. Its definitely not in the $node object.

Any ideas?

# Answer
It's stored against the field settings in the `field_config` table. You can get access to it through the API with `field_info_field()`

```
$field_info = field_info_field('field_name');
$to_date_setting = $field_info['settings']['todate']; // optional, required, etc

```
> 0 votes

---
Tags: 7, entities, datetime
---


# Question
Title: Example of how to configure contextual filters with taxonomy using php arguments to display a view of commerce products?
Currently I am trying to configure view to display a grid of commerce products that matches a specific taxonomy term. This term is a **term reference field** in the product display. I also have a **view reference field** in the product display. Right now I am trying to pass that taxonomy term into the referenced view as an argument.

I am having the issue of grabbing the 2nd argument path in views. I'm using the PHP option of the context filter.

As you can see from the sql statement it selects only the 1st argument, its suppose to select the 2nd one as seen in the contextual filter options. I'm not sure if its a bug in itself or i have something wrong with my code.

screenshot of view: http://prntscr.com/18qy2f

screenshot of contextual: http://prntscr.com/18rn4v

---

when it is working it should look like this: http://prntscr.com/18rs0i

In this scenario, i made the first argument as 3ds, which gives me the output i want. But on the top scenario where I want the 2nd argument, it still grabs only the 1st argument.

This is what it should look when it works. It takes the 1st argument. http://img844.imageshack.us/img844/4830/lgt7424d.png

---

it also seems that the TITLE doesnt recognize %2 or %3. see here: http://prntscr.com/18rx3i

# Answer
> 0 votes
On the first run, I was taking the approach of fetching the URL path that contained the related taxonomy data using the contextual filter's path argument selector.

After a good number of hours, I took a completely different approach to solve this problem. I actually figured out how to load the taxonomy field data into the contextual filter via php using the following code:

It will now grab any taxonomy data on the page if it exists. You will need to change it to your field settings.

```
return menu_get_object()->field_EXAMPLE_vocabulary[und][0][tid];

```

You can view my views configuration setup here: http://prntscr.com/18snhm

Looks like this once implemented:

http://img703.imageshack.us/img703/3733/lgt1356.png

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


# Question
Title: How do I access field variables directly in Drupal 7 without having to drill down into a node array?
I have a view reference field and have some php code in the view where it grabs the taxonomy ID of the page its currently on. Currently I am grabbing the TID via

```
menu_get_object()->field_device_type_vocabulary[und][0][tid];

```

I know you can access the fields directly without having to do that, but forgot how that was done.

# Answer
There are two main methods:

1. Procedural, using `field_get_items()`, e.g.

```
$node = menu_get_object();
if ($items = field_get_items('node', $node, 'field_device_type_vocabulary')) {
  $tid = $items[0]['tid'];
}

```
2. Objected oriented, using an `EntityMetadataWrapper`, e.g.

```
$node = menu_get_object();
$wrapper = entity_metadata_wrapper('node', $node);
$tid = $wrapper->field_device_type_vocabulary[0]->tid->value();

```
> 2 votes

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


# Question
Title: How do I restrict a user to visit a particular page only certain no of times?
How do I restrict a user (role) to visit a particular page only certain number of of times? I am using Drupal 6. It is for premium content. I just want to give 5 premium content views for free.

# Answer
If you want to restrict a casual user to only 5 views of ANY premium content, versus restricting his/her looking at the same piece of content 5 times, you might want to consider storing this information in the user's data field.

In broad strokes, you could in a custom module's nodeapi hook, do something like this:

```
if op is view
  if type is premium
    if user doesn't have a premium role assigned
      load the full user object
      if s/he has seen 5 pieces of content
        drupal_goto signup page
      else
        increment count of free page views
        save user
        if this is the 5th view
          tell user this is the last freebie
        fi
      fi
    fi
  fi
fi

```

Look into user\_save() and user\_load() for how to save and load serialized information into and from the data field/column of the user. Also look into hook\_nodeapi() for how to intercept these views.

Also caveats you will have to be aware of is cron and search, you probably don't want them to be limited by this, and that drupal\_goto in there might/will reek havoc if it isn't trapped for these purposes.
> 0 votes

---
Tags: 6, nodes
---


title: Views exposed filter are cached

text:
# Question
Title: Views exposed filter are cached
after performing a search using Views exposed filter,the filter is cached and even I change that I get the same as previously results.How can I solve that? thanks

# Answer
> 2 votes
make sure these settings are set:

remember last selection & caching

---
Tags: views
---


# Question
Title: How to list nodes and have them grouped by Day / Week / Month?
I have an event content type that has a date field (the time the event will take place)

I like to list these events and have them grouped by Day / Week / Month
I dislike the calendar layout, it is too messy

Any ideas are welcome

I attached this mockup of what i'm looking for. The person interested in the event's section should be able to filter the events by day/week/month

*Extra question :* Would it be possible to have a 'next weekend' filter (relative to the time the person is visiting the website) ?

# Answer
What you need to do is create a custom PHP field and manually code out the group by conditions as you have set there. I had the same issue I documented on my blog here: http://drupul.com/content/views-multiple-group-recipe-drupal-7

This is the code I used in my PHP field:

```
<?php
global $prev_month;
global $month;

if($prev_month != date('F Y', strtotime($data->field_field_date_2[0]['raw']['value'])))
{
  $month = '<h4>'. date('F Y', strtotime($data->field_field_date_2[0]['raw']['value'])) .'</h4>';
  $prev_month = date('F Y', strtotime($data->field_field_date_2[0]['raw']['value']));
}
else
{ $month = ''; }

print($month .'<h5>'. date('M d', strtotime($data->field_field_date_2[0]['raw']['value'])) .'</h5>');
?>

```

You will of course have to modify it to your setup, but its very similar to the setup you need as I needed it to be grouped by month then week and then day.
> 1 votes

---
Tags: datetime
---


title: Drupal 8 HTML markup and semantics

text:
# Question
Title: Drupal 8 HTML markup and semantics
When building a bespoke site a pet hate is that you start with a front-end layout that is semantically sound and robust, but when you try and create said layout as a theme in Drupal, by default the system adds `<div>` markup around whatever node, field or general piece of information it can find.

The result is that I usually begin with Mothership as a base theme to reduce the noise of excess markup.

Will Drupal 8 (both core modules and shipped themes) adopt cleaner HTML semantics? If so, how might the new front end HTML compare to its Drupal 7 predecessor?

HTML5 is an obvious assumption. The game is no longer "wrap it in a div" as HTML 5 empowers front end developers to a wealth of possible tags in order to best convey meaning (e.g. aside, header, navigation). How will Drupal change to allow this new level of semantics choice to be controlled by developers?

# Answer
Why should it change (drastically) -- it embraces a base of HTML5 markup; anything beyond that essentially becomes business need, accessibility requirements or simply put designer preference on what *clean and simple* means to them.

### From HTML5 Initiative page

> We want to ensure we're spending our time implementing features that will directly benefit Drupal's user base the most. As part of this initiative we'll focus mostly on:
>
> * Adding support for the new form elements to Drupal's Form API.
> * Adding new semantic elements in core templates in an appropriate way.
> * Adding ARIA roles to markup to improve accessibility.
> * Simplifying style and script elements.
> * Ensuring input filters and functions accept HTML5 elements.

---

Does the above goals mean that Drupal 8 HTML markup will be as lean turning on Fences in Drupal 7 and nuking all built-in markup? No, will the base markup be too complex, hardly. It will be designed to meet most peoples needs.
> 5 votes

---
Tags: theming, 8
---


title: arbitrary order of nodequeues in a view

text:
# Question
Title: arbitrary order of nodequeues in a view
What is the best way to arbitrary order nodequeues in a view?

* Drupal 6.26
* Nodequeue 2.11
* Views 2.16

# Answer
> 0 votes
ended up using subqueues, was not quite what I wanted.

---
Tags: views, nodes
---


# Question
Title: Is there a view for top selling products, including product kits?
I'm looking for a view to list top selling Ubercart 3 products and product kits. It would be a BIG plus if the view can include an image field and a taxonomy field.

I have checked this articles but didn't get what I'm looking for

http://drupal.org/node/1339910

Ubercart most selling product in drupal 7

Thanks

# Answer
> 0 votes
easyrec for ubercart module provides the functionality for most selling products(**most bought items**) and it also provide the following options as blocks.

Available Blocks

```
easyrec: other users also bought
easyrec: other users also viewed
easyrec: recommendations for user
easyrec: most bought items
easyrec: most viewed items

```

> To use the "easyrec for ubercart" module a shop owner needs access to an easyrec server. It's possible to register a free easyrec account at http://easyrec.org/ if the owner cannot host his/her own. After creating an account on the easyrec server and a 'tenant' account for the specific shop, the shop owner just copies the tenantId and apiKey into the drupal module's administration interface to enable recommendations for the ubercart shop.

---
Tags: views, ubercart
---


title: Url mapping from custom CMS to Drupal

text:
# Question
Title: Url mapping from custom CMS to Drupal
We migrated a site from custom CMS to Drupal. The content has been migrated successfully, but there is a problem with URL mapping.

In old site the URLs were like domain.com/artists/Artist\_ID/Artist\_Name (e.g. domain.com/artists/5/picasso), where the URL would work without the last argument part (picasso).

With the Drupal site all URLs use domain.com/artists/Artist\_ID as format (e.g. domain.com/artists/5).

They have shared the old site's links on social media where URLs are like domain.com/artists/5/fabien-m%25C3%25A9relle which used to work fine in the old site **because last part didn't matter**. The same URLs do not work on the Drupal site.

So can I make Drupal ignore the last part of the URL?

# Answer
You can use Apache's `mod_rewrite` to map all the old URLs shared on social media sites into appropriate new ones, including ignoring the latter part. However, Drupal 7 have a quirk. You need to rewrite to *unclean* URLs for it to work.

So first, turn off clean URLs (which also means turning off *PathAuto*) on your site. Then look up one of your artist's pages and figure out what the real URL is. Let's say that for artist 5 (Fabien Mérelle), it is:

```
domain.com/?q=taxonomy/term/5

```

Now you should be able to insert the following rewriterule:

```
RewriteRule ^artists/([0-9]+)/.*$ ?q=taxonomy/term/$1

```

(You must of course change the target to whatever your test showed the true query string to be.)

The above rule will change `artists/5/fabien-m%25C3%25A9relle` into `?q=taxonomy/term/5`.

Verify that that the rule "works" (i.e. that the URL is really rewritten). Then you should be able to turn clean URLs and PathAuto back on, and it should still work.

The rule consists of two parts. The first (`^artists/([0-9]+)/.*$`) is the pattern to look for, the second (`?q=taxonomy/term/$1`) is the target. They're separated by a single space.

The `^` in the pattern indicate the start of the local path, so it looks for a pattern starting with `artists/` followed by a number (`[0-9+]`) followed by a slash (`/`) followed by anything (`.*`). The final `$` in the pattern is just a marker for the end of the local path. The parentheses around the number stuffs the number into the variable `$1`. The target simply consists of the static string `?q=taxonomy/term/`, followed by the value of the `$1` variable.

Note: You must place the line with the rewriterule inside the `.htaccess` file for the site, inside the block that starts with:

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

```
> 2 votes

---
Tags: 7, uri, .htaccess
---


# Question
Title: Using select list with Views exposed filter when it is a custom schema through hook_views_data
I need to build a page in Panels that is composed of Views displays. The page that this will make will function as a kind of workstation for a staff member displaying bespoke information about readership details, demographics, products chosen etc. etc.

The problem is that I've inherited this project and the previous developer was hard-coding things, avoiding the Drupal API and trying to create his own CMS to handle this complex readership-type subscription system. I now have to make this something that will play nicely with Drupal rather than starting again due to time constraints.

I've used hook\_views\_data to expose his custom tables but because it seems to be data unmanaged by Drupal (i.e. he used nothing like nodes/ entities etc.) I don't think I'm able to exploit the node/custom field/select (https://drupal.org/node/391528) workaround I'm not sure of what I should start looking at.

Please do offer suggestions (possibly even on the wider context if it's relevant)

# Answer
> 1 votes
Unfortunately for me the project is too far gone to create the underlying design with entities, which seems to be the only way that I'm going to achieve that, so instead I am going to be using AJAX like forms which hopefully (in time) will output into Views (to save time and hopefully provide some flexibility). So for now I'm building Panels with blocks that I'm creating programmatically and then using `drupal_get_form('mymodule_mainform')` to add the content of those blocks with forms designed in different functions in my modules.

For that I'm using the Example module's 'block\_example' module (block\_example.module code pasted at the bottom here - find and replace 'block\_example' with your module name if you want to paste it straight into your own .module file, remember though that you can't duplicate hooks, so copy the contents into any pre-existing functions or hooks with the same name).

To help out other people I've included the links that helped me here (may you have better luck!) "joshaust.in"'s .pdf was a brilliant explanation...

For conceptual understanding: http://joshaust.in/wp-content/uploads/2012/06/Entities-and-Bundles-in-Drupal-7.pdf

http://joshaust.in/2012/06/entities-and-bundles-in-drupal-7/

For attaching fields to your entity programmatically: How to attach a field to an entity programmatically?

For programmatically creating your entities: http://www.phase2technology.com/blog/programmatically-creating-entities/

http://www.trellon.com/content/blog/creating-own-entities-entity-api

# block\_example.module

```
/**
 * Implements hook_menu().
 *
 * Provides a default page to explain what this module does.
 */
function block_example_menu() {
  $items['examples/block_example'] = array(
    'page callback' => 'block_example_page',
    'access callback' => TRUE,
    'title' => 'Block Example',
  );
  return $items;
}

/**
 * Simple page function to explain what the block example is about.
 */
function block_example_page() {
  $page = array(
    '#type' => 'markup',
    '#markup' => t('The Block Example provides two sample blocks which demonstrate the various block APIs.
            To experiment with the blocks, enable and configure them on <a href="@url">the block admin page</a>.', array('@url' => url('admin/structure/block'))),
  );
  return $page;
}
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function block_example_block_info() {
  // This hook returns an array, each component of which is an array of block
  // information. The array keys are the 'delta' values used in other block
  // hooks.

  // The required block information is a block description, which is shown
  // to the site administrator in the list of possible blocks. You can also
  // provide initial settings for block weight, status, etc.

  // Many options are defined in hook_block_info():
  $blocks['example_configurable_text'] = array(
    // info: The name of the block.
    'info' => t('Example: configurable text string'),
    // Block caching options (per role, per user, etc.)
    'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );

  // This sample shows how to provide default settings. In this case we'll
  // enable the block in the first sidebar and make it visible only on
  // 'node/*' pages. See the hook_block_info() documentation for these.
  $blocks['example_empty'] = array(
    'info' => t('Example: empty block'),
    'status' => TRUE,
    'region' => 'sidebar_first',  // Not usually provided.
    'visibility' => BLOCK_VISIBILITY_LISTED,  // Not usually provided.
    'pages' => 'node/*', // Not usually provided here.
  );

  $blocks['example_uppercase'] = array(
    // info: The name of the block.
    'info' => t('Example: uppercase this please'),
    'status' => TRUE,
    'region' => 'sidebar_first',  // Not usually provided.
  );

  return $blocks;
}

/**
 * Implements hook_block_configure().
 *
 * This hook declares configuration options for blocks provided by this module.
 */
function block_example_block_configure($delta = '') {
  // The $delta parameter tells us which block is being configured.
  // In this example, we'll allow the administrator to customize
  // the text of the 'configurable text string' block defined in this module.

  $form = array();
  if ($delta == 'example_configurable_text') {
    // All we need to provide is the specific configuration options for our
    // block. Drupal will take care of the standard block configuration options
    // (block title, page visibility, etc.) and the save button.
    $form['block_example_string'] = array(
      '#type' => 'textfield',
      '#title' => t('Block contents'),
      '#size' => 60,
      '#description' => t('This text will appear in the example block.'),
      '#default_value' => variable_get('block_example_string',  t('Some example content.')),
    );
  }
  return $form;
}

/**
 * Implements hook_block_save().
 *
 * This hook declares how the configured options for a block
 * provided by this module are saved.
 */
function block_example_block_save($delta = '', $edit = array()) {
  // We need to save settings from the configuration form.
  // We need to check $delta to make sure we are saving the right block.
  if ($delta == 'example_configurable_text') {
    // Have Drupal save the string to the database.
    variable_set('block_example_string', $edit['block_example_string']);
  }
  return;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function block_example_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'example_configurable_text':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Title of first block (example_configurable_text)');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = block_example_contents($delta);
      break;
    case 'example_empty':
      $block['subject'] = t('Title of second block (example_empty)');
      $block['content'] = block_example_contents($delta);
      break;
    case 'example_uppercase':
      $block['subject'] = t("uppercase this please");
      $block['content'] = t("This block's title will be changed to uppercase. Any other block with 'uppercase' in the subject or title will also be altered. If you change this block's title through the UI to omit the word 'uppercase', it will still be altered to uppercase as the subject key has not been changed.");
      break;
  }
  return $block;
}

/**
 * A module-defined block content function.
 */
function block_example_contents($which_block) {
  switch ($which_block) {
    case 'example_configurable_text':
      // Modules would typically perform some database queries to fetch the
      // content for their blocks. Here, we'll just use the variable set in the
      // block configuration or, if none has set, a default value.
      // Block content can be returned in two formats: renderable arrays
      // (as here) are preferred though a simple string will work as well.
      // Block content created through the UI defaults to a string.
      return array('#markup' => variable_get('block_example_string',  t('A default value. This block was created at %time', array('%time' => date('c')))));
    case 'example_empty':
      // It is possible that a block not have any content, since it is
      // probably dynamically constructed. In this case, Drupal will not display
      // the block at all. This block will not be displayed.
      return;
  }
}

/*
 * The following hooks can be used to alter blocks
 * provided by your own or other modules.
 */

/**
 * Implements hook_block_list_alter().
 *
 * This hook allows you to add, remove or modify blocks in the block list. The
 * block list contains the block definitions. This example requires
 * search module and the search block enabled
 * to see how this hook implementation works.
 *
 * You may also be interested in hook_block_info_alter(), which allows changes
 * to the behavior of blocks.
 */
function block_example_block_list_alter(&$blocks) {
  // We are going to make the search block sticky on bottom of regions. For
  // this example, we will modify the block list and append the search block at
  // the end of the list, so even if the administrator configures the block to
  // be on the top of the region, it will demote to bottom again.
  foreach ($blocks as $bid => $block) {
    if (($block->module == 'search') && ($block->delta == 'form')) {
      // Remove the block from the list and append to the end.
      unset($blocks[$bid]);
      $blocks[$bid] = $block;
      break;
    }
  }
}

/**
 * Implements hook_block_view_alter().
 *
 * This hook allows you to modify the output of any block in the system.
 *
 * In addition, instead of hook_block_view_alter(), which is called for all
 * blocks, you can also use hook_block_view_MODULE_DELTA_alter() to alter a
 * specific block. To change only our block using
 * hook_block_view_MODULE_DELTA_alter, we would use the function:
 * block_example_block_view_block_example_example_configurable_text_alter()
 *
 * We are going to uppercase the subject (the title of the block as shown to the
 * user) of any block if the string "uppercase" appears in the block title or
 * subject. Default block titles are set programmatically in the subject key;
 * titles created through the UI are saved in the title key. This module creates
 * an example block to demonstrate this effect (default title set
 * programmatically as subject).  You can also demonstrate the effect of this
 * hook by creating a new block whose title has the string 'uppercase' in it
 * (set as title through the UI).
 */
function block_example_block_view_alter(&$data, $block) {
  // We'll search for the string 'uppercase'.
  if ((!empty($block->title) && stristr($block->title, 'uppercase')) || (!empty($data['subject']) && stristr($data['subject'], 'uppercase'))) {
    // This will uppercase the default title.
    $data['subject'] = isset($data['subject']) ? drupal_strtoupper($data['subject']) : '';
    // This will uppercase a title set in the UI.
    $block->title = isset($block->title) ? drupal_strtoupper($block->title) : '';
  }
}

```

---
Tags: views
---


title: Add Tab to Homebox

text:
# Question
Title: Add Tab to Homebox
I'd love to create a tabbed display for my Homebox where each tab is it's own Homebox. So for instance:

> Dashboard Timesheet Analytics

Where each of the tabs is a link to an individual Homebox - Dashboard being the main menu item.

# Answer
> 1 votes
There is module for that: Quick Tabs

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery

---
Tags: routes, dashboard
---


# Question
Title: How do I enable pagination on a taxonomy term page
I have a taxonomy term page displaying node teasers. I would like to know how I can enable pagination on it?

Thanks

# Answer
There is a default view for that. If you have installed Views module, you can just enable the view named 'Taxonomy Term', which is disabled by default.

Then you can adjust the pager settings in the view configuration interface.
> 3 votes

---
Tags: taxonomy-terms
---


title: Views - need to show 1 image on teaser

text:
# Question
Title: Views - need to show 1 image on teaser
I have a news page on my site, and I'm displaying it using Views and Display Suite so the image is along side by side to the description of the news. In Manage Display for News Content Type I want to display 1 image on the teaser view, then when the user clicks through it shows all images for that news item.

But when I set `#1` in manage display, and click save, it doesn't save the setting. If I have more than 1 image for the news item, it displays all of them in the teaser when I only want to show 1. Can anyone advise?

# Answer
> 2 votes
In **display suite** manage display, put **1** *(the number of image to display)* instead of **#1**

# Answer
> 0 votes
So it's not related to "display suite", it's related to "views" module. Use agregation on the view to group results by content and avoid duplicated content results.

# Answer
> 0 votes
The solution provided by jramby was correct, just set to 1 instead of #1 in Manage Display, and it works perfectly. The workaround I provided also works, but would recommend just setting to 1 of course.

# Answer
> 0 votes
Though its an old question but recently I also came a cross the similar problem, here is the module which resolved my problem: https://drupal.org/project/field\_multiple\_limit

From the module's project page:

> This is a simple module that provides settings to limit the number of values to display on fields with multiple values.
>
> The module extends the field display settings for fields which permit multiple values. Site administrators can specify how many values to display for each display mode (e.g. teaser). Optionally, an off-set can be specified to skip some values.

---
Tags: views
---


# Question
Title: perform action if user is not logged in for 24 hours
I wrote this script using poor man's cron to send an email in 24 hours if a user has not logged in during that amount of time. It works but I can't figure out why after 24 hours passes the email sends, but then it starts sending again every hour.

```
function dreamcharts_cron() {
      $now = time();
      $result = db_query("SELECT u.uid, u.mail, u.access
                      FROM {users} u
                      INNER JOIN {users_roles} ur ON ur.uid = u.uid
                      WHERE ur.rid = 4 AND u.uid NOT IN (0,1)");
      $i = 0;
      while($user = db_fetch_object($result)) {
        if ($user->access + 86400 < $now) {

         // drupal_set_message('<pre>' . print_r($user->mail, 1) . '</pre>');
               $message = array(
            'to' => $user->mail,
            'subject' => 'you have not logged in in 24 hours',
            'body' => t('Please log into your Account Today', array('@title' => $title)),
            'headers' => array(t('From') => variable_get('site_mail', ini_get('sendmail_from'))),
               );
              drupal_mail_send($message);
          $i++;

      }
      }
      }

```

# Answer
It is sending every hour because cron is running every hour, and the user has not yet logged in to change the timestamp. There is no check to see if the email has been sent, or when it was sent.

You can either update the user's timestamp to $now, which will stop the email from being sent for the next 24 hr., or set a flag on the account to say that an email has been sent.
> 3 votes

---
Tags: 6, cron
---


# Question
Title: Dynamically size images for mobile first design (omega theme)
I've built my first site using an omega subtheme and I'm really liking it. The mobile first design dynamically changes the width of the page to follow the width of the browser.

With my column arrangement with a wide browser, my content area is 780px wide. So, the header images I use on my blog posts are up to 780px wide. If the user's browser is more narrow, then the css will shrink the content area to the following sizes:

wide: 780px normal: 620px narrow: 460px mobile: 720px and smaller (in this arrangement the sidebars are removed to give the content more room.

The smaller the browser gets, the smaller the content area gets. When it is below 720px, then it follows pixel for pixel, so if I make my browser only 480px wide, then that's how wide the content area will be.

PROBLEM:

The header image on my Article nodes is up to 780px wide so that it fills the content area in the widest browser size. However, when the content area shrinks to 620px, the image doesn't get smaller which means that it overlaps the side bar.

The image below shows how the layout would work in the "wide" arrangement.

The next one shows how the header image is overlapping the sidebar in the "normal" arrangement:

I tried to solve the problem by setting the css width of my header image to be 100% of its container element. That did successfully restrict the width of the image, but when drupal generates the html for that image it always includes explicit width and height tags. This causes the image to become distorted because the width is shrinking to match 100% of the parent container but the height isn't changing along with it, so it ends up looking like this:

Is there a way to prevent drupal from including the explicit height attributes? Or is there some other drupal solution?

I know that I could set up some javascript to strip those attributes off, but that seems really hackish.

Any suggestions or solutions?

# Answer
More of a CSS than Drupal question, but the standard solution is

```
img {
  max-width: 100%;
  height: auto;
}

```

You might get some funny results with images inside table columns that don't have an explicit or minimum width set, but those just have to be handled on a case-by-case basis.
> 2 votes

# Answer
I would add this in a comment to Clive's answer, but I don't have enough reputation to post a comment, so I'll add this here. Not only is the standard CSS solution correct, but be sure also to read Ethan Marcotte (who was one of the first prominent authors to write about responsive design) writing about fluid images at: http://unstoppablerobotninja.com/entry/fluid-images/

There's important information there as to making fluid images a bit more cross-browser compatible, especially for older versions of IE that don't understand `max-width`.

Cheers!
> 0 votes

---
Tags: 7, media, theming
---


# Question
Title: How to see override functions and template files in use for any part of the drupal site?
I remember there is a module for displaying which core or theme functions or template files are used in order to create any part of a drupal site. Has anyone know what is the name of this module?

I need this module in site building. Thanks in advance.

gokhan

# Answer
You are thinking about the Theme Developer module. When you install and enable, it you can click on just about any properly rendered element and see

* Preprocess and process function candidates
* Theme function candidates
* Template file suggestions

Just keep in mind that it can interfere with some themes, and doesn't work well in some versions of IE.
> 1 votes

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


# Question
Title: How to make slideshows work on mobile devices browsers?
I created a view formatted slideshow using Views Slideshow and another formatted flexslider using Flex Slider.

But the two blocks show no content when displaying the page from a mobile device.

What's wrong (with flexslider as it support mobile) or how to make the slideshow work for mobile using one of the two modules listed?

# Answer
Download the FlexSlider library from https://github.com/woothemes/FlexSlider

Put the folder in a libraries directory sites/all/libraries and also

Try installing the FlexSlider Views Slideshow module which integration with Views Slideshow and FlexSlider

> This is the FlexSlider Views Slideshow module which used to be included in FlexSlider by default.

This tutorial shows you how to create a responsive slideshow using the Views Slideshow module and jQuery FlexSlider.
> 1 votes

---
Tags: views
---


# Question
Title: Why is the first visit to a rarely used site slow or even lead to timeout?
I am looking for suggestions on Apache/Drupal/MySQL (localhost) configuration, to solve my issue. I use Ubuntu servers 8 LTS with classic Apache installation, and perform manual Drupal installation too. After publishing a site for customer review, I notice, that if a site is not visited very often or not visited at all for some time, such site response time increases significantly, up to situations with timeouts. Although, other vhost sites not on drupal on the same server run smoothly. E.g., if a site is rarely used, opening and navigating through out it takes very long times, or even timeouts. Each next page visit opens faster.

I use regular Apache settings and PHP memory up to 512MB, as sometimes Drupal module installations ask for more. Server is with 4GB RAM, and around 10 sites running on it at a time. Drupal for customer review is set without caching and performance settings turned on, thus I consider, that this can be a bottle neck in some cases, but still, if I work on the site, it is quite responsive, even without performance settings turned on.

I understand that there are very many ways of solutions and potential issue roots, but wondering, if there are some constructive ways to track this down to small list of tasks to accomplish better configuration. I've experimented with different Drupal performance tuning solutions found on the net, but it still does not solve issue, if a site is not used frequently. Restarting apache helps for a while.

# Answer
> 3 votes
There isn't a lot of information, and the answer is likely specific to your instance, but my first guess is that you are experiencing the effects of one or more cache misses.

If you are using APC, then your rarely used site may not have core files in the bytecode cache. Subsequent visits will.

If you are using MySQL query caching, then your rarely used site likely doesn't have anything in the cache, so all queries need to actually run.

The Drupal cache entries themselves (ie, the variouls `cache` table) may also be stale, so initial slowdowns could be caused by this.

If you are using Poormanscron, then this could be running, too, on initial page loads.

# Answer
> 2 votes
On Drupal 7, this is most certainly caused by Drupal's built-in implicit running of the site's cron hooks when a user hits any page on the site if it has not been run in quite some time.

You should disable this, and set up a proper cron job that runs externally. This way, users won't experience long page loads on a cold start.

See Improving Drupal 7 performance after a period of inactivity for details.

# Answer
> 0 votes
May be the accepted answer to this question may help you What would the optimal MySQL configuration for a Drupal 7 site be? or may be the answer to this question Why Drupal 7 is so slow?

# Answer
> 0 votes
Maybe the issue is not with the web server configuration, but instead lying with the DNS servers. If you are actually using 'localhost', see Firefox and Chrome slow on localhost; known fix doesn't work on Windows 7. Otherwise, test with the IP address - if the problem only occurs when using the hostname, the problem is probably DNS-related.

---
Tags: performance
---


title: D7: using a list-based field for views

text:
# Question
Title: D7: using a list-based field for views
Stumped. This should be Drupal 101, but the dots aren't connecting.

Scenario: from among many, I have two content types:

* employee
* department

Each content type displays on its own but we will also run a list of employee teasers as a list within a views block on the department pages. This is easy to create: I use views to render the list, i.e.,

* View uses filter criteria of "department" for a teaser list of employees.

Set the views block to display on the appropriate department node page on the blocks admin page and all is good. However, I have 7 department pages. Sure I *could* create the first view, clone that view per required filter type, but, better, is reusable code. Both content types have the same "department" field list (uses the core list module) where I've identified the department.

How can I use that "Department" list field to create the link that joins the employee list to the department when rendering the department page?

# Answer
Using Drupal 101, and assuming that you have one Department page per department, and one Employee page per employee, and assuming that each employee can be associated with more than one department ...

First add a node reference field to the Employee content type (field\_department). Set it to reference the Department content type and set the number of values to unlimited.

Then create a view of Content type:Employee.

Add a Relationship on `Content:Department (field_department)` and make it *Required*.

Then add a Contextual Filter on `Content:NID`. Have it use the Relationship you have just created and configure it to *Provide Default Value: Content ID from URL* when the filter is not available.

Under *Advanced \> Query Settings* check *Distinct*. This type of query might produce duplicates.

Place the View block on the Department page, and this will restrict the list to employees related to the department currently being viewed.

A similar approach can be used with term reference fields, but you would require two relationships (first to the term, then from the term to the other content type). I cannot speak about the List module as it appears to be discontinued on D.O.
> 2 votes

# Answer
You add a `contextual filter` to the view block that grabs the department ID or title as a filter for your employee list.

Then you can re-use the 1 block at essentially any path with a department in the url you setup as the `path` in the Blocks UI, or if your using Context, etc.
> 1 votes

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


# Question
Title: Display multiple values of a field in separated rows
I'm using drupal 7, and in my node views, I have a field named field\_phone to display phone numbers. It is possible for a company to have more than a phone number, so I add some more rows in form edit to add more phone numbers. Instead of displaying all numbers in multiple rows, Drupal automatically puts them all inline inside a `<span>` tag. There are so many people on google trying to the opposite thing: make them display inline.

So I think that, by default, it displays multiple values in separated lines. How can I get over this stuff?

P.S.: I know I can edit the template file, and make it display the way I want, but it's not cool at all, when I have to edit all the field template files, as all my multiple-values-fields are displaying that way.

# Answer
> 1 votes
1) If you are using a view with field you can click on your field and have a look at

"MULTIPLE FIELD SETTINGS"

the checkbox "Display all values in the same row" is checked by default. If you uncheck it it's going to show your field in different rows.

2) If you are using a view with content (teaser, full etc..) you can modify the output in different way:

Have a look at Field API The one you may need is template\_preprocess\_field()

```
function templatename_preprocess_field(&$variables) {
    if($variables['element']['#field_name'] == 'field_name') {
        if($variables['items']['0']['#markup'] == 'your_value') {
            $variables['items']['0']['#markup'] = '';
        }
    }
}

```

If you have Devel Module you can use the dsm() function to see how to manupulate it.

```
function templatename_preprocess_field(&$variables) {
        if($variables['element']['#field_name'] == 'field_name') {
            dsm($variables['element']);
        }
    }

```

It will show what's inside $variables\['element'\] as a drupal message.

3) You can use field.tpl.php and use field-name-\[field\_name\].tpl.php to target only your field. Have a look at theme\_field() .

If you want to change all your multiple value field in that way, use the second method without the if statement that targets your field.

Find out the method better fits your needs.

# Answer
> 0 votes
You could be interested in Text Formatter module which enables you to format multi-value fields to your liking

# Answer
> 0 votes
You can create a Custom Field with Views PHP module. You exclude your original value from display, add get the value in your php code with $data or with $row

You can create your own php function to display values as you wish.

Example :

```
print _your_own_function( $data );

```

---
Tags: entities
---


# Question
Title: Is there a way to create custom page in panels with path "/search"?
Is there a way to create custom page in panels with path "/search" ? I need to replace default drupal 7 search page with my own views page. But I can't because this path is already exist (duplicate). Also I can't disable "Search" module, because I use in views filter providet by search module "Search: Search Terms". Any advise will be appreciated.

# Answer
If you have Search Module enabled, you should see built-in search node panel page.
> 2 votes

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


title: Like / Dislike Button

text:
# Question
Title: Like / Dislike Button
I need to like AND to dislike contenttyps, but the total likes should be displayed as Likes - Dislikes. I tried to use the "flag" module and created two different flags (one for likes, one for dislikes) but this leaves me with two problems

1. I need to get the total count of the likes (likes - dislikes) within a view - how can I do this??
2. Can I disable the like/dislike button, if it was already clicked? So you can like and dislike but only once (no toggle).

# Answer
You might be able to customize the excellent tutorial on the use of Ajax for Like and Dislike using voting API by Amitav Roy. His primary purpose is to show the reader how to use AJAX, but the code is solid and seems to suit your purpose.
> 1 votes

---
Tags: views, nodes, flags, rating
---


# Question
Title: Hooking in to the email verificatin process
In Drupal 7 (7.22), we'd like to hook into the email verification process for new users. Perhaps the one time password node. We need to do a test on the email address and set a value in a custom user field based on what we find. This will allow us to give software activation terms to users with email matching certain business partner domains, for example.

Extra credit: we'd also like to enable a particular role for these users. The first step, though, is to figure out where to hook in our php to do a regex test of $user-\>mail.

# Answer
> 0 votes
It would make more sense to create a rule to activate on *After saving new user account*. You could do a Text comparison on `Account:mail` using your regular expression, and if the condition was TRUE, *Assign a role* for the new user. It would be waiting for them when they verified their account.

If your requirements change for the site, it is easier to make an alteration through the UI than it is to track down the code that has to be changed.

The same rule can *Set a data value* in the custom user field if you wish.

EDIT:

Install and activate the Rules module. Then go to `/admin/config/workflow/rules` and create a new rule, calling it, lets say 'Upgrade new user' and set it to react on *After saving a new user account*.

When the configuration screen comes up *Add condition* and select *Text comparison* (wait for the AJAX request to complete) then set the Data selector to `account:mail`. Under Matching Text, click the *Switch to direct input* button, enter your regular expression in the Value box, and at the bottom use *Regular expression* for the Comparison operation. Then save the condition.

Then add two actions; First add *Add user role* (wait for the ajax to complete) and you should see `account` as your data selector. Then choose the role(s) to add and save the action.

Then add an action to *Set a data value*. In the Data selector, find your field, and click *Continue*. In the *Value* box using `<?php ... ?>` delimiters, enter the code you need to `return` your activation key.

Save everything and try it out.

---
Tags: hooks, emails
---


title: files[] not working on module_name.info

text:
# Question
Title: files[] not working on module_name.info
I am having problems making my module work.

module\_name.info

```
...

files[] = module_name.module
files[] = module_name.pages.inc
files[] = module_name.admin.inc
files[] = module_name.install
files[] = module_name.controller.inc

...

```

But when the module should access to functions stored on module\_name.module I get this error, saying the function has not been found.

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback....not found or invalid function name in call_user_func_array() (line 517 of /path_to_modules/module_name/includes/menu.inc). =>

```

If I put the functions on the module\_name.module file, everything works fine. Apparently is not loading the files\[\]

**Update: I've followed this example:** https://github.com/LearningDrupal7Development/artwork

Any idea?

# Answer
> 5 votes
`files[]` is only used to register files containing *classes or interfaces*, not functions. The docs explain it well:

> Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing **class or interface declarations** in the .info file, like so:
>
> ```
> name = Really Neat Widget
> ...
> files[] = example.test
>
> ```
>
> When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.

emphasis mine. Unless you have classes in any of those files (including the .module and .install file) that you want to be auto-loaded, you don't need an entry for them in the .info file; it just won't do anything.

If you need to pull other files in you can use `module_load_include()`, e.g.

```
module_load_include('inc', 'module_name', 'module_name.controller');

```

---
Tags: 7, files
---


# Question
Title: What is the reason to define indexes in hook_schema?
How do I choose what fields to index and which ones not to? Is the index useful for when I set a condition in the database query for a quick look up of the rows? I guess this is an SQL question but I really want to know what indexes are used for Drupal entities.

What are all these indexes in the node table for?

```
  'indexes' => array(
    'node_changed'        => array('changed'),
    'node_created'        => array('created'),
    'node_moderate'       => array('moderate'),
    'node_frontpage'      => array('promote', 'status', 'sticky', 'created'),
    'node_status_type'    => array('status', 'type', 'nid'),
    'node_title_type'     => array('title', array('type', 4)),
    'node_type'           => array(array('type', 4)),
    'uid'                 => array('uid'),
    'tnid'                => array('tnid'),
    'translate'           => array('translate'),
  ),

```

# Answer
# MySQL Indexes

You can start by reading the MySQL reference.

You are right in saying that index is useful when you use a condition in your query. Deciding which fields to index is not as easy as it looks, though. There are pros and cons to each index, and it is not right to say that having an index always boosts overall performance at the expense of disk space.

Using index results in faster lookup of data when queries use the indexed columns in its conditions; however, large indexes can slow things down in cases of heavy inserts or updates to the table as any update to the rows result in updates to the index as well.

Therefore, you have to carefully decide if it is worth adding an index to the column even if you are going to use it in a query. In most cases it is.

On the next level, when you are using multi-column indexes, you have to be even more careful about the queries. Suppose you define:

```
CREATE TABLE test (
    id         INT NOT NULL,
    last_name  CHAR(30) NOT NULL,
    first_name CHAR(30) NOT NULL,
    PRIMARY KEY (id),
    INDEX name (last_name,first_name)
);

```

You might expect a query like this to use an index, but it won't.

```
SELECT * FROM test WHERE first_name = 'hw';

```

The reason is explained in the documentation:

> The name index is an index over the last\_name and first\_name columns. The index can be used for lookups in queries that specify values in a known range for combinations of last\_name and first\_name values. It can also be used for queries that specify just a last\_name value because that column is a leftmost prefix of the index (as described later in this section).

# Drupal

As far as Drupal is concerned, it uses the Schema API to define those indexes. As you would see, these are common fields that are used in queries on the `node` table.
> 8 votes

---
Tags: database
---


# Question
Title: Differences between Firefox and Chrome in the Omega theme
I'm building a site in Omega, and I'm having trouble understanding why Firefox is so much different than Chrome/IE. For example, in the menu bar, the font is fine and the text has plenty of room on the right side; in IE and Chrome, the font is much larger and the text wraps to another line. The display width doesn't seem to be that much different. Zooming in and out don't seem to matter.

Why does it seem to fit like it should in Firefox, but not IE/Chrome? How can I control that?

# Answer
As I previously mentioned in comment, its not related to Omega nor Drupal, but you can still try to use normalize.css.

> A modern, HTML5-ready alternative to CSS resets (as used by Twitter Bootstrap, HTML5 Boilerplate, TweetDeck, Soundcloud, and many others)

Alrternatively as you didn't provide any link or capture, I suggest to check your styles and libraries list in your omega subtheme settings, go to `Appearance > THEMENAME > Settings` , under Toggle styles and Toggle Libraries
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Do I need to give a complete copy of my site's source code to a themer?
I want to get my sites themed from expert themers ( for example at Freelancer etc). I need node, views etc be themed along with site look and feel.

I've done little themeing till now and I tested with my site source.

What I want to ask is it necessary to give complete site source code to the themer which i don't want to do? What minimum they'd need?

# Answer
> 3 votes
The minimum they need depends on what you are having them theme.

Basically they have to have everything they need to do their job.

If you exclude something that affects any visual part of the site it could impact their ability to do their job.

If they are making the whole theme for your site I feel you really should give them everything, because if you don't it is possible that some things will not get themed.

If I was the one implementing the theme and I was not given the whole code I would definitely specify that any problems with the theme that relate to not having all the parts are not covered by warranty.

In the end though it depends on your specific site and what you are having themed. Maybe on your site there are pieces of functionality/code that could be excluded without impacting the parts of the site being themed.

If your worry is them seeing your code, because there are specific things regarding your code that are very sensitive then you either need to find a themer you can trust, and have them sign legal NDA agreements or whatever else is required.

If you are worried about them doing bad things to your code, use version control. Have everything in version control before you give it to them so that when you get their work back, you can see exactly what has been changed, so if they are changing things they shouldn't be you can more easily know about it.

You could also try to get someone to review their work (or you review it yourself if you have the knowledge).

Another thing you could do is host the site somewhere on the internet where the themer can work on it, but only give them access to the theme directory. So they are allowed to FTP to the theme directory only, and not have access to the rest of the site, but they still get to use the fully functioning site.

The harder you make things for them though, the more chance you have of getting an inferior result or having the work take longer than expected.

---
Tags: theming
---


# Question
Title: setting template file using template_preproccess_page not working
I have a list of pages with url

```
?q=value/abc/1
?q=value/abc/2
?q=value/abc/3
?q=value/abc/4

```

for which i require a specific template.I have written a `template_preprocess_page` function,but it does not call the required `tpl` file.But if i set the test variable as `$test = array("value/abc/1");` the template file is being used.Could someone tell me what i am doing wrong..??

```
function template_preprocess_page(&$var){
 $test = array("value/abc/%");
        if(in_array($_GET['q'], $test)){
            $var['template_file'] = 'testing';
        }
}

```

# Answer
Assuming D6 then, in template.php:

```
/**
 * Implements hook_preprocess_page
 */
function THEMENAME_preprocess_page(&$variables){
 if (strpos($_GET['q'], 'value/abc') === 0) {
   $variables['template_file'] = 'testing';
 }
}

```

Clear theme registry, or all caches at `admin > config > performance` to apply.

More info:

> There are two special variables that these hooks can set: 'template\_file' and 'template\_files'. These will be merged together to form a list of 'suggested' alternate template files to use, in reverse order of priority. template\_file will always be a higher priority than items in template\_files. theme() will then look for these files, one at a time, and use the first one that exists. https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme/6
> 1 votes

# Answer
I believe what you want is to set up five content-type templates. You can read more about this here and in this tutorial. Essentially if you wish to use a template, you need to create a content-type for it. Then you can use your content-type machine name (let's say your content type's machine name is "foo" then your template PHP file will be titled "page--foo.tpl.php"

You have to then add this to the top of your template.php in your main theme:

```
function YourTheme_process_page(&$variables) {
      $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}

```

Then you can add a content page for each content type and give it the path you need (ie value/abc/1 or value/abc/2 etc).

If the processing you do with your URL value is minimal, then you can also just retrieve the value through the PHP $\_GET function and then use it in your PHP processing as needed (after sanitizing the variable of course).
> 0 votes

---
Tags: theming, 6
---


title: Have conditional fields in entityform

text:
# Question
Title: Have conditional fields in entityform
So it's my first time using entityform module which is awesome to create an order form.

Within my form, I have an "Entity Reference" field which prepoppulating as checkboxes from my "Node: Products".

in my order form now I have my node:title to choose from, what I want is that another field appear IF the user select one.

mainly I want the user to be able to select/check the product name then provide the amount he is ordering with another textfield or something.

# Answer
> 0 votes
I tried conditional fields module which is in dev version to make it works!

> Conditional fields module, define dependencies between fields based on their states and values.

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


# Question
Title: Duplicate part of the main menu to a sidebar
I am building a website like the one in the picture (here is the photoshop mockup :P) My question is the blue arrow!

I want to relate the main menu with the node as follows: When the visitor clicks on a parent item of the main menu (or a child of that parent menu) (let's say he clicks on "services" or on "Web dev" or "Web design" or "SEO") I want a submenu to be displayed, on the left sidebar, with "services" as the parent element highlighted and the sub elements also present (as shown in the photo).

If i use menu block and choose to display from a certain level and on, then I will have that level from the whole main menu depicted, and not just the active one, right? (for my example, in the left sidebar i only want to show the items shown, not "Home" or "About us" or "Contact us")

Which modules should I use? Can I do it with hook\_page\_alter, and if yes, how will I choose to only show the submenu of services and not the whole main menu? (Any directions are appreciated)

P.S. for what's worth, the main menu is a drop down Superfish menu with a depth of 2 levels.

# Answer
> 0 votes
in nice menu you can select parent menu item to render, also you can achieve this with views tough

---
Tags: 7, navigation, theming
---


title: How to add multiple fields

text:
# Question
Title: How to add multiple fields
Let's say, I have a `text field` which I use it as a phone number field. I set the number of values to `unlimited`, so people can enter more than one number.

However, I want to use another `text field` for the definition of that number. Such as:

```
Name    Number
====    ======
Home    123456
OFfice  234567
Mobile  456789

```

How can I combine these two fields and require the Name field to be filled when each time a number field is created?

# Answer
> 2 votes
the easiest way is field\_collection:

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

You can make a compound field in code as this Phase2 Blog Post describes .... maybe there's a module for a compound field, but its usually not worth the effort.

# Answer
> 2 votes
You can also do this using the Double Field module:

> Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can divide your fields into two seporate parts.
>
> For the moment it includes the following sub-widget types:
>
> * Textfield
> * Select list
> * Single checkbox
> * Textarea

---
Tags: entities
---


# Question
Title: Access one field from another when using entities
On my Drupal 7 website, I have used Entity Construction Kit to create an entity that contains two fields: `field_body_image` and `field_image_position`.

This entity is then attached to a node.

I want to be able to access the value of `field_image_position` from inside `field_body_image`. How can I do this?

---

**Steps I have taken to solve the problem:**

I know that if you have the fields placed directly on the node (ie. so not using ECK) you can use field\_get\_items

However, this doesn't seem to work when ECK is involved.

Here is the code I am using in my template.php file

```
function [THEMENAME]_field__field_body_image(&$variables) {

    //Load the value of field_image_position
    $field_image_positon = field_get_items('node', $variables['element']['#object'], 'field_image_position');
    $image_positon       = $field_image_position['und'][0]['value'];

if ($image_positon == 'image_position_bottom' ) {
print 'Successful' //This is just a test to see if it works, the actual code will be different
}
 However, this does not work.

```

If I use Devel and do:

```
function [THEMENAME]_field__field_body_image(&$variables) {
kpr($field_image_positon);
}

```

Then I can see `field_image_position` located in the following:

```
$...['element']['#object']->field_image_position['und'][0]['value']

```

and

```
$...['element']['#items'][0]['value']

```

So how can I access it?

(using `$field_image_positon = field_get_items('node', $variables['element']['#items'], 'field_image_position');` causes a White screen of Death. )

# Answer
You mentioned you are using ECK to create a new entity, whereas in your code, you are using `'node'` instead of the machine name of your entity.

I am referring to the line:

```
$field_image_positon = field_get_items('node', $variables['element']['#object'], 'field_image_position');

```

Change `node` in this line to `your_entity_machine_name`.
> 2 votes

---
Tags: entities, theming
---


title: How to add text under menu items

text:
# Question
Title: How to add text under menu items
In my menu, I want to add some text under the menu item. For example, I have 'About Us', and right under that, I want some subtext 'About our company'.

Do I add this in region.tpl.php?

# Answer
> 1 votes
Use superfish module for building your menu, and then whatever you type in your description depend on configuration will be print out too.

Under Advanced HTML `Settings > Hyperlinks` enable the "Include hyperlinks description (title) in hyperlinks text."

then simply add a `display: block;` style to the `ul li a span` to make it look the way you want.

you can see a demo HERE

---
Tags: 7, theming
---


# Question
Title: How do you add a conditional to check if the Node object exists?
I have the following code, but how do I add a conditional to check if the menu\_get\_object() is grabbing a node object or not? Im mainly using this in my contextual filter in views and its throwing an error on etity\_metadata\_wrapper() as its trying to load a node page while its in the view page. I'm not sure what condition to check before it returns anything. thanks!

```
$node = menu_get_object();
$wrapper = entity_metadata_wrapper('node', $node);
$tid = $wrapper->field_device_type_vocabulary[0]->tid->value();
return $tid;

```

# Answer
If you are on a non-node page, `menu_get_object()` returns `NULL`.
> 1 votes

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


# Question
Title: How to synchronize two check boxes values, upon change?
In my module, I have created a simple form with a single checkbox (A) and a submit button. I also have a checkbox (B) boolean that i added in the user profile. Now I would like to:

1. write a submit function that would update checkbox (B) with the status of checkbox (A).
2. Get rid of the submit button, and have Checkbox B updated automatically upon change of checkbox (A) status.

I am trying to achieve an email notification on comments system as I described here in a previous post: How to add a checkbox form to a panel?

Thanks,

baba

# Answer
I got it working this way:

```
/**
 * Implements hook_block_info
 */
 function mymodule_block_info() {

  $blocks['block_notify'] = array(
                           'info' => t('Notify me'),
                           'cache' => DRUPAL_NO_CACHE,
                           );

   return $blocks;
}

/**
 * Implements  hook_block_view
 */
 mymodule_block_view($delta = '') {

 $block = array();
 switch ($delta) {
               case 'block_notify':
                 $block['content'] =  drupal_get_form('mymodule_example_form');
                 break;

              }
  return $block;
}

function mymodule_example_form($form, &$form_state) {

 global $user;
 user_full = user_load($user->uid);
 $val = $user_full->field_user_message_notification['und'][0]['value'];

 $form['form_notify'] = array(
                         '#type' => 'checkbox',
                         '#default_value' => $val,
                         '#title' => t('Notify me by email when I receive a new message'),
                         //'#description' => t("Check this option to be notified by email when you receive a new message"),
                         );

drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule_request.js', 'file');
global $user;

return $form;
}

function mymodule_example_form_submit($form, &$form_state) {
// Submission logic.
 global $user;
 $user_full = user_load($user->uid);
 $edit = (array) $user_full;
 $edit['field_user_message_notification']['und'][0]['value'] = $form_state['values']['form_notify'] ;
 user_save($user_full, $edit);

 }

```

Then to trigger form submit on checkbox change I just added the follwing javascript in mymodule\_request.js

```
jQuery(document).ready(

function ($)
{
 jQuery.noConflict();

 $checkBox = $("#edit-form-notify");

 if( $checkBox.length != 0)
 {
    $checkBox.click(
        function(){
            //        alert('hello');
            this.form.submit();
            }
          );

 }
});

```

I can now just select the "Notify me" block in my panel by " add content" in panels.
> 0 votes

---
Tags: forms
---


# Question
Title: How can I add my field of his type of material to be used in the rule
I need to compare two different entities in the field after the update term. Event: "After updating existing term" One field is in the *drupal commerce product*, the other in a *term*. With the help of "entity has a field" do not get to add because you do not see the entitie of the product. What can be done to solve the problem?

# Answer
I hope it is for D7 I was facing same issue some months ago, I assume that you want tocheck the Boolean value of the fields? please confirm that is that you want to do.

To compare to different entites I did following

You might not need to add these module to achieve what you want, but they are always good to know.

Drupal Commerce extra conditions

Drupal Commerce Extra Rules

Gives you more options when working with drupal commerce and conditions Drupal Commerce extra rules - Well it gives you more rules to play with.

But for taxonomy term, Rules would just work out of the box.

The logic would be a "Data comparison" condition, specify the field name, and enter "1" as the value. If the field doesn't appear in the list of fields, first add an "Entity has field" condition, and select the field there. Then add the "Data comparison" next.

1. Data Comparsion
2. Condition, give the field name you want, give the value 1.
3. If you cant find your field. You will need to add it in the above condition as "Entity has field" - or specifying "Content as type". Then you will choose the operator which should be == (equals)
4. Add Data comparsion. (Field might have to be direct input mode)

Hope it helps
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Creating a one-time password, and send the email
We need to create a system where the user enters only an email address. For a specific domain user receives an email with a generated password, and for all other domain receives a notification email to contact support. Password used to access a protected area of the site that is not available to the public. Also, the password can be used only once, ie. each time a user enters an email address, get a new password.

Any ideas how to make this system to Drupal 7?

# Answer
> 0 votes
Login One Time comes closest to your requirements. From its project page:

> Login one time provides the ability to email one-time login links to users.
>
> Features
>
> Rules:
>
> * \[user:login-one-time\] token on user events.
> * \[comment:login-one-time\] token for node author on comment event.
> * User profile - "Send login one time link" button.
> * VBO - Create a view and send login links to the view. Checkout View Reference for ideas on how to embed views.
> * Block - Select a user and send the link. You can use this block in nodes as a CCK field using Block Reference.
> * PHP - Print a button in a template or directly send the emails using the functions described in the README.

---
Tags: users
---


# Question
Title: Which modules are required for the dynamic webform on webform.com?
I'd like to allow users to create webforms like the one on webform.com.

>

Which modules are required? Is Arrange Fields one of them?

# Answer
The website is using the Form Builder module.

> This project allows users to build entire Form API structures through a graphical, AJAX-like interface. It has the ability to read and export FAPI arrays, and users are permitted to change any properties exposed by modules that expose forms to the Form Builder.
> 1 votes

# Answer
you could go through http://www.commercialprogression.com/post/drupal-webforms-dynamic-select-boxes-tutorial for creating webform dynamically.

Link tells you how to create dynamic drupal select boxes. It is done mainly in three steps which are to

1. Build your form with Webform Module.
2. Create a custom module to access your database.
3. Dynamically create and change select boxes on your form.
> 0 votes

---
Tags: webforms
---


title: XML Sitemap for Media

text:
# Question
Title: XML Sitemap for Media
I'm looking for a module, that creates a special sitemap for media (using the Drupal Media 2 module).

# Answer
> 0 votes
You can use the Custom sitemap for achieving this

> The Custom Sitemap module allows users/site admins to add custom sitemaps to a site, unlike currently available module that binds users to build a sitemap using the primary menu.
>
> This module enables you to add or promote random URLs from SEO viewpoint. It also facilitates you to add independent sitemaps for all domains in a multi domain Drupal setup. This also helps you to have a domain specific custom sitemap.

# Answer
> 0 votes
You can use the XML Sitemap for achieving this

For more information about this module you could go through the README.txt of this module.

---
Tags: media, 7, xml-sitemap
---


title: How to use the Drupal flashcard module?

text:
# Question
Title: How to use the Drupal flashcard module?
I am not very familiar with Drupal modules.

I am using Drupal 7, and installed the Flashcard module. I enabled it, the flashcard-cycle module, and the libraries module; I also added the jquery plug-in as \sites\all\libraries\jquery.cycle\jquery.cycle.min.js.

I am getting the flashcard content type in structure/content types, but I don't know what else I have to do.

I need further instructions about what I need to do in order to use the flashcard module. What is my next step?

# Answer
Go to this content type's "Manage fields" page and add new field with "Flashcard" type. Set number values you want (I think you will need Unlimited). Go to "Manage display" page and change your new field formatter from "Default" to "Cycle". Create a new node with a couple of Flashcard pairs.
> 2 votes

---
Tags: 7
---


# Question
Title: Restrict forum access based on user (user list)
I need to restrict access to forums so that only selected users can access an individual forum. (The users should apply for a forum and a moderator should decide if the user should be allowed to participate in that forum or not.)

If users visit the forum listing page for the first time, they should only see all forums listed but they should not be able to see the topics.

I have used Flag module to implement a subscription system.

I have set a flag `'subscribe_forum'` that allows users to flag a forum, and another flag `'approve_forum_subscription'` that allows an administrator to flag a flagging, which means the subscription of the user is accepted.

What I want to do is to grant that user access only to those forums which he has subscribed to and has been approved by an administrator.

The solution you would suggest doesn't have to use this flag system. I am open to any other suggestions.

I have installed Forum Access module, however it allows me to restrict access based on roles, but I need to have a list of users for each individual forum. The only thing that is useful for my case on this module is the ability to set a moderator for individual forums.

Edit: I am also using Advanced Forum module to extend the functionality of the core Forum.

UPDATE:

I have mostly achieved my goal using Panel pages which are already provided by Advanced Forum, adding some custom selection rules.

I have added a PHP Code rule which returns TRUE if the user has flagged the forum, and a moderator accepted it (i.e. flagged the flagging of the user), and FALSE otherwise. I have also added a fallback variant which shows only an 'access denied' message in a panel pane.

I have done the same thing to the topic listing panel, as well.

Then, I have enabled the panel page that overrides node/node% and added 2 selection rules, one for checking if the content type is forum and the other one is the custom PHP.

So, I have almost what I wanted to have, but I am not yet completely sure if this method I follow is a good one. To be honest, I don't find it elegant enough.

I am still open to other suggestions. It can also be a completely different approach.

Thanks in advance.

# Answer
> 1 votes
If you use views or panels to display the forum, you can use their access controls which are quite flexible. Doesn't look like AF has built views for everything, so I think the easiest way would be to use Panels.

Create a page and under the page settings you have access rules that can be quite elaborate within the UI. You can use a naked layout and then just had the forum entities as content to display and render the full node.

Second Look: Take a look at the Drupal Module Flexiaccess. It looks like exactly what is needed and has a nice UI to manage the users that have access to the individual forum with out writing/maintaining custom stuff:

> The Flexi Access module will provide a simple and flexible interface to the ACL (Access Control List) module. It will let you set up and mange ACLs naming individual users that are allowed access to a particular node.
>
> The module let you manage access to individual nodes. The administrator may grant individual users the right to: View (read), update (edit/write), and delete the node.
>
> The main idea behind Flexi Access is to allow flexible per user access control for nodes without the complexity (or features) of Organic Lists, and without having to create a lot of (overlapping) roles.

I see you using Flag to set up the "subscription request" then a moderator looks at the flagged users with the Flag and if approves add em to the ACL with flexiaccess?

# Answer
> 1 votes
Maybe this is more reliable and worth trying:

* Create a user list in views with the subscribed users for every forum. In this view you should use the nid of the forum type as a contextual filter.
* Install and enable Rules Bonus Pack and Conditional Rules modules.
* Create a rule that will trigger on the event: "When a page variant is loaded" where the page variant = the forum page
* In that rule set an action "Load a user list with views" to load the above view
* Add a loop through that list
* Inside this loop add a conditional and then an Add if condition: uid of current user is not in that list (Data/List contains item/Negate)
* Finally continue (inside the same loop) by adding an action to redirect the user to some other page and if you want, add another action for the system to send a message like: "Your subscription has not yet been approved by the admin" or something.

I understand the answer is a bit brief. In case you need more details or some help with the rule let me know.

# Answer
> 0 votes
Since you want the most granular form of permission ( per-user), without too much of investigation, I would check:

https://drupal.org/project/user\_permissions

Second way (non-entirely Drupal, but working) Or writing a custom module that does this functionality.(Gets list of users and a simple field 1 or 0, then in hook node preprocess (php) , you can add some simple logic, to show specific thing only if the value is 1. Also, that will involve some CRUD operations.

There might be other answers though.

Regards

---
Tags: 7, flags, nodes, users
---


# Question
Title: How to hide empty fieldset, but leave prefix and suffix in place?
Simple as this - I have a Form API fieldset with dynamically changing content. When it's empty, I don't want to show it at all. I use `#prefix` and `#suffix` to generate div my AJAX works with.

When I use:

```
$fieldset['#access'] = FALSE;

```

it disappears with it's div and no future AJAX call can make it reappear. So, how to hide it with empty, but leave wrapper intact?

# Answer
The easiest way would be to wrap the fieldset itself in another element.

```
$fieldset_wrapper = array(
  '#prefix' => '<div class="wrapper">',
  '#suffix' => '</div>',
);

$fieldset_wrapper['fieldset'] = array(
  '#type' => 'fieldset',
  '#access' => FALSE,
);

```

As you might expect, setting `#access` to false will prevent an element from being rendered at all.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How can I get a taxonomy menu into the main menu AND a block?
I've got a taxonomy menu of products in DCommerce which appears in the main menu, but I also need it to show up in the sidebar. I installed menu\_blocks but that can only access the main menu that the product menu is within.. and if I make the product menu into it's own menu, I can't get it into the main menu. Can it show up twice??

# Answer
> 1 votes
Taxonomy menu block combines the idea of **Taxonomy menu** with the workings of **Menu block**:

This module does not make use of Drupal's menu system. Taxonomy menu first creates a menu which can then be displayed through a block, this module creates the block directly.

```
Make multiple menus per vocabulary.

"Split" the taxonomy into different menus.

Make a menu out of a specific branch of your vocabulary only.

Follow the active trail, also for nodes coupled to a term with a term reference field.

```

---
Tags: blocks, commerce, taxonomy-terms
---


# Question
Title: Restrict User Type to buy a Product Type in Drupal Commerce
I am selling membership type without using subscription module as it doesn't fit into my scenario. I am assiging role by help of rules as per Randy screencast & it works nice for me.

Now the problem is with renewal of the membership. So I have to set up another kind of product type, which will work for renewing the membership.

So is there any way to restrict usertype to buy any product type ?

Thanks :)

# Answer
> 0 votes
You can create a different product display type (i.e. content type) for the renewal product (at admin/structure/types). Then you can restrict that content type to those with the members role (in admin/people/permissions).

Or, if you want to show the product display type, but restrict the actual purchase, I think you have to resort to custom code like this:

```
<?php
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the Commerce 'Add to Cart' form.
 */
function custom_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  global $user;
  $roles_allowed_to_buy = array(
    'Some Custom Member Role',
    'administrator',
  );
  if (!array_intersect($user->roles, $roles_allowed_to_buy)) {
    // Display a help message.
    $form['help'] = array(
      '#markup' => t('You do not have permission to buy this product.'),
    );
    // Disable the whole form.
    $form['#disabled'] = TRUE;
    // Remove any submit button(s).
    unset($form['submit']);
  }
}

```

(that's an example you would put inside a module called custom\_module)

---
Tags: 7, commerce
---