# Question
Title: List groups own content and all non-group content on groups page
I building a site where some content (eg. news, events) that either belong a group (region) or not (national).

On the national part of the site I have a view in a block that presents all content filtered by type (news or events). No problem...

On the regional part(s) of the site I want to have a view that show all the news (or events) that is published by that region. This is no problem either. (OG contextual filter etc.)

But I also want to include all news that don´t belong to a region at all.... this part I can´t figure out.

What I want to happen (under the hood) in the SQL is this...

The WHERE-part that I get from Views:

```
WHERE ( ((og_membership_node.gid = '<gid>'))
  AND (( (node.status = '1') AND (node.type IN  ('news')) )) )

```

Change that to:

```
WHERE ( ((og_membership_node.gid = '<gid>') OR (og_membership_node.gid IS NULL))
  AND (( (node.status = '1') AND (node.type IN  ('news')) )) )

```

Perhaps hook\_views\_query\_alter() or hook\_views\_pre\_execute() can fix this...

# Answer
> 3 votes
Solved! I used hook\_views\_query\_alter().

```
function MY_MODULE_views_query_alter(&$view, &$query) {
  if($view->name == 'VIEW_NAME') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if (strpos($condition['field'], 'og_membership_node.gid') === 0) {
          $condition_group['conditions'][] = array(
            'field' => 'og_membership_node.gid',
            'value' => NULL,
            'operator' => 'is'
          );
          $condition_group['type'] = 'OR';
        }
      }
    }
  }
}

```

---
Tags: 7, organic-groups, views
---


title: Finding good minimalist base themes

text:
# Question
Title: Finding good minimalist base themes
I am working on a Drupal project and teaching myself the system as I go along. I am trying to find a minimalist theme to use as a base for developing this site. I don't want a framework, because I don't have time to learn that too. I really just want a minimalist theme that looks good out of the box, but that can be easily modified in basic ways.

In my experience so far, most Drupal themes are either overly designed, or completely lacking in any formatting whatsoever. In the WordPress world, there is (for example) something like Thesis, which looks good out of the box but also has lots of potential for modification. Another example would be WooThemes' Canvas. Is there anything similar in the Drupal world?

# Answer
> 1 votes
As you are looking for a Drupal base theme, I suggest you to take a look at Nucleus base theme from themebrain.com. Also on themebrain.com there are themes that match your requirement: TB Sirate or TB Simply (look good and can be easily modified in basic ways).

# Answer
> 5 votes
Zen is all right but after using it a while I ran into problems since it's not built on the grid system. I found Omega pretty amazing as a grid-based starter theme for Drupal 7 with a responsive option. The steep learning curve was worth it, and it provides great tools and help.

# Answer
> 1 votes
Personally, I find Corolla a very good theme to start with, and it is built on top of AdaptiveTheme,- a really good framework for creating your own subthemes.

# Answer
> 0 votes
The Zen theme is a pretty good starting point for designing your own theme. Unfortunately I can't compare it to Thesis or WooThemes because I'm unfamiliar with wordpress. Here is a link: http://drupal.org/project/zen

# Answer
> 0 votes
If you are interested in all the modern buzzwords (html5, responsive ...) :) then pony might be of interest to you. Its not on drupal org yet, but is rather lightweight, has some design and accomodates some of the new ideas.

# Answer
> 0 votes
I would also recommend Zen, but if you want a theme with lots of features, then I would also look at Sasson. It contains a CSS SASS compiler built in, responsive support, and support for HTML. It's also very quick to get going with, and you don't need to use any of the extra features.

# Answer
> 0 votes
You have hit on a philosophical difference between Wordpress and Drupal. In Wordpress "Theme" means look-and-feel. In Drupal Theming is much more structural, and you have to add the look-and-feel using css and your own images.

I moved from Wordpress to Drupal 6 or 7 years ago, and found that I liked the Zen theme. I fought with it a little bit to make it look like a wordpress theme with header images, and drop-shadows, but that was mostly CSS and a little bit of page-tpl.php

---
Tags: theming
---


# Question
Title: How do I load classes using the ctools plugin class loader?
Perhaps, the question should be how do I implement ctools plugins using classes to extend different types of an object? I can't find a simple explanation.

# Answer
mymodule.module:

```
<?php
/**
 * Implements hook_ctools_plugin_api().
 */
function mymodule_ctools_plugin_api() {
    list($module, $api) = func_get_args();

    if ($module == 'mymodule' && ($api == 'plugins')) {
        return array('version' => 1.0);
    }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function mymodule_ctools_plugin_type() {
    return array(
        'plugin_type' => array(
            'classes' => array('handler'),
        ),
    );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mymodule_ctools_plugin_directory($owner, $plugin_type) {
    if ($owner == 'mymodule') {
        return "plugins/$plugin_type";
    }
}

```

plugins/plugin\_type/example.inc:

```
<?php
$plugin = array(
    'title' => t('Example'),
    'handler' => array(
        'class' => 'ExamplePlugin',
    ),
);

```

plugins/plugin\_type/ExamplePlugin.class.inc:

```
<?php
class ExamplePlugin {
function __construct($plugin){

}
}

```

Anywhere:

```
<?php
// Get all available plugins
$plugins = ctools_get_plugins('mymodule', 'plugin_type');

// Load a specific plugin
ctools_include('plugins');
$plugin = ctools_get_plugins('mymodule', 'plugin_type', 'example');
$class_name = ctools_plugin_get_class($plugin, 'handler');
$example = new ExamplePlugin($plugin);

```
> 6 votes

---
Tags: chaos-tool-suite
---


# Question
Title: Some CSS and JS is not loading for anonymous users
I recently started working on an existing D7 site, which has its own custom theme. With this theme only, some CSS and JS files are not loaded at all for anonymous users. Logged in users dont have that problem. When I switch the theme to Garland for example, the CSS and JS files are loaded correctly for anonymous users.

The CSS or JS files are either coming from core, or from some contrib modules.

Where should I start looking?

# Answer
First of all you should find where the CSS or JS is being added, this being Drupal, there are tons of ways that this could happen.

if they're added using drupal\_add\_js and drupal\_add\_css (which they should be) you have to make sure that possible template differences beetween roles and permissions both print out the $styles and $scripts variables.

If the theme follows D7 standards there should be an html.tpl.php file somewhere (most likely the root) in the theme, that would be the best place to start looking. If that does not exist, try page.tpl.php.

Post your findings and it'll be easier for us to help you.
> 2 votes

# Answer
You might also want to make sure the old developer wasn't doing something funky in the template.php file (if there is one, it will be located in your custom themes directory).
> 0 votes

# Answer
This sounds like a caching issue. Clearing caches from drush does not always clear CSS caches because of permissions. Try clearing caches from the GUI and/or testing it without caching for anonymous users.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Altering the page title on a /node/add/ page from a custom module
I have a new content type I am developing that I am packaging using Features.

What I need to do is alter the page title for the node add page for this content type from the Features' `.module` file. I cannot see an appropriate module hook to do this.

# Answer
> 0 votes
I ended up using `drupal_set_title()` in `hook_form_alter()`

# Answer
> 0 votes
The node/add/... page is a form, so you could do it with a `hook_form_alter()`.

---
Tags: 6, hooks, features
---


# Question
Title: Stop User From Publishing an Event if the Start Date is Before a Certain Month Using Rules
I'm working on a development site that will not be launching for a few months. I'm looking to create a rule that will not allow a user to publish an event if the event's start date is prior to launch. I am using the date field in this content type.

How could I accomplish this with rules? Thanks!

# Answer
I'm not sure that Rules is required to do that.

I would rather use Field Validation module. It is able to configure complex validation rules for any field.

In its submodule called "Field validation extras" there's a validation rule that will help you, it's called "Date range2". You can set a specific minimum date according to your needs, and a far enough maximum date.
> 1 votes

---
Tags: rules, datetime
---


# Question
Title: control over what prints on first and second page of pdf
I am generating pdf using dompdf and my website is running on Drupal 6.
I have a requirement wherein I need to print part of my html on first page and some part on second page in some cases.
Also some part remains same for both the pages like header and footer, etc. How do I acheive that? Please help!

Thanks in advance!

# Answer
> 0 votes
I don't think it's possible to achieve that with dompdf. It's impossible to control the page flow when producing PDF files based on HTML pages.

I found an interesting module that has a completely different approach: Views PDF. It also has an administrative interface to compose your document.

Unfortunatly I did not test it myself yet, but it's scheduled for a new project in a couple of weeks.

---
Tags: 6, files
---


# Question
Title: Integrate core search block with search_api and Solr
Since search\_api does not rely on the core Search module, the search bar (Search Form block) isn't used. For a current project I want to use search\_api, but the wireframes require the search bar at the top of the page. The apachesolr module overrides that block so that it uses the Solr search instead of the core search when you specify that Solr is the default search. Is there a way with search\_api to enable the core Search Form block and have it use a specific search page? In addition, you would also need to be able to keep the core Search module from indexing everything into the db, since that partially defeats the purpose of using Solr, but I'm guessing I could just form\_alter that form (admin/config/search/settings) to add a 0 value.

Thanks.

# Answer
> 5 votes
Search API automatically provides you with a default search block for every search page you configure. Just place the block in the region you need it. (Disable core search altogether)

# Answer
> 6 votes
I think he/she means http://drupal.org/project/search\_api\_page provides search blocks automatically. You could also create view that provides that block.

You could also replace the core Search module with Search api + http://drupal.org/project/search\_api\_db.

---
Tags: search
---


# Question
Title: this hook_uninstall isn't deleting fields in my module!
I've trying to make a simple module that creates a node-type and adds a few custom fields to it with the Field API.

Here is my module's .install

Here is my module's .module

The module installs just fine. After changing some things in my hook\_install\_fields, I disabled the module and uninstalled. When I try to re-enable the module, drush prompts me that one of the fields already exists and is active. **My problem is that hook\_uninstall doesn't seem to be deleting the fields from the database.** If I manually delete the field tables from the database, I'm able to re-enable the module without error.

