# Question
Title: DrupalDatabaseCache is causing performance issues
I have devel query log / page execution time enabled on my site and most of the queries which are slowing down my site are related to DrupalDatebaseCache.

> DrupalDatabaseCache::set

**Sample Query :**

> UPDATE cache SET serialized=:db\_update\_placeholder\_0, created=:db\_update\_placeholder\_1, expire=:db\_update\_placeholder\_2, data=:db\_update\_placeholder\_3 WHERE ( (cid = :db\_condition\_placeholder\_0) )
>
> INSERT INTO cache\_menu (cid, serialized, created, expire, data) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4)

Any clue what drupal is doing with caching and how to minimize it . thanks

**####Update####**

I installed Memcache but still DrupalDatabaseCache calls are being made which is making the site slow .

# Answer
> 3 votes
If you concerned with performance then you want to maximise caching, not minimise it!

Caching is used to store data once expensive (time consuming) processes have been used to prepare it. Then future page requests simply return the cached data and don't have to do the slow processing again.

By default Drupal stores it's cache in the database but as you've spotted this isn't always that fast. Using a module like APC or memcache allows you to store the cache in the servers memory, as opposed to having to write it to the DB so this is much faster.

To make the most of Druapl's caching functions I would also recommend taking a read of lullabot's excellent article: A Beginner's Guide to Caching Data in Drupal 7

# Answer
> 2 votes
Getting memcache working correctly is the right answer. I'm leaving a link here for people who don't have the option of installing memcache and are looking for a solution: Fixes for MySQL Deadlocks in D7

---
Tags: caching, performance
---


title: LDAP module + Windows AD

text:
# Question
Title: LDAP module + Windows AD
I have a large AD setup which has not been configured in the ideal fashion, the base DN:

```
dc=davinci,dc=mydomain,dc=local

```

Now the existing structure of our AD looks something like:

```
@ 1122 Logan
  Accounting
  Aquarius
    Alejandro
    Mike
    Justin
  Aerospace
  Distribution
  Engineering
@ 2150 Logan
  Uniflyte
@ 1480 Church

```

Trying to test the authentication of the user Alejandro (old network guy was being funny when he gave me a user name).

Here is my Server Property Dump:

**Server Properties:**

```
sid = Davinci
numeric_sid = 1
name = Employees
status = 1
ldap_type = ad
address = davinci
port = 389
tls = 0
followrefs = 0
bind_method = 2
basedn = Array ( [0] => dc=davinci,dc=cadorath,dc=local )
binddn =
user_dn_expression = cn=%username,%basedn
user_attr = samaccountname
account_name_attr =
mail_attr =
mail_template =
picture_attr =
unique_persistent_attr =
unique_persistent_attr_binary = 0
ldap_to_drupal_user =
testing_drupal_username = Alejandro
testing_drupal_user_dn = cn=Alejandro,ou=@ 1122 Logan,dc=davinci,dc=mydomain,dc=local
grp_unused = 0
grp_object_cat =
grp_nested = 0
grp_user_memb_attr_exists = 0
grp_user_memb_attr =
grp_memb_attr =
grp_memb_attr_match_user_attr =
grp_derive_from_dn = 0
grp_derive_from_dn_attr =
grp_test_grp_dn =
grp_test_grp_dn_writeable =
search_pagination = 0
search_page_size = 1000

```

I enter in my password for non-anonymous search (Windows login password)...

**Testing Drupal DN:**

> cn=Alejandro,ou=@ 1122 Logan,dc=davinci-1,dc=cadorath,dc=local

Drupal logs report:

```
LDAP bind failure for user userdn=, pass=XXX.

```

Where does the userdn get constructed???

I still cannot login to drupal with Windows login details...D7 is running in the same domain as Davinci so I assume I missing something in the syntax of connection string???

# Answer
The ldap config page for users and fields has a *user\_dn* entry you can set.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Drupal commerce user based percentage discount
I need to have different order total discount rates in % for each customers. The default discount is 10% for all users and it need to be override for certain users too. i.e administrator can set the different discounts such as 12% for user1 and 15% discount for user2 etc on a specific interval (between valid from and to dates). Is it possible using rules or custom module?

Please help.

# Answer
Yes, Rajeesh, anything is possible with Rules. : P

In this case, I'd recommend something like a discount percentage field on user profiles that defaults to 10% and is only visible to administrators who can then override the field value on a user-by-user basis. Your product pricing rule can then look for this field to have a value on the order's user (i.e. use commerce-line-item:commerce-order:owner as the token, not the site:current-user) and then apply it as a discount using the appropriate line item action.
> 3 votes

# Answer
Can you try using commerce discount module which supports dates as well as users... See screenshot below of Create Discount Form..

> Provides a user-friendly UI for managing discounts. The discounts are exportable entities based on which the discount rules are generated.
>
> Contains two submodules:
>
> commerce\_discount\_date: Allows limiting discount validity by date, requires the Date module. commerce\_discount\_usage: Allows limiting discount validity by number of uses (as of alpha1, still needs work!).
> 0 votes

# Answer
Thanks @Ryan Szrama, the product pricing rule and user account new field 'field\_vip\_disc\_perc' worked for me. Now I can override the discount field integer value of each user and gets it deducted from the order total as discount percentage value. In pricing rule event 'Calculating the sell price of a product' I added the action "Multiply the unit price by some amount" for Data Selector 'commerce\_line\_item' with the Amount 'field-vip-disc-perc'. To get the discount percentage deducted from order total, I added the PHP evaluation return value, $value = 1-($value/100); return $value; which is applied to the Price component type Discount.
> 0 votes

---
Tags: rules, commerce
---


title: Are unique node titles neessary?

text:
# Question
Title: Are unique node titles neessary?
I am considering automatically assigning the uid to several of my content types automatically. However, one other data type uses a number as its title too (product number actually.) There is a strong potential for a uid to be the same as a product number. Could this potentially cause problems? What are some common problems that can arise from non-unique titles?

# Answer
Drupal itself does not depend on titles or labels to identify entities, and there is no expectation within the core system that they would be unique. You could in theory have a completely functional site with ten thousand nodes all sharing the same title, tagged with ten thousand terms sharing the same name, linked by ten thousand menu items sharing the same label.

Drupal is full of locally unique, automatically generated IDs: each node has an `nid`, each term has a `tid`, each menu has an `mlid`, and so on (though for identifiers unique across the system, one must use UUID or something similar). Provided your custom code, theme output, Views filters, and so on can be written to reference these machine IDs, I would expect few problems.

It is not always possible to rely on those machine IDs; they are content, and so are subject to editing, deletion, and replacement. You might want a banner to appear on your *About Us* page, but depending on the season the *About Us* page may be `node/25` or `node/29`, for example.

Thus it is possible, even unconsciously, to build parts of the site that *do* depend on labels. Many themes insert a class on the `<body>` based on title, or on the alias/context (which pathauto will by default set to the title); you may have CSS rules applying to the wrong pages. You may have an editorial policy that all nodes pertaining to a particular product include its product code in the title, and set up Views to filter them. But only takes one typo for a node to go missing, or one forgotten edit to the title of a cloned node to have extras appearing.
> 4 votes

# Answer
Drupal uses node ID (`nid` column in `node` table) as a unique identifier and uniqueness of the title is irrelevant for the system.

AFAIK, the only issues you might face are related to management and administration of such content.
For example on `admin/content/node` or other administrative views it will not be clear which piece of content should you edit or delete. You can easily overcome this by installing Admin Views and including node ID next to the node title in your custom views to make the difference visible.

In one of the projects I developed, titles were generated automatically for one content type. Some nodes had exactly the same titles, but it never caused any issues.
> 2 votes

# Answer
No major problems, in my opinion. you will want to create a new view for editing content though, because the default content view uses title.

also if you're using auto generated URLs they'll be kind of ugly, unless you change how they're structured.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Create additional menu page for node that can be accessed by the nodes' alias with /page?
I created a block using `hook_block_view()` and `hook_block_info()`, then set-up the page with `hook_menu()` using `page arguments` but this seems to only work for node/**id**/page?

This is what I have right now:

```
$items['node/%node/text'] = array(
    'page callback' = 'my_module_function',
    'page arguments' = 'array(1)',
);

```

I need it to work for the nodes alias which might be article/**node title**/ or journal/**node title**/ - they are for two different content types. Going to just article/ or just journal/ shows a View page that displays all the articles or everything from the journal.

Currently whenever I try to go to:

> article/**node title**/page

the article/ Panel page is loaded. However disabling the panel for **article/** then going to article/**node title**/page causes a Page not found error, so it seems it's something to do with my `hook_menu()` not registering the URL aliases of the nodes?

As *node/**node id**/page* works perfectly fine.

Edit: unsure how to reopen, see comments

# Answer
You have two options.

## 1. Using the Sub-pathauto (Sub-path URL Aliases) module.

This is based on pathauto, and will create additional aliases for node sub-pages.

This also works for other entity types such as `user/123/contact -> people/geronimo/contact`, if `user/123` has the alias `people/geronimo`.

## 2. Write a custom wildcard loader (far more work).

I am going to use the word "slug" here, which I remember from Wordpress.

The usual node path is `node/%node`, which will trigger the `node_load()` wildcard loader. This wildcard loader only takes node ids. It does not work with node titles. So, `node_load(123)` gets you the node with that id, but `node_load('node title')` will return NULL.

You could now create a new module "mymodule", and use `hook_menu()` to define a separate path `article/%mymodule_article_slug`, and sub-paths `article/%mymodule_article_slug/page`, `article/%mymodule_article_slug/edit`, etc.

This is going to be some work, you need to look into node.module and the `hook_menu()` implementation found there, and copy a lot from there. Or you could use `hook_menu_alter()` instead of `hook_menu()`, and copy some of the data already registered for `node/%` and friends.

The essential trick now is to define a wildcard loader for `%mymodule_article_slug`.

```
/**
 * Wildcard loader callback for '%mymodule_article_slug'.
 *
 * @param string $slug
 *   Part of the url identifying the node, e.g. "pink-elephant"
 * @return object|null
 *   The node object, usually an instance of stdClass, or
 *   NULL, if no such node exists.
 */
function mymodule_article_slug_load($slug) {
  // Load the node identified by $slug.
  $node = ...;
  return $node;
}

```