Can anyone point me in the right direction on this?

# Answer
> 2 votes
It looks like your uninstall hook is incorrectly named and not invoked.

Current (line 137):

```
function _customer_testimony_uninstall() {

```

Try change it to:

```
function customer_testimony_uninstall() {

```

(No underscore in the beginning)

---
Tags: 7, entities
---


title: db_select group by of union

text:
# Question
Title: db_select group by of union
I'm quite new to drupal ad I've some problem with parsing a query throught the API:

```
    SELECT t.pg,p.classe, sum(t.punti) AS punti, sum(t.vinte) AS vinte, sum(t.perse) AS perse, (sum(t.vinte)+sum(t.perse)) AS giocate
    FROM(
        SELECT sid, team_member_a_1 AS pg, punti_team_a AS punti, 1 AS vinte, 0 AS perse
        FROM `webform_views_unusual_arena__risultati_6` AS t1
        WHERE tipologia_risultato = 0
            AND vincente = 0
        UNION
        SELECT sid, team_member_a_2 AS pg, punti_team_a AS punti, 1 AS vinte, 0 AS perse
        FROM `webform_views_unusual_arena__risultati_6` AS t1
        WHERE tipologia_risultato = 0
            AND vincente = 0
    ) AS t
    JOIN webform_views_i_miei_pg_1 AS p ON t.pg = p.nome_pg
    GROUP BY pg

```

But I can't find any documentation about a subquery or how to add field like "1 AS vinte"

EDIT Thank's to Tenken this is the code I used.

```
$subquery_1 = db_select('webform_views_unusual_arena__risultati_6', 't')
    ->condition('t.tipologia_risultato', 0, '=')
    ->condition('t.vincente', 0,'=')
    ->fields('t', array('sid'));
$subquery_1->addExpression('team_member_a_1', 'pg');
$subquery_1->addExpression('punti_team_a', 'punti');
$subquery_1->addExpression(1, 'vinte');
$subquery_1->addExpression(0, 'perse');
$subquery_2 = db_select('webform_views_unusual_arena__risultati_6', 't')
    ->condition('t.tipologia_risultato', 0, '=')
    ->condition('t.vincente', 0,'=')
    ->fields('t', array('sid'));
$subquery_2->addExpression('team_member_a_2', 'pg');
$subquery_2->addExpression('punti_team_a', 'punti');
$subquery_2->addExpression(1, 'vinte');
$subquery_2->addExpression(0, 'perse');
$query = $subquery_1->union($subquery_2);

$query->addExpression('sum(vinte)', 'vinte');
$query->addExpression('sum(perse)', 'perse');
$query->addExpression('sum(punti)', 'punti');
$query->groupBy('pg');
$query->orderBy('punti', 'DESC');

```

Hope it will help someone else

# Answer
> 1 votes
See this WEALTH OF DOCUMENTATION on Dynamic Queries in D7 ... it will answer EVERYTHING :) .... in all seriousness :).

To add `SUM(blah) as foo` you want to add an SQL Expression to your Select clause with `addExpression()`.

To add `Group by COLNAME` you want to use `groupBy()` with your db\_selection, see group by docs.

---
Tags: database
---


title: Minus Userpoints for down votes

text:
# Question
Title: Minus Userpoints for down votes
I have configured Vote up/down module for voting. For every vote, content author will be awarded 5 points for up-vote, but i am facing problem for down votes! i can not understand how to minus userpoints for down-votes? Say, if a voter hit down vote then 3 point will be minus from userpoints!
**Installed Modules:**

1. Vote up/down
2. Userpoints
3. Voting API
4. Voting Rules
5. Rule module...

# Answer
> 1 votes
As I mentioned on this answer already: I guess one of your problems is to determine wether upvote insert rule or downvote insert rule was triggered - vote up/down is storing this in two separate voting sets. (I might be wrong here, when I am good for you).

Let's say it is just one vote set and there are minus votes. you would have to adjust the positive check in the condition to a negative points check. I had my rules still in the environment so I cloned them and did those changes:

(minus points will be probably just negative grants.)

```
Event: User votes on a Node

Condition: User has role(s)
Parameter: User: [vote:user], Roles: authenticated user

Condition: Check the value of the vote
Parameter: Vote: [vote], Operator: is lower than or equal to, Data value: 0

Action
Grant points to a user
Parameter: User: [vote:user], Points: -3, Points category: General, Operation: Insert, Moderate: Use the site default

```

Export:

```
{ "rules_substract_down_voter" : {
    "LABEL" : "substract down voter",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "IF" : [
      { "user_has_role" : { "account" : [ "vote:user" ], "roles" : { "value" : { "2" : "2" } } } },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "operator" : "\u003C=", "value" : "0" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-3",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "default"
        }
      }
    ]
  }
}

```

So there are still some things for you to check:

* does vote/up down use one or two rule sets?
* if it uses two, how to determine that in rules?
* if it's only one with negative votes than you're done.

---
Tags: rules, userpoints, rating
---


# Question
Title: Can I clear cache only for particular domain / URL?
I'm using domain module with several domains. With drush you can clear cache using cc command. I have only one database for all domains.

I'm wondering can I clear cache using only specific domain (with -l option) if I'm using same DB for all domains?

e.g: `$ drush -l http://www.example.com cc all`

# Answer
> 3 votes
With just core this is not possible. If you where to write your own cache backend then what you're asking for could be done. An example of a custom cache backend is http://drupal.org/project/adbc

---
Tags: caching, subsites
---


# Question
Title: Calculate the sum of two form fields with javascript?
Hello there i was wondering if anyone had the solution to a problem i am having with my Custom Module. I created a custom form a few days ago and i need two or more(4) field values to be added together and the sum to be output in another field(total).Please not i am using form\_panels here s snippet of how the fields are built.

```
$form['Contract']['twelfth'] = array(
 '#type' => 'textfield',
 '#title' => t('Plus FEE of:'),
 '#size' => 40,
 '#field_prefix' => "$",
 '#form_panel_row' => 7,
 '#form_panel_col' => 1
);
$form['Contract']['thirteenth'] = array(
 '#type' => 'textfield',
 '#title' => t('For a OTHER PRICE of:'),
 '#size' => 30,
 '#field_prefix' => "$",
 '#form_panel_row' => 7,
 '#form_panel_col' => 3
);
$form['Contract']['fourteenth'] = array(
 '#type' => 'textfield',
 '#title' => t('For a TOTAL PRICE of:'),
 '#size' => 40,
 '#default_value' => "",
 '#field_prefix' => "$",
 '#form_panel_row' => 8,
 '#form_panel_col' => 1
 );

```

now how can i insert Jquery or Javascipt into this form to calculate those two fields together?

# Answer
**Replace** your code to next:

```
<?php
  $form['Contract']['twelfth'] = array(
   '#type' => 'textfield',
   '#title' => t('Plus FEE of:'),
   '#size' => 40,
   '#field_prefix' => "$",
   '#form_panel_row' => 7,
   '#form_panel_col' => 1,
   '#attributes' => array(
      'class' => array('summable'),
    ),
  );
  $form['Contract']['thirteenth'] = array(
   '#type' => 'textfield',
   '#title' => t('For a OTHER PRICE of:'),
   '#size' => 30,
   '#field_prefix' => "$",
   '#form_panel_row' => 7,
   '#form_panel_col' => 3
   '#attributes' => array(
      'class' => array('summable'),
    ),
  );
  $form['Contract']['fourteenth'] = array(
   '#type' => 'textfield',
   '#title' => t('For a TOTAL PRICE of:'),
   '#size' => 40,
   '#default_value' => "",
   '#field_prefix' => "$",
   '#form_panel_row' => 8,
   '#form_panel_col' => 1
   '#attributes' => array(
      'id' => 'totalsum',
    ),
    '#js' => array(drupal_get_path('module', 'YOURCUSTOMMODULE') . '/js/custom.js'),
   );
?>

```

Don't forget rename YOURCUSTOMMODULE to your module name.
Create custom.js in your module path/js folder:
**custom.js:**

```
(function ($) {

Drupal.behaviors.custom = {
  attach: function (context) {
    $('input.summable').keyup(function() {
      var sum = 0;
      $('input.summable').each(function() { sum += parseFloat(this.value); });
      $('#totalsum').val(sum);
    });
  }
};

})(jQuery);

```

p.s. **Don't forget** add summing code for inputs in submit function of your form in drupal module, since user can disable JS in browser.
> 1 votes

---
Tags: forms, javascript
---


title: Taxonomy terms as numbers?

text:
# Question
Title: Taxonomy terms as numbers?
Creating real estate website, i have a lot of exposed filters. For year when the object is built i have number field which in views is as exposed filter. When user makes input he puts year 1961 for example.

User searching in exposed filter writes 1961 and filter is set up like "equal or higher" so he gets all objects made 1961 and higher. Works fine.

But i have a problem with floors. For floors i have vocabulary: ground floor 1 2 3 4 etc.. attic

I cant use number field because of ground floor and attic so i had to use taxonomy. But now i cant use equal or higer as exposed filter so if user picks number 3 he only gets appartments with 3 floors.

# Answer
You could still use floors as numeric field, having numbers as keys and display output as needed.

Example of "List (integer)" values:

> ```
> -1|Basement
> 0|Ground floor
> 1|1
> 2|2
> 3|3
> 100|Attic
>
> ```

This would allow you the same logic for floors.

**EDIT:**
When selecting the field as a filter in Views you need to choose the `delta` value. It looks something like `Content: Floors (field_floors:delta)`. This will give you the integer filter options such as `Is greater than or equal to`.
> 3 votes

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


title: Change sort order of commerce orders