Now it gets insteresting. How do you load the node identified by the "slug"? There are different ways.

1. You could store the slug in a field on the node, and then use EntityFieldQuery to load the node with that field value. You also need to decide what to do if more than one node has the same slug.
2. You could use path + pathauto and find the node where the alias is `"article/" . $slug`. `drupal_get_normal_path()` can help you with that.

With method 2, your code would look like this:

```
function mymodule_article_slug_load($slug) {
  // Load the node identified by $slug.
  $normalpath = drupal_get_normal_path('article/' . $slug);
  if ($normalpath && preg_match('#/node\/(\d+)$/', $normalpath, $m)) {
    $nid = (int)$m[1];
    if ($nid > 0) {
      return node_load($nid);
    }
  }
}

```

EDIT: This only works if the "slug" does not contain any slashes by itself!
> 0 votes

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


title: One time db scrub with .install file

text:
# Question
Title: One time db scrub with .install file
I need to scrub a production db to replace paths in the body field. Being a production database, it needs to happen in a time-sensitive, well-documented way with the solution frozen in code. I'd assume that a .install file would be the best way to do this.

What would a one time install script look like to search the database for "http://mysite.com" and replace with "https://www.mysite.com" in the default body field?

# Answer
I typically do things like this outside of modules, and instead use a drush script.

The script itself, would go something like

* Go into maintenance mode
* Do an EntityFieldQuery to get my nids.
* Loop through each nid, and
* Load the node, and make an entity metadata wrapper
* Do the search and replace on the fields
* Save the node
* Exit maintenance mode

Before and after running the script, I usually do a `drush sql-dump`. You can even combine all of this into a single script

```
#!/bin/bash

drush variable-set -y --always-set maintenance_mode 1
drush sql-dump --result-file=~/db/before.sql
drush scr path/to/my/script.php
drush sql-dump --result-file=~/db/after.sql
drush variable-delete -y --exact maintenance_mode

```

By doing a drush script, you can really ensure that the task runs when you want it to, and you aren't bound by execution time limits. I also find it easier to debug.

That said, you should just be able to use Pathologic to rewrite the URLs. Install/enable it, and add it to your text formats, and configure to do the path fixups.
> 0 votes

---
Tags: 7, database, installation
---


title: Adding Search to Responsive Menu Module

text:
# Question
Title: Adding Search to Responsive Menu Module
I'm trying to set up responsive menu module (https://drupal.org/project/responsive\_menus) and add an advanced search inside of it. I've been unable to get the advanced search to show up in the responsive menu. I am using the codrops' Google Nexus\* theme and Drupal 7.

If its not possible to add search inside Responsive Menu, or if there is an alternative module or solution I am open to that as well. Any help would be appreciated. Thank you!

# Answer
> 1 votes
Can you make a "feature request" over on drupal.org about this? https://drupal.org/node/add/project-issue/responsive\_menus

It doesn't have a way to do anything other than the left-side vertical menu currently. I'd like the Google Nexus style to be able to use the top horizontal area as well.

---
Tags: 7, routes, search, theming
---


# Question
Title: Tag to show Related Content Type and Term
I have Content A and Content B Both share the same taxonomy tags i.e interests i.e football, sport, tennis

When someone clicks on tag i,e term "sport"

I want it to show All Content A with "sport" Terms tags

Not All Content A and B with Sport Terms tags

How can I do this please?

Many Thanks for your help

# Answer
You could create two separate vocabularies each with the same terms in it, then make one vocabulary available to content A and the other vocabulary available to content B.

An alternative is to use views: https://drupal.org/project/views

With Views you can list items of a Content type with certain tags associated with it on a page.

E.g. I have two content types News & events both are categorized by term group. I only want display all News items so I use Views to only show content type News.
> 0 votes

# Answer
Yes! I use Pathauto module

It allows you to create URL aliases for all content, users, taxonomy terms etc.

When you enable it look for URL aliases in Administer. Then there is a tab called Automated alias settings. In there you can select which content types and taxonomy terms have which alias.
> 0 votes

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


# Question
Title: How to sort product displays by price using search api sorts?
Actually I want to do the same behaviour as in commerce kickstart 2 for sorting my products by price. I'm using search api, search api db, search api sorts, search api ranges, commerce search api modules. I have created indexed node view with views and it is working fine. I can range nodes by price... I indexed the field "field\_tshirt\_commerce\_price\_amount\_decimal\_asc" with my node (my product type is called tshirt). And I want to see it in my sorts, but it just writes "There are currently no fields for which sorts can be displayed." Am I missing something?

# Answer
my solution is:

1. Fields Tab: in Related Fields section add Product-Price multi field
2. Field sTab: check field\_product:commerce\_price:amount\_decimal for index (integer)
3. Filters Tab: enable aggregated fields.
4. Filters Tab: add aggregated field: name - your custom label, type of aggregation - first, Contained fields - Price \> Amount (decimal)
5. Fields Tab: check your new aggregated field for index (integer)
6. Sorts Tab: now your custom aggregated field available for sort

Be sure you are using latest dev version of the Search API sorts because of the https://drupal.org/node/2202093 issue.
> 2 votes

---
Tags: 7, commerce, search
---


# Question
Title: Horizontally sliding gallery with visible neighbors?
I'm looking for a way to create a horizontally sliding gallery, where the non-"highlighted" images can be seen to the left and right of the "highlighted" image, instead of a normal slideshow where there is just a transition to the next image in a static box.

Essentially, the functionality shown by Royal Slider, and also demonstrated on the WeArInteractive homepage under "Featured Works."

The only thing that I can find that's close is ImageFlow, but it's not quite the same and has some other odd functionality that I don't prefer.

The popular gallery/slider modules that I have found don't seem to have a built in way to do this, but maybe somebody has figure out a way to do it? I don't mind using views as part of the solution, as I'm assuming that will probably be a necessity.

# Answer
> 0 votes
That technique is most often referred to as a carousel.

I would recommend Owl Carousel module (or as a stand alone library depending on how custom you need it) as it is highly configurable and has support for mobile devices as well.

You can check out their (non-Drupal) demo here.

---
Tags: views, media, javascript
---


# Question
Title: How to check when a user last updated password
I would like to display a message to any user who has not changed their password since yesterday (4/21/14).

Does Drupal keep track of when the password was last updated? If so, how can I access that information?

# Answer
> 4 votes
Drupal out of the box does not keep track of password changes. However, there are modules that do:

Drupal 7: The module **Force Password Change** keeps track of it. The data is in its schema (`$schema['force_password_change_users']`), in the field `last_password_change` (shown below):

```
'last_password_change' => array (
  'description' => t('A UNIX timestamp referring to the date that the user last changed their password'),
  'type' => 'int',
  'unsigned' => TRUE,
  'length' => 10,
  'default' => NULL,
),

```

Drupal 6: The module **Password Expire** keeps track of it. The data is in its schema (`$schema['password_expire']`), in the field `timestamp` (shown below):

```
'timestamp' => array(
  'type' => 'int',
   'not null' => 1,
   'unsigned' => TRUE,
   'default' => 0,
   'disp-width' => '11',
   'description' => 'Date user last updated password',
 ),

```