text:
# Question
Title: Change sort order of commerce orders
In admin of the Commerce module, Orders (Store \> Store Orders) are currently being sorted by '*order number*' and I think "alphabetically" because they have a strange order like so: 842, 754...287, 146, 1370

How would I go about changing the default view to sort by '*Created*' date to ensure that the latest orders are always at the top of the list?

# Answer
Visit next: Administration » Structure » Views » Orders (admin/structure/views/view/commerce\_orders/edit/admin\_page)

FORMAT \> Format:Table | Settings
Click Settings. In radios buttons select own default order field.
> 2 votes

---
Tags: 7, commerce
---


title: Views JSON output

text:
# Question
Title: Views JSON output
**Can anyone tell me how I can get plain JSON output with no surrounding HTML?**

I am using the Views and Views JSON modules to get my node data as JSON output.

The problem is my JSON output still comes embedded in the default Drupal theme. I set the default theme to stark hoping that I will not see any HTML in the output but that did not work.

My attempts to set the theme for the View did not work either.

I would appreciate any help. Thanks in advance.

# Answer
> 5 votes
* Go to the configuration of your Views display which produces the JSON output.
* Click on the **Settings** link of the **JSON data document format**.
* Make sure that ***Views API mode*** is **not enabled**. The description of this setting explains it all:

> Not using View API mode means the JSON gets output directly and the server ceases normal page processing. Using it means the server does not cease processing after outputting the JSON. This allows the Views API to be used with the view without having to prematurely terminate page processing.

# Answer
> 0 votes
Try the Views Datasource module. Here is a quote about it (from the module's project page):

> ... is a set of plugins for Drupal Views for rendering content in a number of shareable, reusable formats based on XML, JSON and XHTML. These formats allow content in a Drupal site to be easily used as data sources for Semantic Web clients and web mash-ups. Views Datasource plugins output content from node lists created in the Drupal Views interface in a variety of formats - XML data documents using schemas like OPML and Atom, RDF data documents using a vocabulary like FOAF, JSON data documents in a format like Exhibit JSON, and XHTML data documents using a microformat like hCard.
>
> Views Datasource can be thought of as a userland complement to the work going on in the Services and RDF APIs as a site operator only needs to know Views to be able to create datasources in the different formats.
>
> The project consists of 4 Views style plugins (and related row plugins):
>
> * views\_xml - Output as raw XML, OPML, and Atom;
> * views\_json - Output as Simile/Exhibit JSON, Canonical JSON, JSONP/JSON in script;
> * views\_rdf- Output as FOAF, SIOC, and DOAP;
> * views\_xhtml - Output as hCard, hCalendar, and Geo.

---
Tags: views, 8
---


title: Annotation on top of views text?

text:
# Question
Title: Annotation on top of views text?
Is there a contrib module out there that provides the text equivalent of image marker? E.g. I have views output and i want to place a post it on top of it.

The closest thing i've seen is the annotation field for Drupal 5 which is a bit outdated and i don't really know how it works.

# Answer
Try out Image Annotator module.

> The module allows you to annotate images, and works in combination with field\_collection. The module defines a new field called 'Image Annotator' that can be linked to an image field, so you can add multiple markers to an image.
> 0 votes

---
Tags: 7
---


# Question
Title: Getting a subset of items: Is it better to user PagerDefault and limit, or get'em'all and array_splice?
I want to pull some number of nodes out of the database for rendering and display. There are several ways to do this, two of which would be:

1. do a `db_select(...)->extend('PagerDefault');` and add a `->limit()` clause to specify the number of items to be returned.
2. do the `db_select()` without the `PagerDefault`, and use `array_slice` to get the desired number of items.

Any advice on the relative advantages of these, especially from a performance perspective? I've done a few informal tests that suggest about a 100% penalty for using `PagerDefault`, but I wouldn't want to claim these are definitive. Any recommendations?

# Answer
> 1 votes
Use `range()` instead:

```
db_select(...)->range(0, 10);

```

---
Tags: 7, database
---


# Question
Title: how to use user profile field information as biodata list
I have created a website where users can create their own account expanded by the profile2 module. By using it, users can enter all their information in created fields field like:

* name
* father's name
* mother's name
* education information
* etc

I want to display this information publically in table view where it's possible to search, sort and filter. How would it be possible to create something like that?

I know about content types and use content type in Views module.

# Answer
The easiest solution for this is use a view. If all your data in stored in the profiles you can simply list the profiles.
If you have several profiles or also need to show data from the user you need to create the view showing users and add a relationship to the profile(s) that have data you need to store.

* In the field section you can select fields you want to have displayed.
* In the format you can select the view to create a table, and in the settings you can select which columns should be sortable
* In filters you can create the filters you want the user to use for search and expose them. Fx add filter for the name field, expose it to users and select "contains", "starts with" or something similar to allow users to search. Beware some of the options can make the search a bit slow.

That should pretty much be it.
> 0 votes

# Answer
While creating the View,

> * create View (Show:User)
> * add relationship, (User:Profile); give the Identifier a unique name ie 'MainProfile'; select a single checkbox for 'Profile type', in my case 'Main profile';
> * add another relationship, (User:Profile); give the Identifier a unique name ie 'EducationProfile'; select the other checkbox for 'Profile type', in my case 'Education profile';
> * add Fields to view; select Profile2 field items; use Relationship dropdown in 'Configure field' to associate w/ correct relationship;
> 0 votes

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


title: How to add < to "allowed values list"?

text:
# Question
Title: How to add < to "allowed values list"?
I'm trying to add: 1|small (\<100) 2|etc ...

but it will only display "small (" as the first option. I've tried \< without success. Any way to display the \< ?

# Answer
Both `<`, `<` and also `<` works with a checkbox/radio widget. `<select>` doesn't allow html code for options.

In consecuence Drupal strip tags if the `<select>` widget is configured. This is done in \_options\_prepare\_options().

Short story: after some tests I've found that `small (< 100)` works (there's a whitespace between `<` and `100`), so it is not considered a tag.

I've done my tests with:

```
drush php-eval 'print strip_tags("small (< 100)") ."\n"'

```
> 2 votes

# Answer
This is infact possible by overriding the output using hook\_form\_alter and the Form API's #after\_build, all you need is a custom module.

```
function YOUR_MODULE_form_alter(&$form, $form_state, $form_id) {
  // Check for a particular content type's node form.

  if ($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'YOUR_CONTENT_TYPE_after_build';
  }
}

function YOUR_CONTENT_TYPE_after_build($form, &$form_state) {
  /**
   * Override the output of options which start at 1.
   * 0 is the "none selected" element (if it's a required field)-
   * Replace the text formatted just as it would be in the options textarea.
   * This will properly display the less than character.
   */

  $form['YOUR_FIELD']['und']['#options'][1] = '1|small (<100)';
  $form['YOUR_FIELD']['und']['#options'][2] = '2|small (<200)';

  return $form;
}

```
> 2 votes

---
Tags: 7
---


# Question
Title: Database query to check if current user has created a node reference?
I have a content type B with a node reference field (from url) pointing to content type A. When current user is at "node/add/typeB/nid\_of\_type A" page then how can i check the database if he has already created a B node for that A node?

I am trying the following code in my template php:

```
function theme_name_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'b_node_form') {
global $user;
if (arg(0) == 'node') {
 $nid = arg(3);
}
$query = db_select('node', 'n')
->condition('type', 'b', '=')
->condition('uid', $user->uid, '=');
$query->join('field_data_field_a_ref', 'ar', 'n.nid = ar.entity_id');
//field_a_ref is the node reference field from B to A type
$query->condition('field_a_ref_nid', $nid, '=');
$query->groupBy('ar.entity_id')->execute();
if(!empty($query)) {
drupal_goto('/');

    } else {

   }
  }
 }

```

But i get this error:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node n INNER JOIN field\_data\_field\_a\_ref ar ON n.nid = ar.entity\_id W' at line 1: SELECT FROM {node} n INNER JOIN {field\_data\_field\_a\_ref} ar ON n.nid = ar.entity\_id WHERE (type = :db\_condition\_placeholder\_0) AND (uid = :db\_condition\_placeholder\_1) AND (field\_a\_ref\_nid = :db\_condition\_placeholder\_2) GROUP BY ar.entity\_id; Array ( \[:db\_condition\_placeholder\_0\] =\> vote \[:db\_condition\_placeholder\_1\] =\> 1 \[:db\_condition\_placeholder\_2\] =\> 7 ) in theme\_name\_form\_alter() (line 109 of C:...\sites\all\themes\theme\_name\template.php).

Any help?

# Answer
Took a while to spot this, but you're not selecting any fields in the query so the SQL syntax here `SELECT FROM {node} n` is invalid.

Just select a field and you should be fine:

```
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', 'b', '=')
  ->condition('uid', $user->uid, '=');

```
> 1 votes

---
Tags: database, nodes
---


# Question
Title: Exposed view filter is not rendered properly
I have a view with a filter "Has taxonomy term", this filter is an exposed filter and is set to be a "Dropdown" and "Show Hierarchy"

The vocabulary has parents and children term (hierarchical).

The filter works fine but the html tags of the select dropdown are incorrect. The parent terms should be wrapped in instead of (see image 2)

Can I override this?

I trying to do it with **hook\_form\_alter()** but I see that the construction of the select itself is done by **drupal\_map\_assoc()** function. Then I see no way to do it? Can I put the value for '#options' in other way?

```
<?php
  $form['undergraduate']['school_country'] = array(
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(t('UK'), t('Other'))),
    '#title' => t('In what country is your college or university located?'),
  );
?>

```

# Answer
You could check if it is the top level (maybe by checking if it doesn't have a - at the start), and then add the attribute disabled (disabled="disabled")

You could also use this module: drupal.org/project/term\_reference\_tree. It has on option to only allow selection of the lowest term in the hierarchy. I used it on a site recently and it worked well.
> 1 votes

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


# Question
Title: Does Commerce Kickstart distribution include "advanced search" capabilities?
By default the Commerce Kickstart distribution include a **Search block**. Just wondering if this distribution include a feature to add advanced search capabilities.

The advanced search would allow the user to filter by taxonomies terms.

# Answer
> 2 votes
Commerce kickstart includes the commerce search API module. http://drupal.org/project/commerce\_search\_api

Automatically created Search API db server, if none is found. Auto-generated search index that includes all product display node types\* and related product data. Auto-generated facets for all node type categories and product attributes. Optional integration with Search API Ranges (allowing for a price slider, for example). Search API Filter class for product display node types\* (allowing for an index composed only of product displays) Facet API Filter class for removing facet items that do not change search results. Facet API Filter class for hiding certain facets on the initial search (so that product attribute facets are only shown after the initial search, for example).

---
Tags: commerce
---


title: Theming Form Fields: Alter all fields

text:
# Question
Title: Theming Form Fields: Alter all fields
In Drupal 7, you can put the following code in template.php to add the class 'vr-paragraphs' to the field called 'field\_title'

```
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
       $form['field_title']['#attributes']['class'][] = 'vr-paragraphs';
}

```

How can I modify this code to target all fields on the form and not just 'field\_title'.

Also, this code only adds the class to the form-wrapper part of the filed. How can I alter the label part?

Thanks for any help!

# Answer
When you need to find the child items present in a form, you need to use element\_children(), as Drupal functions like filter\_process\_format() do.

The reason is simple: In a Drupal form array, as well as in a render array, not all the keys are child items; those keys with a name that starts with # are properties. Consider, for example, the form returned from forum\_form\_forum(); if you loop through it with the following code, you would add values where you should not.

```
foreach($form as $key => $value) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

```

In fact, `$form['#submit']` is not a child item, nor is `$form['#theme']`. In particular, when your code will be executed for the last key, you would get a PHP error. `$form['#theme']` is a string, and `$form['#theme']['#attributes']` would select a character of that string, supposing that `'#attributes'` would be evaluated as the integer 0; even in that case, `$form['#theme']['#attributes']['class'][]` would not be a valid PHP construct.

The correct code would be the following one.

```
foreach(element_children($form) as $key) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

```
> 3 votes

# Answer
Implement a for loop over each form field to add the class. eg.

```
foreach(form as $key => $value){
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

```

You may have to check if it is actually a field though, maybe by checking if `$form[$key]['#title']` is set.

If I remember correctly, the label is usually taken from the '#title' of the field.
> -1 votes

---
Tags: 7, forms, theming
---


# Question
Title: Limit node reference to 1 per user & per referenced node, Drupal 7
I am trying to limit the creation of a node reference to 1 per user and per referenced node. More specifically: I have a content type named Debate and another one called Vote. Vote has a node reference field (from URL widget) called \*debate\_ref\* to the Debate type. What i'm trying to achieve is ***for each user and for each debate to have only one vote*** i.e. when a user tries to create a 2nd vote node on the same debate node then he will recieve a message saying "You have already voted!".

"Unique field" module does the job but after the user attempts to save his 2nd vote node. **What i would like to achieve is to deny access to the user who attempts to re-visit the "node/add/vote/nid" form if he has already voted for the specific debate.**

Any help?

# Answer
> 2 votes
A solution is to use hook on form\_alter inside a custom module :

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == 'vote_node_form') {
    global $user;
    $nid = explode('/', current_path());
    $nid = end($nid);
    // I'm sure that next part can be done waaaaaaay better
    $query = db_select('node', 'n')
    ->condition('entity_type', 'vote', '=')
    ->condition('uid', $user->uid, '=');
    $query->join('your_entity_ref_field_table', 'e', 'n.nid = e.entity_id');
    $query->condition('your_reference_column', $nid, '=');
    $query->groupBy('e.entity_id')->execute();
    // I'd advice to do a dpm($query->fetchAssoc();) to check if I didn't make a mistake         :)

    if(!empty($query)) {
            // We force the user to go on any page if he has already casted a vote on that debate (you can i.e create a page with a word of explanation)
            drupal_goto('/');
            //or do whatever you want here
    } else {
            // If not, we let him go to the normal node creation page
    }
  }
}

```

# Answer
> 1 votes
Maybe it's too late to change the specs, but have you considered using Flags with each flag counting as a vote? It seems to cover most of the uses you refer here.

# Answer
> 1 votes
Actually i'm just correcting Greg's code. So here it is:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'vote_node_form') {
global $user;
$nid = explode('/', current_path());
$nid = end($nid);
$query = db_select('node', 'n')
->fields('n', array('nid'))
->condition('type', 'vote', '=')
->condition('uid', $user->uid, '=');
$query->join('field_data_field_debate_ref', 'e', 'n.nid = e.entity_id');
$query->condition('field_debate_ref_nid', $nid, '=');
$result = $query->groupBy('e.entity_id')->execute()->fetchField();
if(!empty($result)) {
        drupal_goto('/');
   } else {
  }
 }
}

```

It's working perfectly now limiting a vote node to 1 per user & per debate node. It can be used as a costum module or directly in template.php and the best (i think): as a php selector for a panel variant of the node/add form, with some minor changes of course.

The other solution is indeed the Flags module as mariomc mentions, but only the 3x dev branch where fields are permitted to be added to flags basically transforming them into content types that can be used for my purpose as votes, therefore having 1 vote per debate per user.

---
Tags: nodes
---


# Question
Title: Display taxonomy terms and nodes together
I have a taxonomy with some terms and subterms and a content type Product, for example:

* Term1
    + Subterm1A
        - Subterm11
    + Subterm1B
* Term2
    + Subterm2A
    + Subterm2B
    + Subterm2C
* Term3
    + Subterm3A
    + Subterm3B

Products can be assigned in every level of the taxonomy (terms, subterms, etc.). If I enter in the **Term1** page, I'd like to display a list of the subterms and also the list of Products assigned to **Term1** (subterms and Products are at the same level). How can I achieve this?

Thanks a lot!

# Answer
> 0 votes
You can use the Views module. Views provides a view by default that overrides the taxonomy term paths. Enable this view (or clone the view if you anticipate making a lot of changes and want to reference the original; then enable the clone).

Then edit the view by adding the relationship **Taxonomy term: Content using Name\_of\_my\_vocabulary**. You will then be able to add the fields from the product nodes that you want.

---
Tags: taxonomy-terms
---


title: How do I enable clean URLs with Nginx?

text:
# Question
Title: How do I enable clean URLs with Nginx?
I'm using Drupal 7.x. I have achieved to make it work without clean URLs.

Investigating, I have understood that I should create a vhost for each drupal site and enable clean URLs with the following code.

```
if (-e $ REQUEST_FILENAME) {
     rewrite ^ / (. *) $ / index.php? q = $ 1 last;
}

```

Alternatively, I could use this code.

```
location / {
         [... ]
         error_page 404 = @ drupal;
         [... ]
}

location @ drupal {
         rewrite ^ (. *) $ / index.php? q = $ 1 last;
}

```

However, I've also seen that without creating a vhost can enable clean URLs (like Apache). I tried on both lines in my setup but I do not get a result. When I enable clean URLs it always displays the word Nginx (The localhost).

What is the right way to enable clean URLs?

This is my configuration in /etc/nginx/sites-available/default.

```
server {
        listen   80; ## listen for ipv4; this line is default and implied
        listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /usr/share/nginx/www;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }

        location /doc/ {
                alias /usr/share/doc/;
                autoindex on;
                allow 127.0.0.1;
                deny all;
        }

        location /images {
                root /usr/share;
                autoindex off;
        }
        # Only for nginx-naxsi : process denied requests
        #location /RequestDenied {
                # For example, return an error code
                #return 418;
        #}

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/www;
        }

        #Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                try_files $uri =404;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                # With php5-cgi alone:
                #fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                fastcgi_pass unix:/tmp/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }
}

```

I have not created any vhost on my server; neither do I know how.

# Answer
I have next that work successfully:

```
  location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass unix:/tmp/php5-fpm.sock;
 }

```
> 11 votes

---
Tags: 7, uri
---


# Question
Title: How to make SASS/SCSS Module works with Drupal 7?
I've installed SASS/SCSS module within drupal seven... There is no configuration page apart from activating debug, and development mode. So, I thought there will be no other configuration needed. I've created my `.sass` files in the css directory... but nothing happens...

Could anyone helps?

# Answer
> 2 votes
You didn't mention whether you installed the PHamlP library or not and from your question description, it sounds like that is the problem -- it needs this to actually render your .sass files. From the readme:

```
1. Create a folder inside the SASS module (sites/all/modules/sass) and name it phamlp
2. Download PHamlP_3.2.zip from http://code.google.com/p/phamlp/downloads/list
3. Extract its contents to the phamlp folder you just created
4. Once you have installed/enabled the module you can visit admin/settings/sass where you can
configure various settings surrounding the behavior of this module.

```

---
Tags: 7, theming
---


# Question
Title: How to use Drush's concurrent execution capability?
I am using Drupal multi-sites (single codebase, multiple sites/\*). Along with this, I have started using Drush aliases to manage them:

```
$ cat sites/all/drush/aliases.drushrc.php
<?php
$aliases['localdev'] = array(
  'site-list' => array(
    'site1',
    'site2',
    'site3',
  ),
);
?>

```

This allows me to easily perform actions on all sites:

```
$ drush @localdev cc all

```

\>\> *I've also just discovered that I can just use @sites, and forgo the drushrc file*.

Doing this, will execute "cc all" on each of my sites in series (one at a time).

I'd like to take this to the next level and try to run these commands on all sites *simulantiously*. I've been doing some reading, and am under the impression that Drush does indeed support this. The drush\_invoke\_process() function takes $backend\_options, which can contain (from function documentation):