You could install one of these modules (depending upon what Drupal version you're using), and just query its table to extract this information as a UNIX timestamp from the field.

It would also be quite trivial to add this by means of a custom module:

You should be able to use `hook_form_FORM_ID_alter` (where `FORM_ID` is `password_change`) to intercept any password changes and record the timestamp for the event along with the `uid` in a table in the database.

---
Tags: users
---


# Question
Title: How do you make sortable tables with a pager with data from a custom table?
For Drupal 6 you could do something like this:

```
$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);
$sql = "...";
$sql .= tablesort_sql($header);
$limit = 25;
$result = pager_query($sql, $limit);
...

```

I took a look and for drupal 7 and both `pager_query` and `tablesort_sql` is now gone. It seems that instead the `PagerDefault` class can be used to create a pager query using DBTNG. I wasn't able to find any clues on a simple API for attaching a sortable table to the query like it is done in Drupal 6.

So how do you create a sortable table with a pager pulling data from a custom table?

# Answer
> 8 votes
You use the so called extenders. In your case, the code would be similar to the following one.

```
$header = array(
  array('data' => t('Order id'), 'field' => 'order_id'),
  // ...
  array('data' => t('Transaction time'), 'field' => 'payment_time', 'sort' => 'desc'),
);

// Initialize $query with db_select().
$query = db_select('your table name');

// Add the fields you need to query.
// ...

// Add the table sort extender.
$query = $query->extend('TableSort')->orderByHeader($header);

// Add the pager.
$query = $query->extend('PagerDefault')->limit(25);
$result = $query->execute();

```

See HowTo: Convert a module to DBTNG, Dynamic queries: Table sorting and Extenders.

# Answer
> 6 votes
Use the `TableSort` and `PagerDefault` extenders.

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

$table_sort = $query->extend('TableSort') // Add table sort extender.
  ->orderByHeader($header); // Add order by headers.

$pager = $table_sort->extend('PagerDefault')
  ->limit(5); // 5 rows per page.

$result = $pager->execute();

```

# Answer
> 2 votes
Use the DataTables module.

> The DataTables module integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:
>
> * Variable length pagination
> * On-the-fly filtering
> * Sorting with data type detection
> * Smart handling of column widths
> * Themeable by CSS
> * And more to come...

# Answer
> 0 votes
You can just include the same Drupal 6 tablesort\_sql in your code and it works fine.

For pager:

```
$count = <Total No. of Table rows>

$sql = "...";
$sql .= tablesort_sql($header);
$limit = 25; //Pager limit

$results = db_query( $sql );
$rows = array();
//Loop through the result.
while ( $row = $results->fetchAssoc() ) {
$rows = <Get your array values for Table row>
}
$current_page = pager_default_initialize($count, $limit);
$chunks = array_chunk($rows,$limit, TRUE);
$output = theme( 'table', array( 'header' => $headers, 'rows' => $chunks[$current_page] ) );
$output .= theme( 'pager', array('quantity',$count ) );
print $output;

```

---
Tags: 7, database
---


# Question
Title: How to find out if a Rule is successfully executed or not?
I am using Drupal7. I have created a custom event for a rule using `hook_rules_event_info()`. I have added a Rules Action for the Rules Event "*Flag a node*".

When I invoke the Rules Event in code, using `rules_invoke_event()`, I have to know whether the Rules Action is executed successfully or not.

How can I identify if the Rules Action fails and handle the failure situation gracefully? Primarily I need to know how to identify whether the rule is successfully executed or not?

# Answer
Try enabling debugging in rules-\>settings. Hope this will help you in finding the execution of action
> 5 votes

---
Tags: 7, rules, flags
---


# Question
Title: Why does file_validate_extensions fail to validate?
I'm using the following code for validating and uploading a file from a form:

```
function request_form_submit($form, &$form_state) {
    $validators = array('file_validate_extensions' => array('png'));
    $file = file_save_upload('spectrum', $validators);
    if ($file) {
        //do stuff
    }

```

Uploading works, but I want to allow only png files to be uploaded. The validation part does not work at all, file uploading is always successful no matter which extension the uploaded file has.

I also tried giving a space separated list of extensions to `file_validate_extensions` as mentioned in the documentation, but that didn't change anything.

Any idea what I'm doing wrong here and why this doesn't work at all?

# Answer
```
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['survey']['file-upload'] = array(
  '#type' => 'file',
  '#prefix' => '<div class="survey-file-upload">',
  '#suffix' => '</div></div>',
  '#description' => 'Image type PNG/JPG Max Size:2Mb.',
);

function create_survey_form_validate($form, &$form_state){
$save = file_save_upload('file-upload', array('file_validate_extensions' => array("jpg png")),"public://user_sheets",FILE_EXISTS_RENAME);
  if($save == null){
    form_set_error('file_upload', 'Please select a file');
  }
  else if($save == FALSE){
   form_set_error('file_upload', 'Error in file upload');
  }
}

```
> 1 votes

---
Tags: 6, files
---


# Question
Title: drush make build script tries to download project itself from drupal.org
I use a drush make build script to install a profile. Just started that install profile project.

https://raw.githubusercontent.com/groovehunter/releasemanager/master/build-releasemanager.make

When I do

```
drush make "https://raw.githubusercontent.com/groovehunter/releasemanager/master/build-releasemanager.make" -v -y

```

it prepares the core and tries to download

```
Loading release_info engine.                                                  [notice]
Unable to clone releasemanager from                                           [error]
http://git.drupal.org/project/releasemanager.git.

```

but that's oviously not successful. THe code is on github only. I have no clue where drush get the information the project lives on drupal.org ?

Cleared drush cache, also manually, but Cannot get it now

# Answer
seems there were some wrong cached files.

I removed all ~/.drushrc/cache/git and downloads
> 0 votes

---
Tags: drush
---


# Question
Title: How can I set up the media file selector for an image with the image styles in the same row?
What I want to do is this:

Thank you.

# Answer
> 0 votes
You can use the Formatter Field module to choose an image style per entity

> The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.

But I don't think anything exists to choose a formatter per *delta* of a field. You'd probably need to look at coding that one yourself. The Formatter Field module would be a good place to start to get ideas for the code.

---
Tags: 7, media
---


title: Style views exposed filters options

text:
# Question
Title: Style views exposed filters options
I'm using views exposed filter, so the users can select a categories from taxonomy.

This is an example of the structure:

Category 1

-sub category 1

-- sub-sub category 1

-- sub-sub category 2

-sub category 2

Category 2

-sub category 1

-sub category 2

The problem is some of the sub categories has a same name, so for the user it's hardly to recognize which sub category belongs to specific category. I'm trying to style with CSS the main categories in one color and sub categories in other, but with firebug I don't see a way how to do that. Is there any option or feature for Views exposed filters? So far I've tried with better exposed filters module, but it does not have any option for that.

# Answer
You need each subcategory in a separate opt-group.

There is a thread about adding support for that here: Support optgroups for taxonomy selection list.

The thread includes a patch that can be applied to give this functionality.

There is also a module called Taxonomy container that looks like it also does what you want (image from module page):

I would also recommend the chosen module to further improve the select and allow additional styling changes (it converts the select to a UL).
> 2 votes

---
Tags: theming, views
---


# Question
Title: Resolving mysql error Integrity constraint violation: 1062 Duplicate entry '' for key 'uri':
I'm getting the integrity constraint violation error (as shown below). There indeed exists a row in file\_manage table with uri=''.

So my question is **can I simply delete this row entry from the table without any side affects?** Additionally how this empty row could have been added here.

Error Output when I do "drush cron":

```

WD node: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0,                     [error

:db_insert_placeholder_1, :db_insert_placeholder_2); Array
(
    [:db_insert_placeholder_0] => 0
    [:db_insert_placeholder_1] => 1
    [:db_insert_placeholder_2] => 1398243826
)
 in drupal_write_record() (line 7166 of D:\WORKAREA\work\htdocs\gij\includes\common.inc).

```

And here is the table row with empty uri:

```
mysql> select * from file_managed where uri='';
+------+-----+----------+-----+----------+----------+--------+------------+----------+
| fid  | uid | filename | uri | filemime | filesize | status | timestamp  | origname |
+------+-----+----------+-----+----------+----------+--------+------------+----------+
| 3356 |   0 |          |     |          |        0 |      1 | 1389353548 |          |
+------+-----+----------+-----+----------+----------+--------+------------+----------+
1 row in set (0.00 sec)

```

# Answer
You can check whether the file is being used by another part of the system with the `file_usage_list()` function:

```
$file = file_load($fid);
$usage = file_usage_list($file);

```

If the returned array is empty, you can probably assume that it's an orphaned record, and safe to delete. But take a backup first, as always.
> 5 votes

---
Tags: 7
---


title: Include a View page in a Book Outline

text:
# Question
Title: Include a View page in a Book Outline
I have a site that heavily uses the book module to organize hierarchical documents. I would like to include a View in a Book Outline.

Here is a simplified example: The Parts Department of a company has documentation of all of its standard operating procedures. These procedures are organized using Drupal's book outline. The department also uses a content type called "Part" to individually enter descriptions of each part. A view was created to display a glossary of parts. This glossary should be in the book outline, but I cannot find a way to insert a view into a book outline.

**Example:** Parts Department Standard Operating Procedures

1. Page: Procedure 1
2. Page: Procedure 2
    1. Page: Detail A
    2. Page: Detail B
3. Page: Procedure 3
    1. Page: Detail A
    2. Page: Detail B
    3. Page: Detail C
4. View: glossary of parts -- NEED TO GET THIS INTO BOOK OUTLINE.

Thanks for your help.

Jordan

# Answer
I'm not sure if this was the best option, but ultimately, I had a time deadline and this is how I solved my problem of including my glossary views in a book outline:

1. Created pages A-Z as regular *book page* nodes. Assigned URL paths */book-root/glossary/a*, */book-root/glossary/b*, etc.
2. Created a "node template" panel variant for glossary pages.
3. Populated panel variant with a view content pane that displays the correct page of my view based on context from the */a*, */b*, */c*, etc., in my node URLs.
> 1 votes

# Answer
You can use the Views Field module, to embed a view into. Here is a quote about it (from the module's project page):

> Allows field tables to be used as base tables with Views.
>
> On a field settings form, you may select:
>
> * to expose the field table as a base table
> * the columns of the field table to expose (e.g., entity\_type, entity\_id, and delta)
>
> Multiple "exposed" field tables may be related by a multi-column join using the primary key columns. This module provides a programmatic interface to trigger this relation. A user interface is provided by the combination of the Field Group and Field group views modules.
>
> One use case is to generate a table using columns from one or more field tables. As the field tables are treated as standard base tables, the Field API handling of the "field" is not invoked. Thus, by default, the raw value in each column of the field table is displayed.
>
> By relating field tables, the individual columns of each table function as if they were part of a single table.
> 1 votes

# Answer
Create a blank book page called Glossary (or whatever), then add a Block display to the view, and make that block show up on the book page's path.

You'll have to use AJAX if you have exposed forms because without AJAX the exposed form won't work (show) when used as a block.

(I would also like to know whether it's possible to include other paths into a book's outline because there are cases when view-as-a-block doesn't suit.)
> 1 votes

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


# Question
Title: can I implement select_or_other just with core form API?
Select (or other) works great but I want know can I implement its functionality with `invisible` key available for #states attribute described in form API

# Answer
> 1 votes
Yes you can do that with FAPI & #states.

You would do something like this:

```
$form['options'] = array(
  '#type' => 'select',
  '#title' => t('Select'),
  '#options' => array(
    'one' => t('One'),
    'two' => t('Two'),
    'three' => t('Three'),
    'other' => t('Other'),
  ),
);
$form['other'] = array(
  '#type' => 'textfield',
  '#title' => t('Other'),
  '#states' => array(
    'visible' => array(
     ':input[name="options"]' => array('value' => 'other'),
    ),
  ),
);

```

This would make the "other" field visible when the value of the "options" field is "other".

For more info on states see the docs for drupal\_process\_states()

---
Tags: 7, forms
---


# Question
Title: How to always show poll results view instead of vote view on poll single node?
The default poll runtime settings don't fit our needs. We need to have a time window with a specific start date and a specific end date. When it's too early the button and radio inputs will be hidden. I solved that by a simple `hook_form_alter()`. But when it's too late the results view should be displayed and I can't find out how.

All anonymous users.

I know I could `hook_init()` everybody to the `node/%nid/results` URL. Problem is, this URL gets unavailable when the user already voted. How does Drupal know if someone already voted? How can I call the clean URL alias of a node and ensure that always the results view will be displayed even when the poll settings still say the poll is open?

# Answer
> 1 votes
It's `template_preprocess_node()` to hook in :D

```
function MYTEMPLATE_preprocess_node(&$vars) {
  // check if we are in the right place
  if ($vars['type'] == 'poll') {
    if ( /* add other conditions here if you need to */ ) {
      // then unset the voting view first
      unset($vars['content']['poll_view_voting']);
      // and add the results view instead
      $node = node_load($vars['nid']);
      $vars['content']['poll_view_results'] = array('#markup' => poll_view_results($node, TRUE, FALSE));
    }
  }
}

```

---
Tags: 7, polls
---


# Question
Title: New user email notification not being sent
This is my first day using Drupal, and I apologize in advance for such a basic question. I am using Drupal 7.26 with no modules installed and when I try to sign up new users the e-mail notification is not being sent. I tried signing up with two different e-mail addresses and checked the spam folder in each account. I also tried to find an answer on the internet but I'm not having much luck. Can anyone provide some suggestions on how I might troubleshoot this issue? I've been to my Administration\>Account Settings and Administration\>Site Information but I'm not seeing anything that looks obviously amiss.

# Answer
Install and use the SMTP module: https://drupal.org/project/smtp \- Period. Nothing comes close to using SMTP and you'll avoid current and future headaches. Details are below. Good luck!

**Why sending via the server is bad:**

The post recommended by Anil Sagar is good. However, based on my expertise with web hosts, especially DreamHost, you want to avoid at all costs sending emails from your server.

By default, Drupal sends email via the server it's residing on. That server might not have email configured. That server might have email configured now, not properly configured in the future. That server might get spam listed in the future. In summary, a lot of things might happen that leave you without email sending capabilities, and most probably you will not be notified of the issue.

Also, you're lucky that your email is "not working" as, in most cases, some emails via the server will be sent, others will not, which is even worse as you'll not even know you have a problem to fix.

**Why sending via SMTP rocks:**

When you send via SMTP, you're relying on an external dedicated mail server. Choose a solid mail server provider (Gmail, Yahoo, Zoho, etc) and you'll be on the safe side. They handle maintenance and everything for you and all you have to worry about is the first step which is setting up and installing the SMTP module.

**Note about SMTP sending limits:**

If you're sending a large number of emails, most good email providers will have a daily limit that you'll reach and they'll stop sending your emails. This is a way for them to fight spam. For Gmail, I think the daily limit is 250 emails, which is plenty for most needs. If you have larger volumes, you might want to buy a paid SMTP account with a large limit or consider something like: http://www.mandrill.com/ \- You can send up to 12,000 per month for free. They also have a Drupal integration module: https://drupal.org/project/mandrill

And if you're sending a large number of emails via your own server, you're ending up on a spam list from day one and your emails will soon not even reach junk mail.
> 3 votes

---
Tags: users, emails
---


# Question
Title: How to Show Nodes under different flags in a view
I have two flags, Flag A and Flag B. I need to have a view that lists the nodes that flagged under A and also the nodes that flagged under B.

Using Include only flagged content option in Relationship, I only get the nodes that are flagged by both the flags. But in my scenario I need nodes that are flagged either by flag A or flag B.

# Answer
> 0 votes
I found out the solution for this question.

Refer:https://stackoverflow.com/questions/1340423/or-operator-in-drupal-view-filters?rq=1

If you are using Views 3 / Drupal 7 and looking for the answer to this question, it is baked right into Views. Where it says "add" next to filters, click the dropdown, then click "and/or; rearrange". It should be obvious from there.

---
Tags: flags
---


title: Broken URL on node teaser code

text:
# Question
Title: Broken URL on node teaser code
Fankly this is a silly question.

I want to print node teaser in a block.

As discussed here: How to programmatically render a node's teaser using the theme layer? I've used this code to get the html code of teaser:

```
 $node = node_load($nid);
 $rendered_teaser = drupal_render(node_view($node, 'teaser'));
 //now print this teaser in block using PHP filter.

```

But the problem is that this contains a logo whose img src value is

> http: //default/sites/default/files/styles/small-logo-image/public/ddn-job/iitblogo-1395397403j.jpg?itok=ZhTVC9Ee

Also internal URL's are linked as http:// localhost/node/1 which should have been http:// localhost/mysite/node/1

What is the problem? I've also tried running it through `check_markup($rendered_teaser,'full_html')`

# Answer
> 1 votes
About this problem :

> Also internal URL's are linked as http:// localhost/node/1 which should have been http:// localhost/mysite/node/1

The solution lies in the .htaccess file, at the root of your site : locate the line with `RewriteBase`, uncomment it if needed, and set it to : `RewriteBase /mysite/`

---
Tags: 7
---


# Question
Title: hook form alter with hidden field, throw an error
I try to alter taxonomy edit form.

This is my hook:

```
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
    // hide the desciption field and relations group field
    $form['description']['#type'] = 'hidden';
    $form['relations']['#type'] = 'hidden';

    // set the default value
    $form['description']['#value'] = ' ';
    $form['relations']['weight']['#value'] = 0;
    $form['relations']['parent']['#value'] = array('value' => '13');

}

```

But When I submit, It throw me an error:

```
Warning: Illegal string offset 'value' in taxonomy_form_term_submit_build_taxonomy_term() (line 862 in /Users/tangmonk/MyGit/Drupal/daxuebao/modules/taxonomy/taxonomy.admin.inc).

```

# Answer
> 1 votes
The problem causing the error is that you are setting your hidden description field value is a string, but the taxonomy module is expecting a text area type array with a 'value' and a 'format', which you cannot replicate with a hidden field.

Unfortunately the term description field is a special property of the term, not a proper field, so you can't remove the field (the taxonomy module relies on it being there).

If you don't want people to see it and you always want it to have an empty value a good option is to restrict it from the user like this:

```
$form['description']['#access'] = FALSE;

```

but that doesn't allow you to change the value if you want to.

Another option is to use 'value' instead of 'hidden' as the type, like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  // Hide the desciption field and relations group field
  $form['description'] = array(
    '#type' => 'value',
    '#value' => array(
      'value' => '',
      'format' => 'filtered_html',
    ),
  );
  // Unset the existing relations fieldset.
  unset($form['relations']);
  // Set hidden values for all the sub-fields of the relations fieldset.
  $form['weight'] = array(
    '#type' => 'value',
    '#value' => 0,
  );
  $form['parent'] = array(
    '#type' => 'value',
    '#value' => 13,
  );
}

```

Note the changes to the relations fieldset too:

Since you only want to pass hidden values from the children of the fieldset just remove the fieldset altogether and then set the hidden values (be careful if using other add on modules that add fields to the 'relations' fieldset).

Because the fieldset wasn't using #tree the values passed through in $form\_state will just be \['weight'\] and \['parent'\], not \['relations'\]\['weight'\] and \['relations'\]\['parent'\] so you can leave the \['relations'\] part out when adding the values back in.

---
Tags: taxonomy-terms, forms
---


# Question
Title: Form altered select field is submitting the wrong values
I created a content type in a module called travel\_page.

In Drupal, I added a new empty List(text) field called English\_side\_menu

Now I want to populate the List text dynamically.

I did:

```
/**
 * Implements hook_form_alter().
 */
function travel_page_form_alter(&$form, $form_state, $form_id) {

  // $english_side_menu_list has been initialed here

  $form['field_english_side_menu']['und']['#options'] = $english_side_menu_list;
  dpm( $form['field_english_side_menu']);

}

```

Every thing is working fine, except the value that appears for the select once I submit the button, is the rank of the selection instead of the text selected.

Do you have an idea what is wrong in the code?

Thanks.

# Answer
For dynamic list text no need of form alter for a content type.

You can achieve this goal using Content Construction Kit (CCK) module.

Install this module and configure field as below image and define function statement like

```
function _options_english_side_menu(){
    $english_side_menu_list = array('1' => 'value1', '2' => 'value2');
    return $english_side_menu_list;
}

```

Using this function you can assign dynamic list to list text.
> 1 votes

# Answer
The code should be similar to the following :

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

    if ($form_id == 'ENTER_YOUR_FORM_ID') {

    $english_side_menu_list = array('1' => 'value1', '2' => 'value2');
    //enter the values for the list above similarly
       $form['field_english_side_menu']['und']['#options'][] = $english_side_menu_list;

    }

 }

```
> 0 votes

# Answer
That is because of the options you have set using $english\_side\_menu\_list.

The keys of that array are what is submitted when the user selects a value and submits the form.

Either you have to map the selected value back to the human readable value by using the $english\_side\_menu\_list array when you need to (like in the submit handler of the form or elsewhere when displaying that value), or you have to change the $english\_side\_menu\_list array so that the keys are the same as the values (then that is how they will be submitted).
> 0 votes

---
Tags: nodes
---


title: How to make a drupal site read-only

text:
# Question
Title: How to make a drupal site read-only
I want to make a frozen copy of a drupal site (D6) and prevent users from making any changes whatsoever (except for the system adminstrator, if possible). How can I do that? I want to keep the usernames.

Hiding the login block is easy, but the login url is still available. I've tried disabling all passwords by setting the hash to 'x', but still, someone could recover access via email, and login. So, I want to prevent password recovery too. I could alter all email addresses to something invalid, such as {uid}@example.com. But I don't want the system to even attempt to send email to these addresses.

The site is used for a yearly campaign/contest. I want to keep results of previous contests online, for reference, at a different url, and I don't want anybody changing anything. Ideally, I would structure the site so it keeps previous contest results in the same database, but that requires extensive changes which I don't have the time to do.

# Answer
> 5 votes
1. Disable all user accounts apart from admin.
2. Disable new users from registering new accounts.
3. Edit permissions as necessary.

Now only admin can login, and anonymous users won't have permission to edit anything.

# Answer
> 2 votes
Simply block all the user except the user #1.

---
Tags: users
---


title: Taxonomy View and Paths

text:
# Question
Title: Taxonomy View and Paths
I have a view set up to display all my taxonomy nodes for "Classified Categories" Vocabulary, in the view I have set up the path to be /Dogs however when it lists the terms they are all linked to /Dogs/(term) and this will then display nothing, but if I change the path from /Dogs/ to /Classified-Categories/(term) it will show.

I've had a look at setting up patterns for my URLs but seem to have no joy. Further on this the terms with spaces are linked with %20 in and will not show even in the changed format; only when I replace the %20 with - will they show.

I'm pretty stuck on getting this to work especially being a Drupal newbie.

This is a screenshot from my current configuration of my view.

Both "Link this field to its taxonomy term page" and "Convert spaces in term names to hyphens" are ticked.\**

# Answer
> 1 votes
remove the filter and only add the contextual filter with taxonomy term id. also change path to /Dog/%.

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: Drush downloading to an old version of Drupal
I am new to Drupal/Drush. I tried to learn Drupal last year with tutorial that was based on Acquia-drupal (which I downloaded and was using drush there). Now, i decided to give it another go by installing Drupal on MAMP. I tried to download a few development modules and the operation was a succes, but the modules didn't appear in my list of modules. Than it dawned on me that they must ended up on the wrong location instead at my new MAMP/sites/all/modules... How do I fix that - do I ought to delete the Acquia, or should I install another instance of drush?

# Answer
> 0 votes
Drush is path-sensitive and can be installed system-wide; no need to install a separate instance.

To run Drush commands in the context of a site, you need to be in the web root of that site.

```
cd /path/to/mamp/drupal_root;
drush cc all; // Clears cache for the current site only