```
 *      'invoke-multiple'
 *        If $site_alias_record represents a single site, then 'invoke-multiple'
 *        will cause the _same_ command with the _same_ arguments and options
 *        to be invoked concurrently (e.g. for running concurrent batch processes).
 *      'concurrency'
 *        Limits the number of concurrent processes that will run at the same time.
 *        Defaults to '4'.

```

What I can't figure out, however, is **how do I actually use this from the Drush command line**. Is there an option I need to pass to Drush, or do I need to set something in a settings file?

Any info will be much appreciated - my curiosity is piqued!

# UPDATE

Based on the answers below, I was able to create a simple test that demonstrates Drush's behaviour, and draw some conclusions:

Drush's default behaviour when executing operations on multiple sites is to use concurrent processes:

```
$ drush @localdev ev "drupal_set_message(time()); sleep(5);"

Continue?  (y/n): y
site1             >> 1360512943      [status]
site2             >> 1360512943      [status]
site3             >> 1360512943      [status]

```

This is true even when not using aliases, and is also true when using Drush's built-in @sites alias. These two commands yield identical behaviour as above:

```
$ drush site1,site2,site3 ev "drupal_set_message(time()); sleep(5);"
$ drush @sites ev "drupal_set_message(time()); sleep(5);"

```

To change the number of concurrent processes (default is 4), the '--concurrency=N' option can be passed in the drush command. For example, if I want serial execution, I can set the number of concurrent processes to 1:

```
$ drush @localdev ev "drupal_set_message(time()); sleep(5);" --concurrency=1

Continue?  (y/n): y
site1             >> 1360513387      [status]
site2             >> 1360513393      [status]
site3             >> 1360513399      [status]

```

# Answer
> 5 votes
This worked for me:

```
drush @site1,@site2,@site3,@site4 cc all --concurrency=4

```

I'm not sure how concurrent it actually was; the last message about site1 came immediately after the first message for site2, and all other messages were printed sequentially. I did not measure to what extent each cc operation happened concurrently, or to what extent the system might have just been cpu or i/o bound, but it did seem to be nominally working.

# Answer
> 1 votes
For single instance (without site-list):

```
<?php
$aliases['localdev'] = array(
  'invoke-multiple' => TRUE,
);
?>

```

For aliases with site-list array it will run concurently even...

**After below comments**, let's review code for drush\_invoke\_process:
*`//` \- my comment, `/* ... */` \- shortening provided code.*

```
<?php
function drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(), $backend_options = TRUE) {
  if (is_array($site_alias_record) && array_key_exists('site-list', $site_alias_record)) {
    /*  $invocations[] - this array filled with command for each site in site-list. */
  }
  else {
    /* aliases not defined or site-list not found.  So $invocations filled by one item. */
  }
  return drush_backend_invoke_concurrent($invocations, $commandline_options, $backend_options);
}
?>

```

Next called:

```
<?php
function drush_backend_invoke_concurrent($invocations, $common_options = array(), $common_backend_options = array(), $default_command = NULL, $default_site = NULL, $context = NULL) {
  /* Here building command line happen for each site (invocation). */
  return _drush_backend_invoke($cmds, $common_backend_options, $context);
}
?>

```

Next will called:

```
<?php
function _drush_backend_invoke($cmds, $common_backend_options = array(), $context = NULL) {
  /* Some simulating code and fork code */
  if (array_key_exists('interactive', $common_backend_options) || array_key_exists('fork', $common_backend_options)) {
    /* Direct running (interactive or fork) */
  }
  else {
    // Concurrency set to 4 by default. So --concurency just override it by another value.
    $process_limit = drush_get_option_override($common_backend_options, 'concurrency', 4);

    // Next is main call, that run commands as concurent processes using proc_open and streaming:
    $procs = _drush_backend_proc_open($cmds, $process_limit, $context);

    /* Processing of result running of processes. */

  }
  return empty($ret) ? FALSE : $ret;
}
?>

```

---
Tags: drush, multi-sites
---


# Question
Title: I forgot the password to the admin account
A few month ago I have make a web-page using drupal. I had some break due to phd thesis. Now I want to push the subject foreward and finish the page, but I have forgot the admin's password. Is there a possibility to get it, or change it?

I tried the method described on http://drupal.org/node/1023428, but I got the following errors:

> PHP Warning: include\_once(/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/password.inc): failed to open stream: No such file or directory in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 83 Warning: include\_once(/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/password.inc): failed to open stream: No such file or directory in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 83 PHP Warning: include\_once(): Failed opening '/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/password.inc' for inclusion (include\_path='.:/usr/share/php5:/usr/share/php') in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 83 Warning: include\_once(): Failed opening '/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/password.inc' for inclusion (include\_path='.:/usr/share/php5:/usr/share/php') in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 83 PHP Warning: include\_once(/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/bootstrap.inc): failed to open stream: No such file or directory in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 84 Warning: include\_once(/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/bootstrap.inc): failed to open stream: No such file or directory in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 84 PHP Warning: include\_once(): Failed opening '/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/bootstrap.inc' for inclusion (include\_path='.:/usr/share/php5:/usr/share/php') in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 84 Warning: include\_once(): Failed opening '/var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/includes/bootstrap.inc' for inclusion (include\_path='.:/usr/share/php5:/usr/share/php') in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 84 PHP Fatal error: Call to undefined function user\_hash\_password() in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 87 Fatal error: Call to undefined function user\_hash\_password() in /var/www/localhost/htdocs/26\_05\_2012/zipshop/scripts/password-hash.sh on line 87

Is there a possibility to change the password just through mysql-cient?

# Answer
If the email you used to register the account is still active, or you still have access to it, then the easier way to change the password is using the "Request new password" link that appears in the login block, or the login page.

If you don't have access to the email you used to register it, you could change it in the "users" database table, and then request a new password.

If you don't have access to the database, but Drush is installed, then you can use the following command.

```
drush user-password <username> --password=<password>

```

Alternatively, you can use this command, which allows you to login as a user for once; once you are logged in, you can change the password for that account.

```
drush user-login <username>

```

The command return a link that can be used in the browser to access the site. If the username is omitted, the link is for the user #1.

If Drush is not installed, then you need to write a PHP file to change the password for the account. For Drupal 7, the following code works.

```
$account = user_load_by_name($username);
$edit['pass'] = $newpassword;
user_save($account, $edit);

```

Place the code in a file with extension .php, in the same directory containing the index.php file that comes with Drupal. Replace `$username`, and `$newpassword` with the username of the account you need to change the password, and the new password.

The following code work with both Drupal 6, and Drupal 7, but it requires you to know the user ID of the account.

```
$account = user_load($uid);
$edit['pass'] = $newpassword;
user_save($account, $edit);

```
> 1 votes

# Answer
Done! I have used the following method:

http://drupal.org/node/1556488
> 0 votes

---
Tags: users
---


# Question
Title: Drupal 7 CKEditor-CKFinder remove "Browse Server"
I have a multi-domain site setup with domain access module. In each domain users are allowed to post their own contents with media upload settings. I am using CKEditor and CKFinder together.

Now, I want to disable the "Browse Server" Button but the local Browse button will be there.

I am unable to find the settings(which I think not in Drupal admin) or the code to edit to fixup this. https://stackoverflow.com/questions/3610041/ckeditor-with-ckfinder-disable-filebrowser-keep-upload-functionality This one didn't helped my either. Any help on this?

# Answer
Well I have found that patch solution. So just answering my own question. In sites/all/modules/ckeditor/includes/ckeditor.lib.inc file,

There is a section as

```

if (user_access('allow CKFinder file uploads')) {
                $ckfinder_full_path = $host . ckfinder_path();
                //$settings['filebrowserBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?id=' . $profile_name;
                //$settings['filebrowserImageBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?Type=Images&id=' . $profile_name;
                //$settings['filebrowserFlashBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?Type=Flash&id=' . $profile_name;
                $settings['filebrowserBrowseUrl'] = '';
                $settings['filebrowserImageBrowseUrl'] = '';
                $settings['filebrowserFlashBrowseUrl'] = '';
                $settings['filebrowserUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Files&id=' . $profile_name;
                $settings['filebrowserImageUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Images&id=' . $profile_name;
                $settings['filebrowserFlashUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Flash&id=' . $profile_name;
            }

```

So I commented the actual filebrowserBrowseUrl, filebrowserImageBrowseUrl & filebrowserFlashBrowseUrl settings and made those as blank. That did the trick.
> 1 votes

---
Tags: wysiwyg
---


# Question
Title: Translating custom database table fields
How can I translate the fields for my custom database table which uses the following schema?

* member\_id: int
* name: varchar(60)
* i\_prefer: varchar(50)

I need to translate the string that is displayed for the 'i\_prefer' field. I know how I should represent this in template page (`<?php print t($query->i_prefer); ?>`), but the translated string will not appear until I provide the translation. I checked in 'Regional and language \> Translate interface'; I can not see my text.

How can I do this?

# Answer
> 1 votes
The first argument of `t()` is a literal string, not a dynamic string. If you use a dynamic string, that will be translated only if it matched a literal string another module passes to `t()`.

For example, if I use the following code, the string will be shown translated (when a translation for the currently enabled language exists), as `'E-mail address'` is used as argument of `t()` from user\_account\_form().

```
  $label = 'E-mail address';

  $form['mail'] = array(
    '#type' => 'textfield',
    '#title' => t($label),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#required' => TRUE,
    '#default_value' => '',
  );

```

If the values contained in that database field are limited to specific values, then you can add the following code to the module you are using.

```
function mymodule_translated_strings() {
  $strings = array(
    t('first value used for the database field'),
    t('second value used for the database field'),
    t('third value used for the database field'),
  );
}

```

The function doesn't need to be called; it is required only to have a call to `t()` for each literal strings that contain one possible value of that database field. Clearly, this is convenient if the database field can assume values which are restricted to a small set of values. If the values assigned to the database field are input from users, then this approach is not possible, since the users can (theoretically) enter any value.

For the other cases, the Internationalization module could be helpful. As described in Translating user-defined strings (module developers), i18nstrings() is the function that should be used in this case.

---
Tags: i18n-l10n
---


# Question
Title: How to use separate databases for Drupal tables?
So far, what I've read is you can config multisites to use different tables and share any table with other sites in that multisite config.

My question is if it is possible to get this config:

* Database A has Site A's users and Site A content
* Database B will only have Site B's content
* Site B will use users table in database A.
* Site B will have its content in database B.

It may not be a multisite question after all but rather, in short...

Is it possible for a Drupal site to use two different databases for some of its tables? How?

# Answer
> 7 votes
In the settings.php file used for the site, you can specific a different prefix for each database table.

```
  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => array(
      'default'   => 'main_',
      'users'     => 'shared_',
      'sessions'  => 'shared_',
      'role'      => 'shared_',
      'authmap'   => 'shared_',
    ),
    'collation' => 'utf8_general_ci',
  );

```

You can also refer different databases, or schema, using code similar to the following one.

```
  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => array(
      'default'   => 'main.',
      'users'     => 'shared.',
      'sessions'  => 'shared.',
      'role'      => 'shared.',
      'authmap'   => 'shared.',
    ),
    'collation' => 'utf8_general_ci',
  );

```

The difference between the last snippet, and the previous one is that the last character used for the prefixes is the dot, not the underscore. That causes the database engine to select a different database/schema, instead of the currently set one.
To be clearer, in the code I shown the database engine is still MySQL running on localhost; what changes is that for the users table, Drupal will use the *shared* database instead of the *databasename* one.

As far as I know, this is valid for Drupal 7, or higher. The same *trick* is not reported in the comments present in the default.settings.php file that comes with Drupal 6.

### Reference

The comments shown in the default.settings.php file.

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


title: CDN Module and Canonical Domain

text:
# Question
Title: CDN Module and Canonical Domain
I have a site where I am using the CDN module in origin pull mode with Amazon CloudFront. Apache is configured so Drupal will handle www.example.com and static.example.com.

Is there a way to get Drupal to only use the static URL only for my static resources (images, CSS, JS, etc), and redirect other requests to www? Is the only real way to implement a `hook_page_build()` and check the Content-Type header to see if it begins with "text/html", and potentially redirect then?

# Answer
> 0 votes
If by static resources you mean resources for which the content is served from the server, using the content of a file, then `hook_page_build()` is not invoked for such resources.
It's the server that handles those requests, and Drupal doesn't do anything. In that case, you could edit the .htaccess file to redirect the users to the right domain.

That is what I would do also in the case it's Drupal to produce the content. Rather than letting Drupal produce the output, and redirect the user to the correct sub-domain, where the output would be produced again, I would rather redirect the user once it is clear what type of resource is being requested, and which is the URL of the resource.

---
Tags: cdn
---


title: Changing a field title in a panel

text:
# Question
Title: Changing a field title in a panel
I've got a field in a panel. I want the field title to be replaced by something that is dependent on another node. In a view this is really straightforward:

View -\> Configure Field -\> Rewrite Results -\> Rewrite the output of this field: (\[field\_A\] is the name of this thing)

The Panel, however, doesn't recognize the \[bracket\] functionality in Node -\> Settings -\> Override title.

Apologies if this is obvious, but I can't find the solution anywhere. Any help would be hugely appreciated.

# Answer
> 1 votes
You can use **keywords from contexts** when you override a title of a pane in Panels. Go to *Contexts* in the Page Manager UI. The summary of contexts displays the available keywords.

In your situation you may want to add a new context, the node that you want your pane title to be pre-populated from. You can select the node ID, and the same node will always be loaded.

If it's not always the same node that you want to use, but e.g. a reference field in your already loaded node defines it, you can use a relationship to create the appropriate node context.

---
Tags: panels
---


# Question
Title: How to prevent a field from wrapping in Views?
I have a price field that gets squished and displays on multilines instead of a single line. The only way to solve this is to apply some css wrap magic?

# Answer
> 0 votes
With css you could set a specific width or use white-space:nowrap. I don't know how to do it other than with css or javascript

---
Tags: views, theming
---


# Question
Title: How do I create a view with filter on a field built using the date module?
I created a content type that includes a date field. I want to create a view that filters on this field, but it appears that the field is being seen as a text field because there are no operators for greater than or less than like I would see if I were filtering on the posted date. I only see text based operators like length, starts with, etc. What do I need to do? I'm running Drupal 7. How do I make this work?

# Answer
> 0 votes
You have 2 types of date filter handlers in Views ; try not to use the one that is your field but **the date field, that will ask you on which date field it'll filter**.

# Answer
> 0 votes
Just to better explain how to have date support on views: it has to be enabled "date views" module.

People using drush just needs to execute:

```
drush en date_views

```

---
Tags: views, datetime
---


# Question
Title: How to have a view field that searches node title, body and everything about node
I am looking at replacing the core search module with a custom view. I would want a field that lets users search all the content by keyword(s).

What's my best option, preferably a module that does this in a user friendly way.

# Answer
You could try using Apache Solr backend. You can use the following modules:

Another solution is to use a module like "views\_or" or "views\_filters\_populate".

Otherwise you could give a try to "search\_autocomplete".

Good work!
> 2 votes

---
Tags: views, search
---


title: Only override part of a theme function

text:
# Question
Title: Only override part of a theme function
In Drupal 7 you can take a theme function and override it.

For example if I want to override `theme_form_element`, I would place it in my template.php as `MYTHEME_form_element`.

The only problem is that I then have to copy the entire theme function into my template. For example, for theme\_form\_element, there is over 60 lines of code.

This seems overkill, if I only want to do something simple as add a class to the attributes array.

Is there any way to only include the part of the theme function I want to override and tell Drupal to refer to the rest of the built in function?

# Answer
If you need to change the content of the variables passed to the theme function, then you can simply implement a preprocess function for that theme, which in Drupal 7 is invoked for every theme function, including the ones not using a template file.
In the case of `theme_form_element()` the preprocess function for your theme is `MYTHEME_preprocess_form_element()`.

You could also avoid duplicating the code of `theme_form_element()`, and call it before, but in that case you should call it directly as `theme_form_element()`, not as `theme('form_element')` (which would cause an infinite loop).

The problem with `theme_form_element()` is that it doesn't use `$element['#attributes']['class']` to set the attributes of the form element. It uses a local variable that is initialized with the following code, which passes its value to `drupal_attributes()`.

```
  $attributes['class'] = array('form-item');
  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

```

To add a new class to the form element, you have two alternatives:

* Copying the code from `theme_form_element()` to your theme function, and editing it
* Call `theme_form_element()` from your theme function, and add a new class to the output returned from `theme_form_element()` using preg\_replace().
> 5 votes

# Answer
If you're just adding a class to the attributes array a `template_preprocess` hook would be sufficient, and stop you having to copy the entire thing, e.g.

```
function MYTHEME_preprocess_form_element(&$vars) {
  $vars['attributes']['class'][] = 'another-class';
}

```

If you need to add a wrapper around the outer element you can do something like this

```
function MYTHEME_form_element($vars) {
  $original = theme_form_element($vars);
  return '<div class="something">' . $original . '</div>';
}

```

But if you need to add an extra attribute to an internal element of that theme function, you'll need to copy the whole thing over. PHP offers no way to pick a section of a function to run, it's all or nothing.
> 3 votes

---
Tags: theming
---


# Question
Title: viewing fields with field_view_field after EntityFieldQuery doesn't work
I'm using an EntityFieldQuery to load a node and try to access some of its fields, but can't seem to get any of the fields. The code is below:

```
$nodestoload = $query->execute();
$nids = array_keys($nodestoload['node']);
$nodes = entity_load('node', $nids);
print_r($nodes);
$output = field_view_field('node', $nodes, 'suppliername');

```

However, `$output` is returning an empty array. I can see that the node loads using the print\_r. I've also tried various options (such as replacing 'node' with the actual bundle type). But nothing seems to be working... How do I access fields from a node that I loaded programmatically?

# Answer
> 1 votes
The correct code is the following one.

```
$nodes_to_load = $query->execute();
if (isset($nodes_to_load['node'])) {
  $nodes = entity_load('node', array_keys($nodes_to_load['node']));

  foreach ($nodes as $node) {
    $output = field_view_field('node', $node, 'suppliername');
    // ...
  }
}

```

field\_view\_field() accepts a single entity object, as second argument; you cannot pass it an array of entities.

# Answer
> 1 votes
Your code will only work if there is only a single value returned by your EFQ. Whatever you want to do with the nodes, you need to put in a `foreach()`:

```
$nodestoload = $query->execute();
foreach ($nodestoload as $loaded_node) {
  $nid = array_keys($loaded_node['node']);
  $node = entity_load('node', $nid);
  print_r($node);
  $output = field_view_field('node', $node, 'suppliername');
}

```

---
Tags: entities, nodes, database
---


# Question
Title: Storing Credit Card Information for later use
I'm building a website where registered users would place future order(s). e.g. after 6 months for $20, or even on a specified date may be after one year or so.

In order to charge them on those transaction dates through paypal or any other payment gateway, we would need their credit card information to store somewhere.

What is the best way to complete the task with maximum security.

Please advice.

Edit: Currently I'm using Ubercart, but if any other module can fit for the required scenario, I'm open for that.

These would not be recurring payments, but I would rather call them "post-dated orders". I've never used any payment methods. This is my first site for shopping cart so I've no idea. If paypal can store the CC info for multiple transactions for every site member and give me option to execute the orders on specific dates, I hope that would be fine with me too.

# Answer
> 13 votes
The most secure place to store credit card numbers will be on a third party service designed to securely retain that data. These service providers are PCI Level 1 compliant with code and systems in place to prevent the unwanted or unexpected exposure of sensitive card data.