```

If you run commands outside of a Drupal root, the effects will vary. Modules will be downloaded to the current folder, cache-clear will clear Drush's internal cache, and some commands simply won't work as they don't make sense without a Drupal boostrap.

---
Tags: 7, drush
---


# Question
Title: Role based exposed filter is not showing anonymous and authenticated roles there. Can anyone tell me any method to add that roles?
I've created one drupal7 view which will filter all contents based on roles not current user role. For that I've created one relationship 'author' then in view filter criteria I've given exposed author roles. But by default Anonymous and Authenticated roles are not showing there. Do we have any method to add Anonymous and Authenticated role to that filter?

# Answer
> 1 votes
That's because they are not really real roles, more just a group of users.

What I mean by this is that the relationship between users and roles is stored in the table users\_roles. There is one field for uid (the users ID), and one field for rid (the role ID).

So, the admin user has a uid of 1 and also has the administrator role with an rid of 3, so there is an entry in the users\_roles table like: 1 | 3.

Any other roles created and assigned will also have rows inserted into this table.

However when the admin user logs into the site there is not a row inserted into users\_roles table for the "authenticated user" role. And likewise when they log out a row is not inserted for the "anonymous user" role.

The actual query used by views would be something like this:

```
SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, node.uid, ur.rid
FROM node node
LEFT JOIN users users_node ON node.uid = users_node.uid
INNER JOIN users_roles ur ON users_node.uid = ur.uid
WHERE node.`status` = '1' AND node.type IN  ('article') AND ur.rid = '3'
ORDER BY node_created DESC

```

Here it is joining onto the users\_roles table, but we know that the roles "anonymous user" and "authenticated user" don't have entries in the users\_role table so it won't work.

So whilst it is possible to add these 2 roles into the select, the query that runs won't ever return anything.

---
Tags: views
---


# Question
Title: How to show a node but return HTTP 404 response
I want to show an existing page(node) normally but return a HTTP404/410 etc instead of HTTP200.

How can I do it? Is there any simple way to do it?

# Answer
> 17 votes
# Drupal's built in mechanisms

for delivering 404 pages are useless to you. We can read:

> Page callback functions wanting to report a "page not found" message should return `MENU_NOT_FOUND` instead of calling `drupal_not_found()`. However, functions that are invoked in contexts where that return value might not bubble up to `menu_execute_active_handler()` should call `drupal_not_found()`.

Of course if page callback will return `MENU_NOT_FOUND`, it will not return any meaningful data. And while calling `drupal_not_found()` does not always prevent data delivery, comments under function clearly shows that it causes double display of error message more often than any other result - not what you want, either.

# Drupal generic header functions

may help you. Especially `drupal_add_http_header()`. Let me emphasize one thing in it's description:

> $value: The HTTP header value; if equal to FALSE, the specified header is unset. If $name is 'Status', this is expected to be a status code followed by a reason phrase, **e.g. "404 Not Found"**.

So you want to set status to 404:

```
drupal_add_http_header('Status', '404 Not Found');

```

It should be enough, after all that's what `drupal_deliver_html_page()` is doing when you use higher-level 404 calls from previous part of my answer.

Also, you might be interested in logging it like other 404 errors:

```
 watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);

```

# Where to place it?

It **depends on what you need to decide** if page should be 404 or not. If all you need is the actual data in page, you can go for `hook_page_delivery_callback_alter()`:

> This hook is intended for altering the delivery callback based on information **unrelated to the path of the page** accessed. For example, it can be used to set the delivery callback based on a HTTP request header (as shown in the code sample). To specify a delivery callback based on path information, use `hook_menu()` or `hook_menu_alter()`.

emphasis mine.

## Let's assume that you need it for nodes

and this means you need a node id. NID is part of the path, so, following suggestion quoted above, you want to use `hook_menu_alter()`.

Let's take a look on how node's menu looks like. The part we want to alter is:

```
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),

    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );

```

What you need to do is to alter it to provide your own callback. In that callback:

1. Perform any logic needed
2. Set header as you need
3. Log to watchdog if you want to
4. Call original callback and return it's result. Render cascade does not explicitly set `HTTP 200 later`, so your status header should be delivered unaltered. Unless some modules will alter it, of course, but that's something we cannot know.

# Last notes

thanks to Ayesh K and MPD:

* Sending header might now work in any of the preprocess hooks or just about any tpl.php file. The fact that you could does not mean you should, especially not in tpl files, as it may interfere with caching, but it's worth to remember you are not limited to the ways I described above. For example `hook_page_alter()` can be a safe choice, too.
* Make sure the page size is more than 512 bytes, otherwise some browsers (Howdy, IE) will ignore it.
* Keep in mind that by RFC 2616

> User agents SHOULD display any included entity to the user.

As you may notice, this RFC uses MUST in some cases and this is **not** one of them, so if browser will refuse to display your page after you send 404, it's not exactly an error. Browsers are **not forbidden** to ignore your HTML when you send 404.

# Answer
> 4 votes
Use drupal\_add\_http\_header()

Put this inside of the node via PHP filter (which is usually a bad idea).

```
drupal_add_http_header('Status', '404 Not Found');

```

OR Put this inside of a hook\_init call.

```
// Get the current active node object if present.
$node = menu_get_object();
if (!empty($node) && !empty($node->nid) && $node->nid == 86) {
  drupal_add_http_header('Status', '404 Not Found');
}

```

---
Tags: 7, http-request
---


title: Bulk deletion of rules?

text:
# Question
Title: Bulk deletion of rules?
I was testing with rules and now I got around 50 rules. Just wondering if Is there any way to bulk delete rules and components

# Answer
The rules module provides a function called `rules_config_delete()`.

You can call this with an array of rules ids to delete multiple rules in one go:

```
rules_config_delete(array(3, 4, 5, 6));

```
> 1 votes

---
Tags: rules
---


# Question
Title: Unpublished content type using rules module based on user role
I have a website were there are two type of users, Administrator and Clients.

I would like to add a rule that should apply if the user is Clients.

The rule should unpublished the new content and send an email to administrator.

I have manage to create the rule which is working fine but the condition is not working.

currently the rule is applying to all the user types.

I am confuse what to use as a data selector to apply the rule only to Clients users.

Thanks,

# Answer
After some background research I manage to fix the problem.

1. Go to content/admin/config/workflow/rules
2. Click add a new rule
3. Give Name to rule and select react even, in my case it was "After saving new content". You can also select restrict by type if you want to apply the rule only to one content type then click save
4. Click add condition, select the condition to add in my case it was user has role(s), add a data selector in my case "site:current-user" because i want to run the rule if user has Role is client. select Role
5. Click add action, select action to add in my case "Unpublish content"click save click save

It is all done, however I had two other actions Send mail to notify administrator to publish content and show a message on the site to tell user his content is waiting for admin approval
> 0 votes

# Answer
Are you using rule sets and triggered rules?

You should use a Rule set to set the conditions for the specific role and unpublish the content.

Then use the triggered rules to schedule the rule. E.g. When a user updates content run the Rule set
> 0 votes

---
Tags: 7, rules, users
---


# Question
Title: Show User Information in Block from View
I have a block that shows some data from the User area (People) in Drupal 7. I have a rewrite setup that shows "VACANT" if there is no user selected for the content type. When logged in, I see users for 3 of the 4 contents I have created, which is correct. When logged out, I see VACANT for all of the contents.

Is there some restrictions on showing User data to the public? How can I make a certain Role visible to everyone?

EDIT::: Thanks to @Clive: **View user profiles \[x\] for anonymous**.

# Answer
> 0 votes
Go to `/admin/people/permissions` and tick the "View user profiles" permission for anonymous users:

---
Tags: 7, blocks, users
---


# Question
Title: Contextual Links not appearing in Panels
I use panels to display almost every page on my website. I display content type article as a panel, configured from

```
structure->content type->article->manage display

```

The contextual link cogwheel is not appearing on the full content type display rendered through panels, whereas it is displayed on the teaser view, rendered on the site home page, also rendered through panels as a panel page. What might be causing the error? Is there a workaround?

# Answer
> -2 votes
Please apply a patch from Impossible to set attributes on Panels panes on Drupal.org.

This is a patch to the module I believe will fix the problem you have.

---
Tags: 7, panels, navigation
---


# Question
Title: Using states in Drupal 7 form to provide 'select all' functionality
I'm trying to use this to achieve the functionality of having a checkbox that, when selected, causes a range of checkboxes to all be selected. I made the selectall box a separate form field, and it looks like this, and works not a lick:

```
$form['report_group']['selectall'] = array(
  '#type' => 'checkbox',
  '#default_value' => 0,
);