Many payment gateways support such "card on file" functionality, where they allow you to process an authorization or capture for a credit card and provide you with a token to perform follow-up transactions using that same card data. Such a transaction is generally referred to as a "reference transaction", with example implementations being PayPal's reference transactions, Authorize.Net's Customer Information Manager (CIM), or CyberSource's Managed Billing / subscriptions.

The name and price of these services will vary from payment gateway to payment gateway, but they will always require a similar point of integration in Drupal - a way to retain a payment token and process that reference transaction at a later date; typically you want some sort of customer interface as well, allowing customers to update their information or reuse a credit card on a later order.

To solve the Drupal integration, we created the Commerce Card on File module, which does all this and more within Drupal Commerce. It works through payment method callbacks, allowing any payment method module to implement the callbacks to integrate reference transactions through its payment gateway's API. Obviously, not every payment gateway under the sun is supported, so be sure to check the documentation to find out if yours is supported.

And as the comments on your original question indicate - you should never be in the business of storing card data in your site, which was unfortunately easy to do in Ubercart. Multiple times now I've been part of rescuing sites that incorrectly used the UC Recurring module to retain credit card data in plaintext in the database for later processing. Do not do this - ever.

---
Tags: ubercart, commerce, payment-gateways
---


# Question
Title: How do I remove the default 'my cms' text from my drupal 7 webpage with the bartik theme?
I have recently created a webpage with drupal 7 and currently have the bartik theme applied. However, I have encountered what I assume is a trivial issue but have been unable to fix it. The site has the default text **'my cms'** appearing in the banner across the top of all pages and I have been unable to remove it. I assume it is the site's slogan, but I have not been able to locate where that is set in either the the admin of the site or the files of the site.

Here is the site to show what I am talking about.

Thanks for the help.

# Answer
That *My CMS* text is the *Site name* setting value. You can change it from the setting page on /admin/config/system/site-information.
> 0 votes

---
Tags: 7
---


title: Why would custom fields not update?

text:
# Question
Title: Why would custom fields not update?
I am having trouble updating custom fields programmatically. The code appears below and is in the body of my custom module. When I run this changing the title, it changes OK. But, when I try to do this with the custom field, the field doesn't get updated and I don't understand why. Should I be wrapping this into some hook? Is there a cache not being cleared somewhere? Basically, what am I missing when it comes to programmatically updating fields.

```
$nodes_to_load = $query->execute();
if (isset($nodes_to_load['node'])) {
  $nodes = entity_load('node', array_keys($nodes_to_load['node']));

  foreach ($nodes as $node) {
  $node->field_myother_field[$node->language][]['value'] = '500';
  $node->title = "retest the test";
  node_save($node);
 }
}
 else {
  print "no nodes to load";
}

```

UPDATE: When I try to change the field by going into the admin panel, and simply typing in a new value I get a "The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved" error.

# Answer
> 3 votes
I suspect you don't have $node-\>language set, or perhaps the empty \[\] is causing trouble.

Try:

```
$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    // Set node language to default, if not set
    $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;
    $node->field_myother_field[$node->language][0]['value'] = '500';
    $node->title = 'retest the test';
    node_save($node);
  }
}else {
  drupal_set_mesage('no nodes to load');
}

```

Using entity\_metadata\_wrapper

```
$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    $node_wrapper = entity_metadata_wrapper('node', $node); // Get node wrapper
    $node_wrapper->field_my_other_field->set('500'); // Set field value
    $node_wrapper->save(); // Save entity
  }
}else {
  drupal_set_mesage('no nodes to load');
}

```

---
Tags: entities, updating
---


title: Sitemap and XML sitemap

text:
# Question
Title: Sitemap and XML sitemap
I originally had a sitemap using the sitemap module. I've now installed and enable dthe xml sitemap module instead. After following the instructions and configuring xml sitemap, when I go to mysite/sitemap.xml all I see is an unstyled page with an ugly table listing the Links.

How would I go about styling this sitemap? I was expecting it to work like the Sitemap module does and generate a page using a default template, but I guess I was wrong, or am I?

How should a sitemap.xml display after it's been set up?

# Answer
Sitemap.xml is used to provide a way for search engines to index your site. It should not be used by your website users.
> 2 votes

---
Tags: xml-sitemap
---


title: Version history/ revisioning

text:
# Question
Title: Version history/ revisioning
Is there a way to get drupal 7 to keep version history for every node/page without having to remember to select the "Create new revision" option every single time?

Is there a module that improves this feature? Also, the ability to Diff two different revisions would be great.

# Answer
> 1 votes
You can set each content type to default to create a new revision; if you edit a content type you'll see something like this:

Select the 'Create new revision' checkbox and save the form; when you add/edit content of that type the 'Create new revision' option will be pre-selected.

As far as diffing revisions goes, you can install the Diff module:

> This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.

---
Tags: nodes
---


# Question
Title: How do you configure it so a published article promoted to another page instead of "front page"?
I have a main menu with:

"Home" -basic page "Contact us" -the default drupal contact form "news" - which I want all the news articles to dynamically publish to the top so that when people click on news they see the latest article.

I thought that making a menu item in the form of an "article page" might do it but that only seemed to be comfortable with a single article. I made it into a book and it has allowed me to create a page but the formatting has gone dead weird so I would like to be able to create my articles and click an option which allows me to promote my articles to the news page. Is this possible?

Thanks

# Answer
> 3 votes
With Views, you can use "promoted to front page" as a filter value, so that things with that box checked can also be "promoted" to any page view that takes that as a filter.

If you don't want to us the native "promoted to front page" checkbox, but would rather have a separate checkbox just for that page, you can add a custom field to your content type(s) and use that as a filter value instead.

# Answer
> 1 votes
Views

> **You need Views if**
>
> * You like the default front page view, but you find you want to sort it differently.
> * You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
> * You use /tracker, but you want to restrict it to posts of a certain type.
> * You like the idea of the 'article' module, but it doesn't display articles the way you like.
> * You want a way to display a block with the 5 most recent posts of some particular type.
> * You want to provide 'unread forum posts'.
> * You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
> "Month, YYYY (X)" where X is the number of posts that month, and
> displays them in a block. The links lead to a simple list of posts
> for that month.
>
> Views can do a lot more than that, but those are some of the obvious uses of Views.

Views Tutorials

---
Tags: views
---


# Question
Title: Create a view to display the list of content created by user
I want to create a view for each individual user of my site which would display the content create by that logged in user only, i.e, When a user logs in, then when he clicks a tab (i am using quicktab here) a view appears which shows all the content that this user only has created. I do not want to show this user content created by others. Is there any efficient way to do so. I am using Views3.

Thanks for your time

# Answer
Yes, the easiest way to list content created by user is with Views.

Basically, create your view, with the relevant filters for content type, fields etc..

Then add a contextual filter for current user.

* Click "Advanced" \> "Contextual Filters"
* "Add" \> "Content: Author uid"
* "Provide default value" \> "User ID from logged in user"
* Save
> 10 votes

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


title: Google Analytics report on the website

text:
# Question
Title: Google Analytics report on the website
Is there a way of making the google analytics available for previewing on the drupal 7 site?

# Answer
> 2 votes
Try Google Analytics Reports module.

> Graphical reports include a dashboard widget for admins, a small path-based report in blocks, and a full path-based report.
>
> Prerequisites are the Google Charts API module and the OAth module. Do not forget to set the module’s permissions about who has access to the reports.

---
Tags: 7, google-analytics
---


# Question
Title: What tpl should I choose for this faq page?
What's the template that controls the /faq-page (from the FAQ Module in Drupal 7)? I've read the explanation at the top of each tpl file inside the module, but can´t understand what file should I override.

**When I enter the /faq-page url, I have the categories. When I click each category, they open in a new page. So I've tried the faq-category-new-page.tpl.php**

But it won't work. I've copied the tpl into my theme, opened it and added some css classes. They won't work (even when I've flushed cache).

What template should I choose? Thanks! Rosamunda

# Answer
The most simple solution would be to copy all of the 9 templates from the module directory to your theme, and then add a simple output and see where and how they are used. You can later delete the ones you don't need to modify.

The templates used seems to be based on the configuration settings though, so keep that in mind.
> 1 votes

---
Tags: 7, theming
---


title: Page not found error when using panels

text:
# Question
Title: Page not found error when using panels
I'm trying to add a block to an existing panel. The dialog opens but then I see this error,

> The requested page "/panels/ajax/editor/select-content/panels\_page\_wizard:landing\_page/bottom" could not be found.

and the ajax spinner never stops. The panel module is currently up to date, and google doesn't return any hits for the error.

I can create a brand new panel page, and the same problem occurs.

# Answer
Turned on logging and saw Rejected-By-UrlScan next to the 404 errors.

Since our site is hosted in IIS, I needed to go into URLScan config, and allow colons, which are used by the Panels ajax func

C:\Windows\system32\inetsrv\urlscan\UrlScan.ini

```
; :   ; Don't allow alternate stream access

```
> 0 votes

---
Tags: blocks, panels
---


title: user details as block with auto refresh

text:
# Question
Title: user details as block with auto refresh
I am new to drupal. I want to show a module that refresh every 3 seconds and displays the other existing user details with their photo graph .

# Answer
Try Block Refresh module.

> Block Refresh allows an administrator to configure a block to refresh it's content in a given number of seconds. Block Refresh uses jQuery/AJAX so the refresh happens "behind-the-scenes".
> 2 votes

---
Tags: 7, views
---


title: Bulk import module

text:
# Question
Title: Bulk import module
I've created a custom content type and I need to enter 30 or so records. The type has around 5 fields.

Is there a module that provides a table for me to enter these details? At the moment, I assume I need to enter them one by one, or spend time writing some kind of mySQL script.

# Answer
> 2 votes
1. Feeds \- Import or aggregate data as nodes, users, taxonomy terms or simple database records.
2. Node import \- Node import allows users to import content (node, user, taxonomy) from CSV or TSV files.
3. Node export \- This module allows users to export nodes and then import it into another Drupal installation, or on the same site.
4. Migrate \- The migrate module provides a flexible framework for migrating content into Drupal from other sources