$form['report_group']['boxes'] = array(
  '#type' => 'checkboxes',
  '#options' => $boxes,
  '#states' => array(
    'checked' => array(
      ':input[name="report_group[selectall]"]' => array('checked' => TRUE),
    ),
  ),

```

# Answer
> 0 votes
I don't think the "checked" property works with the "checkboxes" form control (or if I does I know how to use it!)

As a work around use the checkbox type instead:

```
$form['report_group']['selectall'] = array(
  '#title' => 'Check All',
  '#type' => 'checkbox',
  '#default_value' => 0,
);

$boxes = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five');

foreach($boxes as $key => $val) {

  $form['report_group']['box_'.$key] = array(
    '#type' => 'checkbox',
    '#title' => $val,
    '#return_value' => $key,
    '#states' => array(
      'checked' => array(
        ':input[name="selectall"]' => array('checked' => TRUE),
      ),
    ),
  );
}

```

Your selector was also wrong. This is a jQuery selector so I find it easiest to use firebug to figure out what it should be and test if it's working.

---
Tags: forms
---


title: How to create question/answer form?

text:
# Question
Title: How to create question/answer form?
I need to create a textarea (textfield) that every user who visits the site be able to ask his/her question via this textarea (textfield), and then the content managers will answer the question and both answer/question will be published via a view.

I don't know how to implement such thing. creating a page which only shows the question textarea needs a module to create its form but how does this form can act as a field in a content type?!

thanks.

# Answer
You could use the answers module which creates the Question and Answers System for you.

But for the requirement you want, you could create a Content Type which is not published by default, and has Body Field as the Question asked by the User. For the answers to the question another textarea field can be added via Field UI. When the answers are given you can make the node published. Here you can add checkbox to let the user know his question has been answered.

You can then use Field Permissions module to hide the new answer field from the user.
> 2 votes

# Answer
How about creating a content type called QandA. This will have 2 fields - 1 called question and 1 called answer. Using the field\_permission module set it so only admins can fill in the answer. Then you could also use the entity\_relationship module to create a relationship between the user and the QandA if this is required so users can see *their* question (maybe in their profile).

Then using the rules module create a rule to add a new QandA when a user registers. At this point you can also set the relationship between the user and the QandA.

Admins can then have a custom view to show unanswered questions to allow them to work though the list.

Creating a view of questions and answers will then be easy as it will just involve showing one content type, filtered to only show QandA's with answers.
> 1 votes

---
Tags: forms, hooks, users
---


# Question
Title: Stripe_InvalidRequestError: You cannot use a Stripe token more than once
I'm trying to integrate Stripe’s Checkout and PHP into a simple module and I've got the following:

```
Stripe::setApiKey($stripe['secret_key']);

if (!empty($form_state['input'])) {
  $input = $form_state['input'];
  // Create a Customer
  $customer = Stripe_Customer::create(array(
    "card" => $input['stripeToken'],
    "email" => $input['stripeEmail'],
  ));

  // Charge the Customer instead of the card
  $charge = Stripe_Charge::create(array(
    "amount" => 4900,
    "currency" => "GBP",
    "customer" => $customer->id,
  ));
}
else {
  $data = array(
    "data-key" => $stripe['publishable_key'],
    "data-name" => variable_get("site_name", ""),
    "data-amount" => 4900,
    "data-currency" => "GBP",
  );

  $form['stripe'] = array(
    '#markup' => '<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" ' . join(' ', array_map(function($sKey) use ($data) {
      if (is_bool($data[$sKey])) {
        return $data[$sKey] ? $sKey : '';
      }
      return $sKey . '="' . $data[$sKey] . '"';
    }, array_keys($data))) . '></script>'
  );
}

```

Everything is working great so far apart from when I call $charge = Stripe\_Charge::create I get an error returned *Stripe\_InvalidRequestError: You cannot use a Stripe token more than once* but I don't understand how my code would be using the token more than once.

Although I get this error, in my dashboard at Stripe the payment is successfully processed, I'm using the Stripe API Client Library for PHP

# Answer
> 0 votes
OK I have figured it out, when the form code is running, it runs multiple times, to stop it I added a variable to $form\_state so the top of my code above becomes:

```
Stripe::setApiKey($stripe['secret_key']);

if (!empty($form_state['input']) && !isset($form_state['processed'])) {
  $form_state['processed'] = TRUE;

```

---
Tags: forms
---


# Question
Title: Rule set username after changed user email
I need an email registration system only in my drupal site.

I installed the module email\_registration and I created a module like this http://www.grasmash.com/article/using-your-email-address-your-drupal-username to set the username like the own email address.

Now my user has: name: fra@ore.com email: fra@ore.com But if the user changes is email address the username doesn't update. So if fra@ore.com changes his email to fra@ore2.com the username remain the same.

I tried to update the username by the Set a data value of Rules module After updating an existing profile but I dont know how set this action... Can you help me??

# Answer
You can look at this: https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_save/7

It will run after a user is created and if a user is edited. You can update the data as required.
> 0 votes

---
Tags: rules, users
---


# Question
Title: if I change site with local devdesktop it will not change anything with my live site?
I am new so bare with me! I am using a local acquia dev desktop 2 beta and want to make sure if I play around with it in drupal it will not change anything with my live site.

We do not host with acquia so I am sure it wont but I want to make sure anything I do does not translate to the mysql?

Again, I am apologize if this is a newbie question. Thanks.

# Answer
> 1 votes
Normally there is nothing to worry about. Some advices:

1. make sure that you are working on a local database and not producction.
2. Sanitize your database (users + passwords) or use reroute email to ensure that your site does not send emails from your local environment.

```
drush sanitize

```

> Reroute email: This module intercepts all outgoing emails from a Drupal site and reroutes them to a predefined configurable email address.
>
> This is useful in case where you do not want email sent from a Drupal site to reach the users. For example, if you copy a live site to a test site for the purpose of development, and you do not want any email sent to real users of the original site. Or you want to check the emails sent for uniform formatting, footers, ...etc.

---
Tags: database, acquia-dev-desktop
---


# Question
Title: My data content type does not appear as an option on my 'Add content' page
I have just created a new content type for my site, and wrote a few rules which act when an instance of that type is created. I went to create a few test instances of my new content type and noticed that it did not appear on that 'Add content' screen (mysite/node/add.) 'No problem' I thought, 'I'll just go to mysite/node/add/new\_type.' However, this failed to work too. The page loaded as as the url I submitted, but it appeared to be a duplicate of mysite/node/add. This is a problem because I can not add new content of this type.

I have a few other content type that do not appear on the mysite/node/add, but this was never problematic because I could still create new content of that type by visiting mysite/node/add/some\_other\_type.

I found that I can create new instances of this content type using Development: Generate Content (and the rules work just fine.) Still, I have yet to figure out why I cant get to the creation page manually. What could be causing this?

Edit ===================================

A newly added content type (just called test with no other changes or fields added) does not appear either (even with all permissions set to 'registered user').

# Answer
> 1 votes
It sounds like there is a problem with your menu system.

This is an (educated) guess but rebuilding your menus may help.

Install the devel module and then click on **Rebuild menus**:

# Answer
> 1 votes
After searching for a few hours, I found this post about a another developer that was experiencing this problem:

http://www.drupalgardens.com/content/new-content-type-not-appearing-add-content

The problem was related to a url that was being used by two different pages. This was causing the navigation menu to break down and only display a limited number of links. Her problem was resolved by renaming one of the urls that her views were creating.

I began to review all of the modules that were creating page links. I was using the 'empty page' module to create pages for my blocks and something was causing this module to generate errors. After removing it, the content creation menu links came back and the node creation pages became accessible.

---
Tags: 7, nodes
---


# Question
Title: Should I activate feature modules on my dev site?
I have installed the features module on my dev site. I am using it to store newly developed site functionality within new modules. I then install the modules on my live site.

I was wondering, should I activate these modules on my dev site? I am considering not doing this, because the functionality already exists on the dev site Activating the new features modules (that are created by functions) seems a bit redundant and even a little dangerous.

# Answer
> 3 votes
Features allows you to assure that the configuration that is described in code (in the features that you the module Features generates) is the current configuration in the DB. If you enable a feature that describes exactly the same configuration that you have in your site no changes are made.

Features is a powerfull way to move configuration between sites (dev, stg and live, between devs sites, etc). I don't understand exactly your setup, but I think you can enable them.

Features help you to know if some configuration change needs to be moved to producton. For example: you start with your features in a clean state (default state) in production and in your dev site. If you make a configuration change in your dev site implementing a new functionality you can see that the feature is in overwritten state: this means that you shold take this configuration change to production when new code is deployed. You can do it by hand, or regenerating the feature and deploying it to production.

# Answer
> 2 votes
Later on, you will want to update your feature, ideally via a drush command (drush fu), and that requires that the feature be enabled.

So yes, **do enable** it, having the settings allready in database doesnt pose a problem.

---
Tags: 7, features
---


# Question
Title: Got error message from Deleting Vocabulary
I'm trying to delete one of the Taxonomy's Vocabulary on Drupal 7.26. It would not allow me to delete and turn out an error message. How can I fix this and be able to delete Vocabulary?

> Fatal error: Call to undefined function drpual\_static\_reset() in /sites/all/modules/metatag/metatag.module on line 271

# Answer
Please see this post https://drupal.org/node/1719600 as it explains that the function has a typo. I would recommend updating to the latest version of the metatag module.
> 2 votes

---
Tags: taxonomy-terms
---


title: Assign taxonomy term to a view

text:
# Question
Title: Assign taxonomy term to a view
I would like to set a taxonomy for a view. I have Taxonomy called "CMS Templates" and under that I have "Drupal". I would like to set Drupal for a view which is displaying Drupal templates but I don't know how. I tried to put field taxonomy and all taxonomies but I don't have possibility to set it there.

# Answer
> 0 votes
You can easily output taxonomy term based information by going to admin/structure/views/add and under "Show" choose "Taxonomy terms".

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


# Question
Title: Why does field_get_items() sometimes return "blank"
`field_get_items('node', $my_node_object, 'field_[fieldname]')` is returning the string 'blank'. Not an array, not NULL, but a string reading 'blank'. It's causing errors in media\_wysiwyg module. What causes this? How can I fix it?

# Answer
> 1 votes
Reading the function's source code it seems that the only way to return 'blank' is when the field's value for the selected langcode is actually 'blank':

https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field\_get\_items/7

I suggest you to use XDdebug to check the node\_object value just before this function is called. You can also use a dirty-and-quick trick: edit the code function and add a dpm (but remember to revert it!). But with XDebug you really can see where that 'blank' value comes from.

---
Tags: entities, media, wysiwyg
---


# Question
Title: Is there a way to trigger an image crop dynamically?
I have a Flag setup for an image content type which allows users to Flag an image that they want to be their avatar/user picture. I also have a View which displays this flagged image.

When a user clicks this Flag I would like to be able to trigger a crop (where the user is able to select the cropping area manually) so that a copy of the image can be made and referenced in a separate avatar gallery, without effecting the original image which will stay in it's gallery uncropped. There are several cropping solutions for Drupal 7 however is there a way that cropping can be triggered dynamically as in my example, perhaps via Rules or another way?

# Answer
> 0 votes
A module that you want to start looking at is Imagefield Crop. Details from project page:

> When the user uploads an image it is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking "preview" or "submit", the image is cropped and the result is saved instead of the original image.
>
> Features \- Seamless, intuitive cropping, almost like using a desktop photo editing app \- All major browsers supported \- Dynamic preview - you see how your crop will look like, in real time! \- Original image is saved for recropping. \- No matter what resolution the cropping area is, the original image is used for cropping (for highest quality) \- The sizes of the cropping area, cropping box and resulting image can be controlled by the administrator

The problem with using this module however is that it only works with the imagefield module and the user picture.

If you already have a bunch of users that uploaded avatars using Drupal's core functionality then it would be best to rip the ImageField Crop module apart and see how it can be integrated into Drupal's user avatars.

If you have yet to have any users upload avatars then you can follow these steps....

1. Create a user field called "Pic" and use the "Image with cropping" widget on it.
2. When the user flags the image, you can redirect to the user edit page while passing the fid of the flagged image.
3. After that you can use hook\_form\_alter to chuck in the fid, uri and fileurl from the passed fid as the '#default\_value' of the newly created "Pic" field from step 1.

The annoying thing about this solution is that you will have to modify user-picture.tpl.php to use your custom created field over the default avatar picture.

---
Tags: users, rules, flags, media
---


# Question
Title: How can I apply changes to user permissions across several sites?
I am using Drupal 7, we have a total of 99 different instances of pretty much the same site. All sites have the user roles of adm\_core and mgr\_center.

We are currently using drush and puppet to apply changes/updates across sites.

What I'm wondering is if there is a drush command that I can use to just give adm\_core the same privileges as mgr\_center?

If not does anyone have suggestions on the best method to do this across all sites short of going and changing permissions site-by-site?

# Answer
I found this snippet for copying permissions from one role to another, which you can easily rewrite to a `drush sql` command and integrate in your current workflow.
> 0 votes

# Answer
You may write a little PHP script utilizing drupal core functions to add certain permissions to those two roles and execute that script with drush scr on all 99 sites.
> 0 votes

---
Tags: users, drush
---


# Question
Title: How to check if a user has privs to access a node in organic groups
Does someone know what function within Organic Groups I can use to check if a user (the signed in user) as access to a given node? Do you have an example?

Thanks

# Answer
> 1 votes
The same function you should always use in any context: `node_access('view', $node);`

Modules are expected to use node access hooks to implement access control, so this function will consider all of the modules that may grant or remove access to the given $node object.

---
Tags: organic-groups
---


title: How do you search for duplicate urls?

text:
# Question
Title: How do you search for duplicate urls?
I have a problem with my navigation menu which may be related to a duplicate url. A view or or other module may be creating the same url and a different view/module. At this point, I do not know what the duplicate url is. How would I search my site for duplicate or conflicting urls? is there a module for that?

Would XML sitemap list duplicate urls?

# Answer
> 2 votes
You can use the PHP function `menu_get_item('path/in/question')` to determine more about what module is responding to the url.

If the path is an alias, you may need to use `drupal_get_normal_path($alias)`.

So if you use drush, you might run

`drush ev "print_r(menu_get_item(drupal_get_normal_path('path/in/question'))"`

That should return an array, which will likely have a 'page callback' element which will tell you the function (and hence, the module) that is handling that url.

---
Tags: 7, uri
---


# Question
Title: place own block from module to the left of the screen
This is the first time i'm making a module for drupal. In my module I create a block with a vertical menu in it. I would like to place the block glued to the left of the screen (out the wrapper).

So far i tried to make my own region in the module (which worked) but I can't get the region to appear in the website. I know i would have to do this in the page.tpl.php from the theme, but I'm trying to do this through my module only.

So is there a way to make the website take the region? Is there a other/better way to place the block to the left?

thanks in advance! TL

# Answer
> 1 votes
**You have to edit your theme's template to create a new region.**

You will need to add something like:

```
<?php print render($page['your_region']); ?>

```

Without this nothing in that region will ever get rendered.

You will also need to add it to your themes .info file.

For more information see: How do I create custom regions in a theme?

# Answer
> 0 votes
Making sure the region is in the .info file, and rendering should work to get it displayed.

You could put the block in whatever existing region you alrdy have, and 'pull it out' using purely CSS, using `position:absolute` and go from there.

Or, still use a separate region, and combine the output of that region, with the output of a 'default' region you have, using code.

While both work, you should avoid them, and stick to adding another custom region. Then make sure your template puts it in the right place. If you really don't want to touch the theme, maybe you should think of working with a sub-theme instead. You'll still need to edit the templates to get the additional regions, but at least you'll have the original theme next to you for reference ( or whatever the reason is you don't want to change your theme files ). Read up on sub-themes here

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


# Question
Title: How do I use a theme hook suggestion in template.php?
How do I convert a theme hook suggestion into a function in template.php?

Here is an example I pulled using TEMPLATE\_preprocess\_field() with dpm().

What would I name my function in template.php to utilize `field__field_video_virtual_tour__basic_drealty_listing`, and where can I find the default theme function for a text field to use?

# Answer
> 2 votes
The default theme function for all fields is (wait for it), `theme_field()`. You can copy this function into your own theme, and rename it to `MYTHEME_field()`, either to alter or to refer to as reference.

You would then name your specific version `MYTHEME_field__field_video_virtual_tour__basic_drealty_listing()`. Note the two underscores separating the parts.

For reference, the standard suggestions are

* `MYTHEME_field__FIELDNAME__CONTENTTYPE()`
* `MYTHEME_field__CONTENTTYPE()`
* `MYTHEME_field__FIELDNAME()`
* `MYTHEME_field()`

Also remember, these are really just to wrap your elements with some HTML. If you want to change the way the element itself gets rendered out, you should really make a field formatter.

---
Tags: 7, theming
---


# Question
Title: D7: file_create_url() usable in node.tpl.php?
Can you use `file_create_url()` inside node.tpl.php? Should I assume you can only use it in the template.php?

```
$img_src = render($content['field_image']);
$bgimage = file_create_url($img_src);

```

Using the following code, I am only getting `public://science-of-rock_background.png` from `$img_src`. Is there any reason why it would be blank?

```
print $img_src;
print $bgimage;

```

---

**Edit made to avoid confusion:**

In my tpl page for this field I am generating the uri.

**field--field\_image.tpl.php**

```
<?php foreach ($items as $delta => $item) : ?>
  <?php
  print $item['#item']['uri'];
  ?>
<?php endforeach; ?>

```

# Answer
> 1 votes
I'd first suggest to dpm($img\_src) -- You'll need the devel module for that to work. See what is actually inside that field. It's odd that it would be a file path though.

I'd never put logic like that inside a template file anyway. Use a preprocess function anyway:

```
template_preprocess_node(&$variables) {

}

```

inside template.php (replace template with your theme name)

# Answer
> 2 votes
`file_create_url` takes a uri, such as `public://science-of-rock_background.png`

The revised:

`$img_src = $content['field_image'];
$bgimage = file_create_url($img_src);`

Would work if your field is only returning the URI.

And, for best practices, should set that up in preprocess\_node, otherwise will work in node.tpl.php

# Answer
> 0 votes
The error is that `render()` returns HTML output, while `file_create_url()` is expecting a URI or a file path. In node.tpl.php, the content of a field is available as variable; so, the field you are trying to access is available as `$field_image`, basing on the following note.

> Field variables: for each field instance attached to the node a corresponding variable is defined; for example, `$node->body` becomes `$body`. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, `$node->body['en']`, thus overriding any language negotiation rule that was previously applied.

---
Tags: 7, nodes
---


# Question
Title: Blog posts are being listed under content
I know nothing about Drupal, trying to help a friend out.

Right now blog posts are being listed under `/content` \[`site.com/content/blog-post-title`\] instead of `/blog`.

I'm trying to figure out where to look to figure out why.

# Answer
> 0 votes
The fact that `blog-post-title` appears suggests that the module **PathAuto** is somehow involved. Try to disable that module (If you're on Drupal 7, navigate to *Home » Administration » Modules*, locate **PathAuto** and remove its tickmark, then press "Save configuration" and clear all caches.)

If the blog posts now appear under `/blog`, you know why.

After you've etablished that **PathAuto** is indeed resposible, you can re-enable the module (all its settings will be left intact), and you can then proceed to change its settings to put blog posts in the place you want them.

# Answer
> 0 votes
You have to specify the path to the content you create. It's under the "URL path setting" "vertical" tab on each node. However, this can be automated using Pathauto.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.

After installing Pathauto you can manage your URL aliases at:
Configuration \> Search and metadata \> URL aliases \> Patterns
(`/admin/config/search/path/patterns`).

Cheers,

---
Tags: nodes
---


# Question
Title: How to save single value from a select field?
I have webform module with multiselect field (Checkbox) User can select all the three.

> PR|Print Required
> DP|Digital Print Required
> TP|Print has been taken

**If user selects the last option then, only that option must be saved after submitting even if the other options are selected**. If other two options are selected then as usual those options should be saved.

*In General, If the user selects the first two options, it should accept the first two options. If user selects third option, then it should save the third option not other two options(If user selects). Example: If user selects all three options, then it should save only the last option.If user selects the last option i.e., Print has been taken, then it should save that irrespective of other selections.*

# Answer
> 2 votes
I would use jQuery to deactivate and uncheck the other two checkboxes when the third has been checked. If they uncheck the third, they will all become active.

Your Drupal form will look something like this:

```
<div class="form-checkboxes" id="edit-field-terms-und">
<div class="form-item form-type-checkbox form-item-field-terms-und-pr">
    <input type="checkbox" class="form-checkbox" value="pr" name="field_terms[und][pr]" id="edit-field-terms-und-pr">  <label for="edit-field-terms-und-pr" class="option">Print Required</label>
</div>
<div class="form-item form-type-checkbox form-item-field-terms-und-dp">
    <input type="checkbox" class="form-checkbox" value="dp" name="field_terms[und][dp]" id="edit-field-terms-und-dp">  <label for="edit-field-terms-und-dp" class="option">Digital Print Required</label>
</div>
<div class="form-item form-type-checkbox form-item-field-terms-und-tp">
    <input type="checkbox" class="form-checkbox" value="tp" name="field_terms[und][tp]" id="edit-field-terms-und-tp">  <label for="edit-field-terms-und-tp" class="option">Print has been taken</label>
</div>
</div>

```

jQuery code would be something like this:

```
(function($) {
$(document).ready(function() {

    $("#edit-field-terms-und-tp").click(function() {
        if($(this).is(':checked')) {
            $('#edit-field-terms-und-pr, #edit-field-terms-und-dp').attr('disabled', true).prop('checked', false );
        } else {
            $('#edit-field-terms-und-pr, #edit-field-terms-und-dp').removeAttr('disabled');
        }
    });

});
})(jQuery);

```

Haven't tested it, but it should work.

---
Tags: forms, webforms
---


title: Importing shapefiles/kml

text:
# Question
Title: Importing shapefiles/kml
I need to add support for importing either kml file or shapefiles, preferably using feeds. The idea is that each record relates to a single node, and the file uploaded could contain hundreds of new nodes. I've tried Spatial Tools, but the feeds import only works in Drupal 6. I've also tried GDAL, but it requires the php gdal extension, which has to be compiled. I'm using windows (not by choice!) and don't have easy access to the compiler and tools necessary, so this is not really an option. Does anyone know of a way to get either of these to work, or if there is a better way to support importing spatial data?

# Answer
> 0 votes
Not sure but this might help: https://drupal.org/node/1980360 \- Importing KML file data into GeoField field instance

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


# Question
Title: Why doesn't composer install drush on $HOME/bin directory?
I'm trying to learn to to use `drush`.

I installed composer to my `$HOME/bin/directory`:

```
$ ls ~/bin
composer  composer.phar  subl  sublime  sublime_config.sh  sublime_text

```

Then I tried to install drush globally:

```
$ composer global require drush/drush:dev-master
Changed current directory to /home/nnieto/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.1.5)
    Downloading: 100%

  - Installing symfony/yaml (v2.2.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Downloading: 100%

  - Installing drush/drush (dev-master 31fa220)
    Cloning 31fa220c9ee33a250d135ad0d65b5b6c92c6c188

pear/console_table suggests installing pear/Console_Color (>=0.0.4)
drush/drush suggests installing youngj/httpserver (dev-master#41dd2b7 as 1.0.1)
Writing lock file
Generating autoload files

```

I expected to find a drush file on `~/bin`, but instead I got a nope from Linux:

```
[nnieto@localhost ~]$ ls ~/bin
composer  composer.phar

```

What am I doing wrong?

# Answer
Composer downloads things and puts them where you (read: your composer/project settings) tells them to go; or in the default location if you haven't specified. It won't assume you want to link anything from the downloaded library into /usr/bin, though this could theoretically be done through a `post-install-cmd` in your composer.json file.

If you install something globally you'll find it in ~/.composer/vendor/ (the Drush executable will probably be in ~/.composer/vendor/bin/drush).

You've probably missed this important step from the instructions to install Drush via Composer:

> Make sure Composer's global bin directory is on the system PATH

Once Composer's global bin path is in your system path, the `drush` command will start working immediately.
> 6 votes

---
Tags: drush, composer
---


title: Display a Menu and Submenu as tabs

text:
# Question
Title: Display a Menu and Submenu as tabs
I have a simple 2 level menu like this:

```
Category1
   Link1a
   Link1b
   Link1c
Category2
   Link2a
   Link2b
   Link2c

```

I'd like to create a tabbed Menu/Submenu for this: When Category1 or any of it's sublinks are selected (clicked) Category1 is "active" and its links are shown. Category2 is visible but its links are not:

tabbed menu http://xooplate.com/assets/template/9845/p16qeq63ber8n2agm6hf8p2kb9-details.jpg (random example from the web)

Can anybody point me in the right direction?

# Answer
Simply use the quick tab module. It exactly do same thing.
> 0 votes

---
Tags: routes
---


# Question
Title: Views relatonship with multi value field - and views distinct
I have a View that shows a list of Classes (nodes) and the relevant Teachers (Users) on my system. It is designed to show one class per table row and then a comma seperated list of the users who belong to this class.

As my "relationship" in the View is a user reference field (multi valued) then I get a list of Classes and teachers names next to them (as this uses the relationship to find Profile2 fields of First Name, Surname etc). But it causes duplicate nodes. I have tried using Views Distinct but you can see what happens below. I can get rid of the duplicates but it doesn't give any way for me to have a comman seperated list of my rewrote ouput of Users.

In my example there are 3 users referencing "Year 2" but when I try to eliminate the duplicates - it only shows one teacher next to that class. Is there a way around this duplicate, multi valued, relationship issue in Views?

# Answer
use group-by class so it will show you unique class name with teachers for the class
> 0 votes

---
Tags: views, nodes
---


# Question
Title: recursive entity reference in a view (tree view?)
I have content type with entity reference to node of same content type. And I would like to show the nested references in the node view. Sort of a tree view.

How could I accomplish that?

I guess I need a view and a view field? But even not yet sure how to create a view which does recursive relationship...

It is for managing software dependencies and releases, there are libraries (=content type) dependent on 1:n libraries.

# Answer
> 4 votes
That can be accomplished with a custom module (great question by the way)...

First define a function to handle the whole process:

```
function make_tree() {

  // This is the nid of the root of our tree - could be passed in as an argument
  // instead of being static.
  $root_nid = 110;

  // First build an array with 3 fields - id, parent_id, title.
  $data = array();

  // We call add row once and then it's called resursivly to fetch each child.
  add_row($root_nid, null, $data);

  // Here we can inspect our data in it's flat form.
  //dpm($data);

  // Now turn the flat data into a multi-dimensional array.
  $tree = build_tree($data);

  // And inspect our tree.
  dpm($tree);

  // Could return the tree here or do anything we want with it...

}

```

Then define the function to build the flat array of data:

```
function add_row($nid, $parent_nid, &$data) {

  $node = node_load($nid);

  $data[$node->nid] = array(
    'id' => $node->nid,
    'parent_id' => $parent_nid,
    'title' => $node->title,
  );

  if(isset($node->field_dependent[LANGUAGE_NONE])) {
    // Now loop childeren to add rows for them too.
    // My entity relationship field is called dependent but rename here as
    // necesary.
    foreach($node->field_dependent[LANGUAGE_NONE] as $child) {
      add_row($child['target_id'], $node->nid, $data);
    }
  }

}

```

Once this step has been completed the `$data` array will look like this.

And then finally the function to turn the flat array into a multi-dimensional one (credit to this answer for this step):

```
function build_tree(array $elements, $parentId = 0) {
    $branch = array();
    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = build_tree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }
    return $branch;
}

```

I've just tested this and my final array looks like this.

---
Tags: views, entities
---


# Question
Title: Tablefield output in No Results behaviour
I have achieved to display the raw value of this tablefield in views - Global no results but not in the table format.

I have this in PHP-format in the **Global - No results behaviour** in views.

```
$view = views_get_current_view();
$node = node_load( $view->args[0] );
$table = $node->field_modal_parameters_tabel[und][0]['value'];
print $table;

```

This gives me this.

```
a:34:{s:8:"cell_0_0";s:1:"N";s:8:"cell_0_1";s:21:"nat. freq. meas. [Hz]";s:8:"cell_0_2";s:22:"&xij";s:8:"cell_0_3";s:1:"N";s:8:"cell_0_4";s:21:"nat. freq. calc. [Hz]";s:8:"cell_0_5";s:17:"damping calc. [%]";s:8:"cell_0_6";s:7:"MAC [-]";s:8:"cell_0_7"; ...

```

How can I display the table format?

# Answer
> 1 votes
Got the answer!!

```
<?php
$view = views_get_current_view();
$node = node_load( $view->args[0] );
$table_data = field_get_items('node', $node, 'field_modal_parameters_tabel');
$output = field_view_value('node', $node, 'field_modal_parameters_tabel', $table_data[0]);
print $output['#markup'];
?>

```

---
Tags: views
---


# Question
Title: How to count date difference excluding weekend and holidays in Computed Field
How to count date difference excluding weekend and holidays?

I should count the number of days between two dates but the weekends and holidays must be excluded from the counting. I used Computed Field.

```
$start_date_value = array_pop(field_get_items($entity_type, $entity, 'field_date_from'));

$end_date_value = array_pop(field_get_items($entity_type, $entity, 'field_date_to'));

$start_date = new DateObject($start_date_value['value'], '');

$end_date = new DateObject($end_date_value['value'], '');

$entity_field[0]['value'] =$start_date->difference($end_date, 'days');

```

Here is my working code for counting the days.

# Answer
why would you try something like this,

create a variable array that contain all the Hollidays

```
$currentyear=the current year;
$holiday['01-01-'.$currentyear,other holiday,other holiday];

$result=$start_date->difference($end_date, 'days');
for(ctr=0;ctr=sizeof(holiday);ctr++;)
{
    if(holiday[ctr]>=start_date && holiday[ctr]<=end_date)
    temp++;

}
$result -= temp;

```
> 1 votes

# Answer
I think you'll find this answer helpful, though it's PHP only:

https://stackoverflow.com/questions/336127/calculate-business-days/19221403#19221403

So you should only need to input your `$start_date/$end_date` values in correct format and then also define the holidays.
> 0 votes

---
Tags: datetime, entities
---