I am recommend for simple case node import/export using. If importing happen eventually and it's simple, then Feeds. If import make hard data and big count of records, then Migrate.

---
Tags: nodes, batch-operations
---


title: How to alter main_menu for logged user?

text:
# Question
Title: How to alter main_menu for logged user?
I would like to alter/change structure of *main menu* links (programmatically!) for logged in users. What is the simplest way to do this?

# Answer
> 0 votes
I hope, Drupal 7 main-menu - change item text if user logged in you check this first.

If this does not complete your requirement, then, u have to override the `theme_menu_link` hook.

http://api.drupal.org/api/drupal/includes!menu.inc/function/theme\_menu\_link/7

You can check whether the user is logged in or not by checking **boolean** `$logged_in`. If it is true, user is logged in else not.

---
Tags: routes, navigation
---


# Question
Title: 6 - No content displaying though content is there
I'm new to drupal, moved from WordPress. I'm trying to get a local install of a client site working. I have the site running normally but no content wants to show.

The content is there, I can see it in the backend and on, say, the blog page it has the right amount of paginated links. Plus the markup and css are correct. The div is empty though.

I've disabled memcache, that might be it, plus all things on the net I could find. \- truncated the cache tables \- run update.php \- tried creating a new view, same issue

plus some others I can't think of right now.

Any help with debug pointers would be much appreciated, thanks.

# Answer
This can be of due to many reasons. Check one of these,

1. Go to *configuration/system/site information*, Make sure, you have correct number of posts and front page. \[Number of posts on front page \]
2. When you add content, then, make sure, you click on publishing option and click on 'published' checkbox. You can check the content is published or not, by making a menu link of it.
3. If these are okay, then, please check by changing the theme, may be your theme page is broken or something. Go to *appearance* and select new theme.

Make sure, you flush your system, cache and try.
> 1 votes

# Answer
This might be obvious and is also a stab in the dark but have you tried comparing with the live site if all the enabled/disabled modules are also enabled/disabled on your local install? Something like Blog page might not show anything due to views/panels being disabled?
> 0 votes

---
Tags: 6
---


# Question
Title: Associating a user with a particular form submit/click
In my web site i have created a custom content type Challenge which contains a list of tasks that the user has to do. I have created the custom content type from the CMS itself through admin/structure/content type. I have created a custom form, , and when the user clicks submit i have made a query which insures that the node id of that challenge and the user id is associated in a Challenge table (the code is below). It works fine. Now i need to create a view which shows the challenges accepted by the user, i.e., when the user logs in and clicks on a tab(i am using quicktab) then a view appears which shows the challenges undertaken by the user. Here my code for the query:

```
function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_my_form($form_state) {

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Accept Challenge',
    '#submit' => array('my_module_action'),
    );

  return $form;
}

function my_module_action($form, &$form_state) {

 if ($node = menu_get_object()) {
  // Get the nid
   $nid = $node->nid;
    }
 global $user;
 if ( $user->uid ) {
 $query = db_insert('challenges')
    ->fields(array(
    'cid' =>$node->nid,
    'uid' => $user->uid
    ))
    ->execute();
}

```

Well, thats it then. Now how do i create a view to show a user their accepted challenge.

Thanks

# Answer
1. For node you should load challenges data in your custom module, using next: hook\_node\_load and/or showing next: hook\_node\_view. See examples module for it: nodeapi\_example.
2. For Views you should define connection with your custom table and node, there nice example for it.
3. For Views also you can use Data module.
> 0 votes

---
Tags: users, views
---


# Question
Title: A module or solution to build first time user walkthrough?
Is there a module or existing solution out there that can be used to create first time user walkthroughs of a site? For example, a user logs in for the first time and gets redirected to a certain page and then can follow steps to learn the site etc etc. I have done some googling on the matter but as you can imagine the results are hold to filter when searching for terms like "guide", "walkthrough", "module", "new user" and so on...

# Answer
The jQuery Joyride module would certainly be an option

> This module provides Drupal integration with Zurb's Joyride Jquery plugin in order to provide a tour of different html elements on your Drupal site. Drupal integration is done via the Context module, which provides a way to control conditional calling of the joyride plugin and copy-and-paste method for adding specific tour code.

It wraps around the excellent jQuery Joyride plugin
> 4 votes

---
Tags: 7
---


# Question
Title: View to show user relationships with different fields
I am using the User Relationships module to allow users to forge relations between themselves. The relationship is 1 way of type Following. I have been able to do so. Now i want to create a view for the logged in user which would show him or her their pending relation request, the people they are following, and the people who follow them I tried to do so using Views and contextual filters and adding different fields but was unable to successfully do so. My use case is : https://i.stack.imgur.com/Eg78Z.jpg

Thanks

# Answer
You need to first add a users view and then you add a contextual filter to the view using the user field that the relation will have now exposed in the contextual admin selection. Then add a default value of currently logged in user to the contextual filter and with that it will expose the relevant fields.

1. Add new view of type users
2. Add contextual filter of type user relationships: User who accepted the relationship
3. Add default value of logged in user
4. (optional but will expose even further info) add views relations to expose further data
5. profit
> 1 votes

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


# Question
Title: The CSS styles of my theme are not applied
I have integrated a new theme in Drupal, and used the following content for its .info file.

```
name = my_theme
description = A flexible, recolorable theme with many regions.
package = Core
version = VERSION
core = 7.x

stylesheets[all][] = tabcontent.css
stylesheets[all][] = styles.css
script[all][] = settab.js

settings[shortcut_module_link] = 0

; Information added by drupal.org packaging script on 2013-01-16
version = "7.19"
project = "drupal"
datestamp = "1358374870"

```

I can't get the CSS styles on my theme. What can I do to fix it?

# Answer
> 0 votes
You should check your folder structure, if your `styles.css` file is under the folder CSS, then you should write

`stylesheets[all][] = css/styles.css`

Always flush all the caches when you change your `.info` file.

I think you should download the Zen theme and read the documentation. Inside the zen folder you will find a folder named STARTERKIT, it gives you and "empty" template fully customizable.

---
Tags: 7, theming
---


title: Menu for /user page

text:
# Question
Title: Menu for /user page
How to edit menu for `/user` page? I can't find this menu in the dashboard.

I have:

```
View
Edit
Orders
Shortcuts
Track page visits
Devel

```

# Answer
> 0 votes
The menu you're referring is named "menu local task". Usually you can edit this menu in different ways like:

* implementing hook\_menu().
* Creating a view with a "menu tab" and a matching path.

The first way needs a bit of programming. You've to create a custom Drupal module which implements hook\_menu() and add the entry.

The second option is more easy:

1. Create a view with a "page" display
2. Set /user/custom-subpath as "path"
3. Select "Default menu tab" or "menu tab"

**EDIT**: if you need to remove an item you can implement hook\_menu\_alter() and unset the unwanted items in this way:

```
function yourmodulename_menu_alter(&$items){
  unset($items['path/to/remove']);
}

```

Good work, bye.

---
Tags: routes
---


# Question
Title: Allow blank search/list all items with 1.x apache solr module
When a user enters a blank search, by clicking "search" right away, or entering the search result url directly, the initial version of the Apache Solr Search Integration module, 6.x-1.x series, tells the user to "Please enter some keywords".

I would like it to issue the empty search, thereby returning all available results. This question List all available items with Apache Solr if the search keyword is empty asks the same for the second generation of the module, 6.x-3.x and 7.x-1.x, but that answer doesn't apply.

I've tried hacking out the `if ($keys == ''` check that yields the "error" message, but that simply results in no results at all.

# Answer
> 0 votes
I ended up with the below patch that seems to do the trick. The patch looks much larger than it needs to because I corrected the indentation after I removed an `if`.

Anyone that considers using this patch should be aware that this will hack the module. You should understand what that means, and be using a make file to avoid future complications.

```
$ diff -u apachesolr_search.module_ apachesolr_search.module
--- apachesolr_search.module_   2013-02-11 10:12:17.814561087 +0100
+++ apachesolr_search.module    2013-02-11 13:29:10.450336901 +0100
@@ -159,24 +159,22 @@
   if (isset($_GET['filters'])) {
     $filters = trim($_GET['filters']);
   }
-  // Only perform search if there is non-whitespace search term or filters:
-  if ($keys || $filters) {
-    // Log the search keys:
-    $log = $keys;
-    if ($filters) {
-      $log .= 'filters='. $filters;
-    }
-    watchdog('search', '%keys (@type).', array('%keys' => $log, '@type' => t('Search')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));

-    // Collect the search results:
-    $results = search_data($keys, $type);
+  // Log the search keys:
+  $log = $keys;
+  if ($filters) {
+    $log .= 'filters='. $filters;
+  }
+  watchdog('search', '%keys (@type).', array('%keys' => $log, '@type' => t('Search')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));

-    if ($results) {
-      $results = theme('box', t('Search results'), $results);
-    }
-    else {
-      $results = theme('box', t('Your search yielded no results'), variable_get('apachesolr_search_noresults', apachesolr_search_noresults()));
-    }
+  // Collect the search results:
+  $results = search_data($keys, $type);
+
+  if ($results) {
+    $results = theme('box', t('Search results'), $results);
+  }
+  else {
+    $results = theme('box', t('Your search yielded no results'), variable_get('apachesolr_search_noresults', apachesolr_search_noresults()));
   }
   if (empty($form)) {
     // The form may be altered based on the query that was run.
@@ -998,9 +996,6 @@
     $get['retain-filters'] = '1';
   }
   $form_state['redirect'] = array($base . $keys, $get);
-  if ($keys == '' && !$queryvalues) {
-    form_set_error('keys', t('Please enter some keywords.'));
-  }
 }

```

---
Tags: search
---