# Question
Title: Display terms, username and user picture in a view block
I created a new view block and it appears in Article - Content type; In these block I want to display the author's user picture, author's username, post date, category, tags, and comment count.

I succeeded to display user picture, username, but the post date, category, tags, and comment count are from the other article (the first or the last article written by the same author).

I used a few relationships and contextual filters, without success.

### Example

I have an article with title "One two three", category numerals, tags "one, two, three, numeral". When someone reads these article, I want that block to show these values:

* Category: numerals
* Tags: one, two, three, numeral
* username
* user picture

Is it possible to display all these things in one view?

# Answer
> 3 votes
There was a recent answer very much along these lines here that recommended the module Author Pane. This module is extensible with hooks; might be the easier way for you to go as well.

> Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.

# Answer
> 1 votes
Have you tried using the `Taxonomy : All Terms` along with the `Limit terms by vocabulary` constraint? That can be used to display all the Tags.

# Answer
> -2 votes
You need the Chaos tool suite, Views and Quick Tabs modules. Under **Chaos tool suite** module enable *Chaos tools*, *Page manager* and *Views content panes*; under **Views** module enable *Views* and *Views UI*.

* Go to Structure/**Views** (`admin/structure/views`); click *"Add a new view"*; give a name and don't select "Create a page" or "Create a block" and click "Continue & edit".
* Remove *"Content: Post date (desc)"* from Sort criteria.
* Under *Contextual Filters* add *"Content: Nid"*; under *"When the filter Value is not available"*, select *"Provide default value, Type - Content ID from URL"*; under *"When the filter value is available or a default is provided"* select *"Specify validation criteria"*, *"Validator - Content"*, under *"Content types"* select *"Article"*, and then click *"Apply (all displays)."*
* Remove *"Content: Title from fields"* and add *"Content: Tags (Tags)"*, *"Content: Category (Category)"*, *"Content: Comment count (Comments)"* and *"Content statistics: Total views (Total views)"*.
* Under *"Relationships"* add *"Content: Author"*, and check *"Require this relationship"*; click *"Apply (all displays)"*.
* Under *"Fields"*, add *"(author) User: Name"* and *"(author) User: Picture"*.
* Under *"Pager"*, click on *"Full"* and *"Display a specified number of items"*; click *"Apply"*. At *"Items to display"* set `1`; click *"Apply"*.
* Then you need to add a display to this view: click on *"Add button"* and select *"Content pane"*.
* Under *"Pane settings"*, click *"Edit"* at *"Argument input"*; at *"Content: Nid source"*, select *"From context"*; at *"Required context"*, select *"Content ID"* and check *"Context is optional"*; click on *"Apply"*.
* Go to `Structure/Quicktabs`, click on *"Add Quicktabs Instance"*, and scroll down; you'll find a table. At *"Tab type"*, select *"view"*; at *"Select a view"*, choose the view you created; at display select \*"panel\_pane\_1: Content pane"\*; give a name in "Tab title", and click on *"Save"*.
* Go to Structure/**Blocks** (`admin/structure/block`) find your quick tab block, and put it in articles pages.

Now play with CSS.

Here is my view export:

```
$view = new view;
$view->name = 'info_about_the_current_article_w';
$view->description = 'I try to create a custom content pane (block) that display the information about who written the article that is viewed, etc.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Info about the current article when is viewed';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = 1;
/* Field: Content: Tags */
$handler->display->display_options['fields']['field_tags']['id'] = 'field_tags';
$handler->display->display_options['fields']['field_tags']['table'] = 'field_data_field_tags';
$handler->display->display_options['fields']['field_tags']['field'] = 'field_tags';
$handler->display->display_options['fields']['field_tags']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['external'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['field_tags']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['field_tags']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['trim'] = 0;
$handler->display->display_options['fields']['field_tags']['alter']['html'] = 0;
$handler->display->display_options['fields']['field_tags']['element_label_colon'] = 1;
$handler->display->display_options['fields']['field_tags']['element_default_classes'] = 1;
$handler->display->display_options['fields']['field_tags']['hide_empty'] = 0;
$handler->display->display_options['fields']['field_tags']['empty_zero'] = 0;
$handler->display->display_options['fields']['field_tags']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['field_tags']['group_rows'] = 1;
$handler->display->display_options['fields']['field_tags']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_tags']['delta_reversed'] = 0;
$handler->display->display_options['fields']['field_tags']['delta_first_last'] = 0;
$handler->display->display_options['fields']['field_tags']['field_api_classes'] = 0;
/* Field: Content: Category */
$handler->display->display_options['fields']['field_categories']['id'] = 'field_categories';
$handler->display->display_options['fields']['field_categories']['table'] = 'field_data_field_categories';
$handler->display->display_options['fields']['field_categories']['field'] = 'field_categories';
$handler->display->display_options['fields']['field_categories']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['external'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['field_categories']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['field_categories']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['trim'] = 0;
$handler->display->display_options['fields']['field_categories']['alter']['html'] = 0;
$handler->display->display_options['fields']['field_categories']['element_label_colon'] = 1;
$handler->display->display_options['fields']['field_categories']['element_default_classes'] = 1;
$handler->display->display_options['fields']['field_categories']['hide_empty'] = 0;
$handler->display->display_options['fields']['field_categories']['empty_zero'] = 0;
$handler->display->display_options['fields']['field_categories']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['field_categories']['field_api_classes'] = 0;
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['label'] = 'Comments';
$handler->display->display_options['fields']['comment_count']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['external'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['comment_count']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['trim'] = 0;
$handler->display->display_options['fields']['comment_count']['alter']['html'] = 0;
$handler->display->display_options['fields']['comment_count']['element_label_colon'] = 1;
$handler->display->display_options['fields']['comment_count']['element_default_classes'] = 1;
$handler->display->display_options['fields']['comment_count']['empty'] = '0';
$handler->display->display_options['fields']['comment_count']['hide_empty'] = 0;
$handler->display->display_options['fields']['comment_count']['empty_zero'] = 0;
$handler->display->display_options['fields']['comment_count']['hide_alter_empty'] = 0;
$handler->display->display_options['fields']['comment_count']['separator'] = '';
$handler->display->display_options['fields']['comment_count']['format_plural'] = 0;
/* Field: Content statistics: Total views */
$handler->display->display_options['fields']['totalcount']['id'] = 'totalcount';
$handler->display->display_options['fields']['totalcount']['table'] = 'node_counter';
$handler->display->display_options['fields']['totalcount']['field'] = 'totalcount';
$handler->display->display_options['fields']['totalcount']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['external'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['totalcount']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['totalcount']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['trim'] = 0;
$handler->display->display_options['fields']['totalcount']['alter']['html'] = 0;
$handler->display->display_options['fields']['totalcount']['element_label_colon'] = 1;
$handler->display->display_options['fields']['totalcount']['element_default_classes'] = 1;
$handler->display->display_options['fields']['totalcount']['empty'] = '0';
$handler->display->display_options['fields']['totalcount']['hide_empty'] = 0;
$handler->display->display_options['fields']['totalcount']['empty_zero'] = 0;
$handler->display->display_options['fields']['totalcount']['hide_alter_empty'] = 0;
$handler->display->display_options['fields']['totalcount']['separator'] = '';
$handler->display->display_options['fields']['totalcount']['format_plural'] = 0;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['external'] = 0;
$handler->display->display_options['fields']['name']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['name']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['name']['link_to_user'] = 1;
$handler->display->display_options['fields']['name']['overwrite_anonymous'] = 0;
$handler->display->display_options['fields']['name']['format_username'] = 1;
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['relationship'] = 'uid';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['picture']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['picture']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['picture']['alter']['external'] = 0;
$handler->display->display_options['fields']['picture']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['picture']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['picture']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['picture']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['picture']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['picture']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['picture']['alter']['trim'] = 0;
$handler->display->display_options['fields']['picture']['alter']['html'] = 0;
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['picture']['element_default_classes'] = 1;
$handler->display->display_options['fields']['picture']['hide_empty'] = 0;
$handler->display->display_options['fields']['picture']['empty_zero'] = 0;
$handler->display->display_options['fields']['picture']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['picture']['link_photo_to_profile'] = 1;
$handler->display->display_options['fields']['picture']['image_style'] = 'thumbnail';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['nid']['specify_validation'] = 1;
$handler->display->display_options['arguments']['nid']['validate']['type'] = 'node';
$handler->display->display_options['arguments']['nid']['validate_options']['types'] = array(
  'article' => 'article',
);
$handler->display->display_options['arguments']['nid']['validate_options']['access'] = 0;
$handler->display->display_options['arguments']['nid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['nid']['not'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Content pane */
$handler = $view->new_display('panel_pane', 'Content pane', 'panel_pane_1');
$handler->display->display_options['argument_input'] = array(
  'nid' => array(
    'type' => 'context',
    'context' => 'entity:node.nid',
    'context_optional' => 1,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Content: Nid',
  ),
  'uid' => array(
    'type' => 'context',
    'context' => 'entity:user.uid',
    'context_optional' => 1,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Content: Author uid',
  ),
);

```

---

I found an easier way to do that: Install the Display suite module; you can watch this screencast made by swentel on Youtube.

---
Tags: 7, views
---


# Question
Title: How can I set node/entity references automatically using rules?
Use case: On my site, when a user registers, four nodes of four different content types are automatically created using rules. I would like references to these nodes to be stored using node/entity reference\* fields in the user profile. I want to use rules to assign each node to the respective field in the user profile automatically. Is there a way to configure a rule to do this?

I tried using the rules "Set a data value" to set the user profile field to the created node but that didn't work-- it doesn't give an error, but after the rule is triggered the reference is still unset.

* I wrote "entity/node" reference because I am happy to use either the entity reference or the references module, so long as I can get a solution.

# Answer
I suggest you take a look at the Relation module. We have added rules support specifically for this type of use case, so that should do it for you.

If what you are trying to do is somehow beyond the capabilities of the current rules integration, you can open a feature request, and we will attempt to work it out.
> 0 votes

# Answer
For what it's worth, you can do this with entity references & rules alone. Nodeone.se has a video covering exactly this scenario. Relation has great potential, and is a much more intelligent way to go about relationships, but it can be tough to use (especially for non-devs) because it lacks a strong way to make new references.
> 2 votes

---
Tags: 7, rules, nodes, entities
---


# Question
Title: How to add body class that carries the menu depth of the current page?
I am on Drupal 7. On the body tag, I need to create a new class that will detect the current page's menu depth. The class could carry the ID of the menu, then something that would detect the current page's menu depth. It could be something like: "primary-depth-0" for the top menu items, then "primary-depth-1", "primary-depth-2" and so forth... Is it easy to code that on template.php? I assume I have to add a new item into the $classes array...

Thank you.

# Answer
I did something similar in the past, but I can't remember on which project, so I don't have working code.

Inside a template\_preprocess\_html, you get the breadcrumb via menu\_get\_active\_breadcrumb. You then walk the breadcrump keeping track of depth, comparing the paths against the current path. When you find a match, you end the walk and then

```
$variables['classes_array'][] = "menu-depth-" . $depth;

```

I am pretty sure this is what I did.
> 3 votes

---
Tags: routes, theming
---


title: Views using taxonomy

text:
# Question
Title: Views using taxonomy
I have a simple Drupal 6 website with a content type 'Software' this has various CCK fields regarding evaluation of the software. The software has been evaluated by a speech therapist and the website is used by people suffering from Aphasia to help them pick the software that is right for them.

One of the pages on the site has a comparison table built using views, selecting nodes with their CCK fields. http://www.aphasiasoftwarefinder.org/comparison-table

I appologise for the amature look of this site, I knew very little about theming and am still learning.

I am now re building this site in Drupal 7 and it has become much more complex with regard to the various evaluation criterion and is also including Apps and other software that may be useful to people. I decided to use Taxonomy instead of CCK fields as there about about 7 areas or evaluation (Taxonomy volcabulary) each with its own list of terms.

Everything is working well except when I come to creating a comparison table. I want to be able to use the Taxonomy terms that are the same as the CCK evaluation fields from the Drupal 6 site but I am strugling as to how I can achieve this. So I have a Taxonomy Volcabulary 'Evaluation' with a list of 8 or so terms, I want to be able to separate those terms out as columns along the top of the view and list the nodes down the side, then populate the colunms with a tick if they have that taxonomy term.

If someone could point me in the direction of any tutorials that may help towards this goal or come up with any ideas on how this could be done???

Many thanks Julie

# Answer
> 1 votes
You can use the `Taxonomy : All Terms` to display the terms each node has associated with a single vocabulary. You would have to spend some time on styling them properly.

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


# Question
Title: Incorporate dropdown list of nodes into a webform to link webform results to said content
I am trying to link the results from a webform comment survey to content that was previously generated within a site so that the webform\_submissions table in the database shows the node those answers are attached to.

I am planning to use a "node reference" dropdown to the content type I need, but that's as far as I've gone.

Any ideas or suggestions are most appreciated.

# Answer
You can create your own predefined lists by using the webform\_webform\_select\_options\_info() hook.

```
<?php
/**
* Implements hook_webform_select_options_info().
*/
function yourmodule_webform_select_options_info() {
  $items = array();
  $items['contentchoice'] = array(
    'title' => t('Content Choice'),
    'options callback' => 'webform_options_yournodes',
  );
  return $items;
}

```

Then generate your list of nodes using

```
/**
* Webform options info callback.
*/
function webform_options_yournodes() {
  $mynodes = array(
  //build your array up here
  );
  return $mynodes;
}

```
> 1 votes

# Answer
Add to webform a select options widget. Then in your implementation of hook\_form\_alter

```
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_webform_name') {
        $nodes = array();
        /*The WHERE section in the query needs to be adjusted to meet your requirements or removed at all if you need to have all nodes in the dropdown*/
        $results = db_query('SELECT * FROM {node} WHERE type=:type', array(':type' => 'article'));
        foreach($results as $result) {
            $nodes[$result->nid] = $result->title;
        }
        $form['submitted']['your_select_widget_name']['#options'] = $nodes;
    }
}

```

I assumed that you use D7. For D6 there might be slight differences in the code.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How to weight a block above a custom form
I'm creating a page with a form with the hook\_menu:

```
function my_module_menu() {
  $items['rsvp'] = array(
    'title' => 'My Page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form_search'),
    'access arguments' => array("access content"),
    'access callback' => TRUE,
  );
}

```

I also have created a block that is to display in the content area of the rsvp page. Right now the form shows above the block. How do I reverse that?

# Answer
In Drupal 7 the output from a page callback will be rendered inside the standard 'Main page content' block. As such it is available to be re-ordered like any other block in the system through the admin UI.

All you need to do is visit the administer blocks page ( http://mysite.com/structure/block ) and move your block above the 'Main page content' block.
> 2 votes

---
Tags: 7, forms, blocks
---


# Question
Title: Provide an interface to edit only one field of a content type?
I am trying to create a 'start a bounty' system, just the same as on this site using userpoints. There should be a link 'Start a bounty' which allows the question creator to start a bounty using his points. I am using userpoints for this purpose and I created a field where the user can select the number of points he would liek to give out for a correct answer. But this can only be done on node creation or while editing the entire node. The question is - how to be able to select the number of points only after clicking on 'start a bounty' without the need of editing all the remaining fields. So ideally there should be a popup with dropdown field that edits only this particular field. I guess one approach is to create a node edit form with this field only (is this possible at all?) and put it in the ajax popup... Any ideas / advice?

# Answer
> 4 votes
There is a new module by Earl Miles, the creator of Views, that does this in Drupal 7 called the Field API Pane Editor. Unfortunately, because this is a new solution for D7 and Earl Miles tends not to reinvent the wheel, I don't think there is any existing module that you can download for this use case in D6.

# Answer
> 1 votes
I'm looking for exactly that feature, luckily I'm on 7 ;-)

Otherwise I would probably have used a hook\_form\_alter to hide the other fields on the edit form when you want to add the bounty. For example when you edit the form with /node/123/edit/bounty then hide other form field.

**Update:**

Checkout jeditable, editablefields and this blog

---
Tags: nodes, entities, 6
---


title: Creating JS file on the fly

text:
# Question
Title: Creating JS file on the fly
I have a code that generate a big bunch of javascript code and I would like to create a .js file on the fly and include the code in it.

The code would be reconstructed at each cache destruction. The file would be used by all visitors.

Any ideas what I could use to make this possible? Or there's no "drupal way" to do this?

thank's!

# Answer
> 2 votes
I would do this in this way:

```
function YOUR_MODULE_init(){
    drupal_add_js('path/you/want/to/use/to/include/javascript.js');
}

function YOUR_MODULE_menu() {
    $items = array();
    $items['path/you/want/to/use/to/include/javascript.js'] = array(
        'title' => 'Generated js',
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name'
    );
    return $items;
}

function your_function_name() {
    $js = ... your code that composes js here ... ;
    print $js;
    exit;
}

```

---
Tags: javascript, caching
---


# Question
Title: Get field names of view from within module
After using `views_get_view($view_name)` how do I get the names of the fields? The list of field names (arranged correctly) is going to be pushed onto an array following which will be all the results. I can see in the return value from `views_get_view()` the `field` array, but how do I get them as they would be displayed in a table, that is, correct capitalization, spaces instead of underscores, etc.?

# Answer
> 2 votes
There is an array of fields in the display object:

```
$view->display['YOURDISPLAYNAME']->display_options['fields']

```

for example if you want to retrieve list of field names of the view arbitrary display, you'd need to do something like this:

```
function get_views_field_names($view_name, $display = 'default') {
   $view = views_get_view($view_name);
   $result = array();
   foreach($view->display[$display]->display_options['fields'] as $field){
       $result[] = $field->label;
   }
   return $result;
}

```

and somewhere in the code

```
$fields = get_views_field_names('YOURVIEWNAME', 'YOURDISPLAYNAME');

```

---
Tags: entities, views
---


title: How to make the main menu expanded?

text:
# Question
Title: How to make the main menu expanded?
I have set main menu items expanded but when I print them in page.tpl.php($main\_menu) there are no children for menu items.How can I make them expanded?

# Answer
That depends on the theme you're using. Unfortunatelly, some of them -- including the Dupal's default Bartik -- don't display children in the main menu.

You can either install a theme that does display menu children, or -- if you are using Bartik -- you can make use of the Drop-down menus subtheme for Bartik or follow the HOWTO create dropdown menus for Bartik in Drupal 7.
> 4 votes

# Answer
Go to `admin/structure/menu/manage/main-menu` and edit the parents that have children that you wish to show, and click the tickbox 'show expanded'

Or alternatively install the module http://drupal.org/project/menu\_expanded which brings back the tickbox on the menu 'list items' page ala drupal 6

Hope this helps
> 4 votes

# Answer
If you are loading your menu via page.tpl and it doesn\`t have children viewed - you can add it via block and it will have ones.
> 1 votes

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


# Question
Title: How do I make a page available via only a single URL?
Is there a way to make the front page available via only a single URL?

The normal method is to use a `<link rel="canonical">` meta tag, but this is not good for SEO.

# Answer
That's what the `<link rel="canonical">` meta tag is *for*.

I'm not sure where you've got the information that this meta tag is not good for SEO, but I'm afraid your source is incorrect; the exact opposite is true. This is what Google have to say on the matter:

> Carpe diem on any duplicate content worries: we now support a format that allows you to publicly specify your preferred version of a URL. If your site has identical or vastly similar content that's accessible through multiple URLs, this format provides you with more control over the URL returned in search results. It also helps to make sure that properties such as link popularity are consolidated to your preferred version.

As you can see this is what Google recommend you do to avoid the problem of SEO penalties for duplicate content. This information is several years old and hasn't changed.

To my knowledge the following modules will add a canonical link to your documents:

1. Global Redirect
2. Redirect
3. Meta Tag

There may well be more though. The 2 redirect modules above will probably help you out even further, as they will automatically perform a 301 redirect to the canonical URL when any of the others are visited. Google also encourages the use of such headers in this situation.

Be sure to read the whole Official Google Webmaster blog post linked to above to understand why this method is the correct one, it's pretty important in terms of SEO these days.

Oh, and if I were you I'd be suspicious of anything else your original source for this tells you...they obviously don't know much about SEO!

Further Reference:

And there are literally dozens more...search Google for "SEO canonical".
> 12 votes

---
Tags: 7
---


# Question
Title: How to write a db_query with condition on a datefield with enddate - value1 and value2
Trying to do following select query on a node with datefield with endvalue:

```
  SELECT nid FROM {node}
  WHERE uid = $uid
  AND type = $type
  AND field_mytime(value) > $daystart
  AND field_mytime(value2) < $dayend;

  db_query('SELECT nid FROM {node}
     WHERE uid = :uid AND type = :type AND field_mytime['und'][0]['value'] > :value, field_time['und'] [0]['value2'] < :value2',
    array(':uid' => $u, ':type' => 'mycontenttype', ':value' => $daystart, ':value2' => $dayend))->fetchField();

```

This do not work of cource: field\_mytime\['und'\]\[0\]\['value'\] field\_mytime\['und'\]\[0\]\['value2'\]

But what will work? Please help.

# Answer
Fields are not stored in the node/entity table to which they relate, it would be quite inefficient to do that.

Drupal 7 introduced the new `EntityFieldQuery` class to help you build up these kinds of queries. I'd recommend reading the docs, but for your purposes the code would look something like this:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type)
  ->propertyCondition('uid', $uid)
  ->fieldCondition('field_mytime', 'value', $daystart, '>')
  ->fieldCondition('field_mytime', 'value2', $dayend, '<');

$results = $query->execute();
if (isset($results['node'])) {
  // Load all node objects based on the results of the query
  $nids = array_keys($results['node']);
  $nodes = node_load_multiple($nids);
}

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Adding a clearfix class to hook_node_view
Ok, so what I want to do is to add a class of **clearfix** whenever Drupal outputs a node view with inline links.

I've been looking around and I figured hook\_node\_view() is what I need to alter.

Looking in node.module I find the following code:

```
$node->content['links'] = array(
    '#theme' => 'links__node',
    '#pre_render' => array('drupal_pre_render_links'),
    '#attributes' => array('class' => array('links', 'inline')),
);

$node->content['links']['node'] = array(
    '#theme' => 'links__node__node',
    '#links' => $links,
    '#attributes' => array('class' => array('links', 'inline')),
);

```

So I guessed I somehow have to add a third value to this array trough my template.php file, but none of the gazillion ways I tried worked.

# Answer
You can do this in a `hook_preprocess_node()` function in your theme's template.php file:

```
function MYTHEME_preprocess_node(&$vars) {
  if (isset($vars['content']['links'])) {
    $vars['content']['links']['#attributes']['class'][] = 'clearfix';
  }
}

```

Remember to clear Drupal's caches once you've added the function so the system picks it up.
> 4 votes

---
Tags: nodes, theming
---


title: How do I add PHP to full nodes?

text:
# Question
Title: How do I add PHP to full nodes?
Is it possible to add PHP bits to nodes? I would like to achieve something like this:

```
<p>Some paragraph I blablabla blablabla blablabla blablabla...<p>
<?php Some PHP code I with echo statements ?>
<p>Some paragraph II blablabla blablabla blablabla blablabla...<p>
<p>Some paragraph III blablabla blablabla blablabla blablabla...<p>
<?php Some PHP code II with echo statements ?>
...

```

If yes, how can I achieve this?

# Answer
You would use the PHP Filter, but I would highly recommend AGAINST it as it doesn't restrict anything, and with it, your users could enter things far more "exciting" than just echo statements...
> 2 votes

---
Tags: 7
---


title: How to delete a Drupal sandbox project?

text:
# Question
Title: How to delete a Drupal sandbox project?
This thread: http://drupal.org/node/1077884 indicates we can delete our own sandbox projects, but I'm a little confused as to how this is done.

I see nothing on the UI on drupal.org that would allow this. If this is done directly with git, I would appreciate some guidance.

# Answer
> 8 votes
Go to `http://drupal.org/node/<yoursandboxnid>/edit` and at the bottom of the edit page is a delete button.

---
Tags: community-official-site
---


title: How to add variables to $conf array?

text:
# Question
Title: How to add variables to $conf array?
To modify some default settings for the Feeds module, I need to set a variable in the $conf array. What is the right way to achieve this?

I've tried adding it in the settings.php file (currently on local), but it doesn't appear in the variable table (even after restarting the server). "Clear all caches" didn't change anything, either. What am I missing?

What I am actually trying to do is to set `$conf['feeds_process_limit'] = 15;` exactly in the same way as described on http://drupal.org/node/1363094 and http://drupal.org/node/1393450; after adding it to the settings.php file, the result is the same: The amount of imported items isn't being limited.

How can I ensure the variable was set as in the settings file, and not to the default value?

# Answer
I think that the best way to modify default settings is to install the strongarm and the features module. Then use features to export the variables you want to modify into strongarm files where you can set the value.

To do this manually, I think you need variable\_set, which will put the value into the database which populates $conf.

http://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable\_set/7
> 0 votes

# Answer
Your variables will not show up in the variables table; variables are loaded from the database first and are then overwritten by `settings.php`. You might need to add a global $conf to access the variables in your `settings.php`.
> 1 votes

---
Tags: 7, configuration
---


title: Hide the <front> item in the main menu

text:
# Question
Title: Hide the <front> item in the main menu
I want to remove the link to the homepage from the main menu.

I can delete it with:

```
menu_link_delete(NULL, "<front>");

```

But I am worried about needing to undo that at some point in the future, or causing problems when some module expects that link to exist.

It looks like `menu_link_save` allows marking a menu item as "hidden", but I can't figure out how to get the mlid so that it knows I want to edit an existing menu item.

I have tried calling `menu_main_menu`, but the result doesn't appear to have a `main_menu['<front>']` element.

Any suggestions?

# Answer
Using the Features module let me export the menu, at which point it was easy to set 'hidden' =\> '1' on the 'main-menu:' link.
> 1 votes

---
Tags: routes
---


# Question
Title: Looking for an employee scheduling module
Using D7, I need to be able to schedule call center staff. Is there any "employee scheduling" module out there?

If not, are there a combination of modules I can use to create such a feature?

# Answer
I created a shift scheduler module about a year ago.

Documentation and Releases: http://code.google.com/p/drupal-shift-scheduler/

Video tutorial: http://www.youtube.com/watch?v=9pPHtoE2ivg

Development: http://drupal.org/sandbox/mcstrother/1075572

I'm no longer actively developing it, but I believe both the 6 and 7 versions are actively in use on at least one production site each with no new bugs reported.
> 1 votes

---
Tags: datetime
---


# Question
Title: Error while creating a node with file attachment through custom PHP code
I need to programmaticly create a node in Drupal 7 i followed availible tutorials and came up with this code:

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$md5 = md5(strtotime("now"));

$field_customer_name = 'NAthtn';
$field_customer_email = "something@gmail.com";
$field_downloads_count_left = '11';

$filename = 'file123.zip';
$filepath = 'sites/default/files/private/file123.zip';

// Create managed File object and associate with file field.
$file = new StdClass();
$file->uid = 1;
$file->uri = $filepath;
$file->filename = $filename;
$file->filemime = file_get_mimetype($file->uri);
$file->status = 1;
$file = file_copy($file, 'public://', FILE_EXISTS_REPLACE);

$node = new stdClass();
$node->type = 'download';
node_object_prepare($node);

$node->title    = $md5;
$node->language = LANGUAGE_NONE;

$node->field_customer_name[$node->language][0]['value'] = $field_customer_name;
$node->field_customer_email[$node->language][0]['value'] = $field_customer_email;
$node->field_downloads_count_left[$node->language][0]['value'] = $field_downloads_count_left;
$node->field_file[$node->language][0]['value'] = (array)$file;

$path = $md5;
$node->path = array('alias' => $path);

node_save($node);

```

I am getting the following error in the log:

PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file\_usage} (fid, module, type, id, count) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> \[:db\_insert\_placeholder\_1\] =\> file \[:db\_insert\_placeholder\_2\] =\> node \[:db\_insert\_placeholder\_3\] =\> 51 \[:db\_insert\_placeholder\_4\] =\> 1 ) in file\_usage\_add() (line 664 of /home/content/16/5470416/html/download/includes/file.inc).

# Answer
replace

`$node->field_file[$node->language][0]['value'] = (array)$file;`

with

`$node->field_file[$node->language][] = (array)$file;`

Also, add `$node->validated = TRUE;` before `node_save($node);`
> 3 votes

---
Tags: entities, files, nodes
---


# Question
Title: How do you create a make file and minify it for pdf.js?
I want to install the PDF module. In the modules "Getting Started" instructions, I read the following sentence:

> Make pdf.js file in the pdf.js/build directory by following the README.

The README file includes these instructions:

> In order to bundle all `src/` files into a final `pdf.js`, issue:
>
> ```
> $ make
>
> ```
>
> This will generate the file `build/pdf.js` that can be included in your final project. (WARNING: That's a large file! Consider minifying it).

How do you accomplish this from a Windows machine?
Does it require the web server to be a linux machine?
Does this require SSH'ing into the remote host?

# Answer
> 1 votes
> How do you accomplish this from a Windows machine?

No, you can't run `make` command in Windows; maybe you want to check cygwin.

> Does it require the web server to be a linux machine?

Final .js file can be placed anywhere, Windows or Linux. You need a Linux machine to create it.

> Does this require SSH'ing into the remote host?

If you want run `make command` in your server, you need ssh-ing.

---
Tags: 7, files
---


# Question
Title: How do I re-arrange the $node->taxonomy array back into a hierarchical tree?
In a node I'm creating, there is a hierarchical select widget. The widget saves the 'deepest' term in a given taxonomy.

These terms come out in the $node-\>taxonomy array in tpl files.

I want to build the tree right back up to the last parent. How do I do this? What is the algorithm? I have a complete sphagetti mess that's not even worth posting here, right now. I have a feeling there's recursion involved somewhere, but I'm missing the specifics - pseudocode please?

# Answer
> 3 votes
I don't know of an API function that can do this but the following code should help:

```
$tid = 4; // Your term id

// Grab all of the parents of this term (including the term itself)
// in reverse order.
$parents = array_reverse(taxonomy_get_parents_all($tid));

$tree = array();

// Get a reference to the root of the array. This reference will be updated
// in each iteration of the loop to refer to the array of children added to
// the term.
$ref = &$tree;
foreach ($parents as $term) {
  // Add the current term to the relevant root/children array.
  $ref[$term->tid] = $term;

  // If the current term is NOT the original child term, we add an array of
  // children to the term and update the array reference to point to it.
  if ($term->tid != $tid) {
    $term->children = array();
    $ref = &$term->children;
  }
}

```

By the time that loop has run the `$tree` variable will be a hierarchical representation of the original term's parents, with each child term in the `children` key of it's parent term object.

I've only tested this on terms that have a single parent; if you've got terms with multiple parents I think you'll struggle to get this to work.

---
Tags: 6, taxonomy-terms
---


# Question
Title: PHP code to add a link to the configured default home page
The default home page of a site can be configured in Home » Administration » Configuration » System » Site information.

I have a node instance (with PHP code text format) and I need to insert a link to the default home page of my site, knowing that it can be reconfigured later. In other words, I can't put a static link, I need to fetch info from Drupal (if possible).

How can I create such a link with a PHP code snippet? Is this possible?

**Solution**

I got away with:

```
<?php
    $ttmp = variable_get('site_frontpage', url());
    echo '<a href="/'.$ttmp.'">Home</a>';
?>

```

# Answer
If you mean you want programmatically get the value in your Site Configuration, then this works for me: `<?php print variable_get('site_frontpage', url()) ?>` although I'm not sure this will work in multilingual environment.
> 2 votes

---
Tags: 7, navigation
---


# Question
Title: Allowing file-transfer to use sftp or ssh?
I have my own dev-server that I installed with Ubuntu 11.04. When I set it up, I was fairly new to the whole "server thing", so I'm not sure that I set up everything 100% up to industry standards.

The problem I am having, is that trying to automatically update things almost never works when using drupal's UI.

I usually got around this, by just ssh-ing into my server, and using drush to update everything.

The problem now, however, is, that instead of updating the site, I am trying to install "apps" (not modules), and I am not sure how to do this with drush. (plus I want to figure out how to fix this FTP problem anyway)

What usually happens, is that I will get an error (not a specific one, just one that is saying `Error installing nameofmodule`)

Recently though, I tried using a different user account with direct access to the folder (it being the user's home folder), and I am getting the folowing error

```
Warning: ftp_login(): Login incorrect. in FileTransferFTPExtension->connect() (line 59 of ..../includes/filetransfer/ftp.inc).
Failed to connect to the server. The server reports the following message:
Cannot log in to FTP server. Check username and password

```

I know the username and password are correct, I checked them more than a dozen times in terminal, however, I realized, that whenever I ftp into the server, I get an error if I use `ftp`, but I instead have to use `sftp`.

Is that what my problem is? If it is, how can I get Drupal to use `sftp` or `ssh` to transfer files instead of just `ftp`?

PS. If it helps, I am using the OpenEnterprise 7.x-1.x-dev distribution of Drupal

# Answer
I would still like to be able to use `sftp`, but for now, I was able to set up `ssh` here's how I did it:

```
user$ sudo apt-get install libssh2-php
user$ sudo /etc/init.d/apache2 restart

```

And now I can use the update manger with ssh, which works, for now......
> 1 votes

---
Tags: 7, files
---


# Question
Title: What is the performance impact of modules that use Field API instead of a custom way of accessing the database?
This answer states that it is better to share fields among content types when possible because each field added slightly negatively impacts performance. Assuming this answer and my interpretation of it is correct, for nodes that already have lots of fields for unavoidable reasons, would avoiding the use of modules that make use of the Field API when alternatives are available enhance site performance?

For example:

# Answer
That can't be answered in a generic way, I think. Some facts:

* Each field does add a certain overhead to the system and it means more queries when loading and saving e.g. nodes.
* Being able to store information as a separate entity that has the information as properties is obviously much faster than having everything in fields.
* However, modules that stores additional information to entities on it's own tables results in additional queries as well.
* The advantage of field API is that the storage is pluggable, so you could for example use it together with MongoDB which could possibly drastically improve the performance, with some drawbacks however.
* Fields also have read cache built-in so that subsequent entity loads will use the cache to load the field content. A module that does not use fields might not have it's own custom caching.
* There is still the generic overhead added by fields but work is ongoing to improve that situation in Drupal 8 and it might possibly be backported as well.

So a module isn't more performant just because it uses fields for storing data or not, there are many more factors and it also depends on how the site is configured.
> 5 votes

---
Tags: performance, entities
---


# Question
Title: PHP drupal added css file does not appear in page source
I have enabled LessCSS on my site and I have a node instance where I want to add a specific CSS.

I used the following piece of code:

```
<?php
    drupal_add_css( '/sites/MyStuff/introduction.css');
?>
<div id="myid" class="box">
    ....some text
</div>

```

Yet, there is no import or link statement in my page source code for `introduction.css`. I am not using compression. FireBug does not mention loading an `introduction.css` file. I have doubled-checked and the file is properly located in the folder.

What could cause this issue? And how to solve it?

**P.S.:**

The css file contains the following:

```
.box {
    color: green;
    background-color: red;
}

```

The styling is not applied on the page.

# Answer
From https://stackoverflow.com/questions/1410494/drupal-add-css-not-working, the solution is to use CSS Injector. I tried and it worked.

**Update**

I maintain a page explaining how to use CSS Injector too add CSS to a page.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: OpenLayers module only displays latitude/longitude instead of map
So I began experimenting with OpenLayers because I'm creating a content type that requires it.

I followed the Step-by-step instructions from the docs (added geofield to node, create data overlay view, cloned and set up my map and created a page view to display the map)... but what I actually need is to somehow embedded the maps for each post. What is the next step for something like this? Right now in each node I see the node pictures and this: POINT (-0.138513 50.8239).

# Answer
> 0 votes
Go to your display settings for your content type and choose 'OpenLayers', then click the gear icon and Select which OpenLayers map you would like to use. Only maps which have the geofield placeholder layer may be selected. If your preferred map is not here, add the geofield placeholder layer to it first.

---
Tags: views, nodes, javascript
---


# Question
Title: Creating a temporary content type on the fly?
I want to create a temporary content type, and a node of that type, in code. It preferably should not live past page load. Can I do that?

For the reason to this very strange request, please see Using field widgets in non-field forms.

If you have suggestions for completely different solutions, then please take those to the linked issue, since this question is mainly a "support" question to the current answer to that question.

# Answer
```
$node_type = array(
  'type' => 'temporary_node_type', // This is the machine name.
  'name' => t('Temporary Node'), // This is the human name.
  'base' => 'node_content', // If you set this to your module name, then
                            // *your module's* hook_insert(), hook_delete(),
                            // etc. will get called in addition to
                            // hook_node_*()
  'description' => t('Description.')
  // A full list of options is at http://api.drupal.org/hook_node_info.
);

$node_type = node_type_set_defaults($node_type);

node_type_save($node_type);

// Do something with your node type. You can also add fields here if you
// would like.

node_type_delete($node_type);

```

Note 1: People with the "administrator" role will see this type on node/add every once and a while, depending on how often you do this.

Note 2: You want to use something more then a hard-coded string for your type attribute to avoid collisions.
> 1 votes

---
Tags: entities
---


# Question
Title: How to implement field formatters for entity properties
I created a custom ***entity*** using ***Entity API*** that has certain properties defined in `hook_schema()` and also declared in `entityPropertyInfo()`, a class extending `EntityDefaultMetadataController`.

So far so good.

Now I'd like for users to be able to customize if and how these properties get displayed when viewing the entities so I implemented hook\_field\_extra\_fields() and declared them.

Then, in my Controller which extends `EntityAPIController` I added the properties to the $content array in `buildContent()` as, outlined here.

It actually works pretty well and properties are rendered and respect the order and visibility settings in "Manage Display".

However, I can't seem to figure out how to add settings in Manage Display to customize the label positioning (`inline/above/hidden`) and, more importantly, how to specify custom formatters for these properties.

Any clues?

# Answer
You could create a module providing a "`property`" field type. Store the the property to be formatted as an instance setting and then apply a formatter to that. It should be relatively straightforward. Relation module has a dummy field module which might help you in figuring out how to code this.
> 7 votes

# Answer
as you can see in `field_ui_display_overview_form` in `modules/field_ui/field_ui.admin.inc` the page `Display setting` will fill with `$instances` and `$extra_fields`:

```
$instances = field_info_instances($entity_type, $bundle);
$field_types = field_info_field_types();
$extra_fields = field_info_extra_fields($entity_type, $bundle, 'display');

```

in this function there is two loops which create the page:

```
foreach ($instances as $name => $instance) {
   ...
}

```

and

```
foreach ($extra_fields as $name => $extra_field) {
   ...
}

```

and only in first loop which iterate in fields there is options for `label` and `formatter`

so if you want this functionality on your properties (as @Clive said):

> You would need to implement that whole mechanism yourself
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to add in-line styles to addressfield field?
How can I add an inline style to an addressfield field without having to modify the template files?

I'm using the addressfield as a field in my user object and am trying to load the full user object in the commerce order display page.

This page is being rendered using the admin theme which is the default Seven theme. I'm trying to avoid having to modify that default theme for this purpose.

Here's the relevant code:

```
function MYMODULE_entity_view($entity, $type, $view_mode, $langcode){
  if ($type == 'commerce_order') {
    $uid = $entity->uid;
    $user = user_load($uid);
    $renderable_user = user_view($user, 'default');  //<-- Can I modify this array to add an inline style?
    $entity->content['customer_info'] = array(
      '#weight' => -2,
      '#markup' => render($renderable_user),
      );
    }
}

```

Or perhaps I'm going about this the wrong way and there's another way to modify the output of this page?

# Answer
> 2 votes
Check out the CSS Injector module. It won't do inline styles, but you could always write a selector (which is the best practice anyway).

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


# Question
Title: How to run a Drush command in interactive mode
I want Drush to actively output messages instead of putting them into a buffer and then outputting them when it is done running. Now Drush has an interactive mode that I think will do this. However I can't seem to figure out how to get it to work.

I can modify either Drush or my Drupal module (that contains Drush commands) to do this. I just need to know what to do to accomplish this.

I am running Drush 4.4 against Drupal 6.22.

Any thoughts or ideas?

# Answer
> 1 votes
The 'interactive' flag in Drush backend invoke is only used when Drush is going to programatically call another Drush command. In this instance, the interactive flag tells Drush to call the subcommand in a way that will allow user input.

The issue you reference above (drupal.org/node/1058874) is now standard in Drush 5. If you upgrade, you should find that Drush does a better job at showing incremental progress in some situations. Of course, there are also still some commands where Drush must first compose all of the output, then format it in a table, then output it. In these cases, the output will always be buffered.

---
Tags: 6, drush
---


# Question
Title: How to hide authoring information on webform for Drupal 7
I went to Administration \> Structure \> Content Types \> Webform \> Manage Display where I am supposed to find a check box to hide or display author information but there is nothing there. Any idea how I could hide this?

Thank you for your thoughts

Drupal 7 Webform 3

# Answer
> 15 votes
The author/date display is controlled in the edit form for the Webform content type, at http://mysite.com/admin/structure/types/manage/webform.

The checkbox you're looking for is here:

---
Tags: 7, webforms
---


# Question
Title: How can I show children in the taxonomy teaser views of parent/grandparent terms?
Lets assume we have a Taxonomy called Region

Asia - Thailand - Bangkok

If a post is tagged with Bangkok, would it show up in the teaser view on following pages:

/region/ /region/asia/ /region/asia/thailand

or would it only show here?

/region/asia/thailand/bangkok

If later is the case, what's the best way to show it in parent terms teaser views?

Thanks for your help in advance.

# Answer
You can try adding taxonomy as a hierarchical structure like

* Term 1
    + Term 1-1
    + Term 1-2
    + Term 1-3
* Term 2
    + Term 2-1

Then you can get the display using either

1. Taxonomy Menu Trails

And css as you wish.

Good Luck.
> 0 votes

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


title: Using Pathauto and custom nodes

text:
# Question
Title: Using Pathauto and custom nodes
I have 2 sections that are accessed as section1, section2 that have thier own node templates. Each section has a resource subsection, which should share a node template (node--resources.tpl.php).

How can I configure my url using Pathauto such that urls section1/resources and section2/resources, both use the node--resource.tpl.php? Is this possible? All attempts have failed.

# Answer
> 1 votes
You can define custom tokens such that they can be replaced by pathauto.

See Implementation with a custom Module

The idea is to define tokens such that they get displayed in pathauto's admin page. and we manage the token from our code; after checking conditions.

AS OP's request here's my **D6** code that i've implemented.

```
function MODULENAME_token_list($type = 'all') {
  $tokens['MODULENAME']['fullname'] = 'The Use\'r Display Name';
  return $tokens;
}

function MODULENAME_token_values($type, $object = NULL, $options = array()) {
  $tokens['fullname'] = _MODULENAME_get_display_name($object->uid);
  return $tokens;
}

function _MODULENAME_get_display_name($uid) {
  //load corresponding user and  get $displayname
  return $displayname;
}

```

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


# Question
Title: .info file having a name that is different from the name of the theme's folder
My .info file is prosperpro.info, but my theme's folder is named prosperpro8. I had not realized this difference because the code was working. When I realized this, and tried to changed the .info file back to prosperpro8.info, the code would no longer work.

I thought that the .info file required to have the same name of the theme's folder.

Am I wrong? If they must have the same names, how can I correct it? (Changing the file name will result in code break.)

# Answer
> 1 votes
You cant give same name for theme and module. I have found an article on drupal.org

> **How to Resolve module-theme name collision**
>
> When developing a site it can happen that a module and theme are being given the same name. This results in very weird behavior: overriding hooks can make your blocks disappear, print $content returns only 'array', hence disappearing admin interfaces which force us to alter the database to get back on track.
>
> Now we have to find out how to remove the new theme and switch back to an old one. if your site is big, with lots of content, then reinstalling is not an option. I tested this with MySQL, so these hints are for MySQL only.
>
> Make a backup of your database first. We are going to edit the dumped records, and reinsert the database. I used this method because using my favorite editor is way easier and safer than using MySQL shell (anyway we shouldn't edit a live site database).
>
> The theme name is registered in the following tables in your database: system, variables and block. Clear the cache manually, meaning to remove all the INSERT INTO `cache_` lines in order to see results. Change the 'default\_theme' value in `system`. Note that 's' stands for string length, so be sure you put the string length after the 's:'. Also make sure you change the value to an existing theme (available themes are listed in `system`). And remove, or rename your troublesome theme.
>
> The change in `block` is imperative, otherwise the blocks will not appear. Drop your old database from the sql server and insert the edited one. Voila, we have recovered from a theme crash.

© drupal.org

And

***Never give a module and a theme the same name***

Here's the D7 Patch

# Answer
> 0 votes
Here is the manual page for creating info files. - Structure of the.info file Those are the requirements for the .info file.

---
Tags: theming
---


# Question
Title: How to re-write/rename HTML output of a View Block wrapper ID?
Drupal newbie here. Would like to know how do I change the HTML wrapper ID of a View Block?

Currently I have a view that has two blocks.

1. The first block is the "Do's" block. HTML output: `<section id="block-views-do-s-block" class="block block-views contextual-links-region block-do-s-block block-views-do-s-block odd">`
2. The second one is a "Don'ts" block. HTML output: `<section id="block-views-do-s-block-1" class="block block-views contextual-links-region block-do-s-block-1 block-views-do-s-block-1 even">`

I would like to rename the "id" of the second block to make it more intuitive.

Screenshot: https://img.skitch.com/20120430-p8dtxdx7h8qa5augidx9gudjbn.jpg

How to do that? Thanks!

# Answer
Go to you view select block display "Do's" then Advanced -\> OTHER -\> Machine Name change this and it''ll change the id of your block.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to place custom menu in user profile
I have created a user menu as shown below

I am using Edit Profile and Me alias module and the menu system is as below

1. Edit Account : *user/uid/edit*
2. Edit Profile : *user/uid/edit-profile*
3. Logout : *user/logout*

This works fine but I am not able to display it on `http://localhost/user` or `http://localhost/users/uname` (alias to the former url). I wanted to show this menu only on that page.

In the 'Visibility settings' of the block, using 'Only on listed pages' option I tried various like *user*, *users/me*, *http://localhost/user*, *http://localhost/users/me*, but the menu is not appearing on the user page. When I check it with other pages, it works fine. Any idea what might be the cause?

# Answer
> 2 votes
I have been searching for this for 2 days now, and decided to go for bounty. But, didn't know the solution was so simple. I tried doing the same on fresh install of Drupal and it worked fine. And kept on adding the modules one by one, again testing the functionality for any change. It appeared to me that after disabling Menu token module, the requirement worked absolutely fine.
Then I checked to see if I gave a wrong token replacement. And the menu structure which i was using was as below

--**My Account** with path *\[node:url:absolute\]* which i thought would direct to same page.
----**Edit Account** with path *user/me/edit*
----**Edit Account** with path *user/me/edit-profile*
----**Logout** with path *user/logout*

And I used gave the path as \*user/\** in the *Visibility settings* of the block(highligted of corporate theme) as discussed in question and comments above,

The **Problem identified**(as per me) was that I was considering user profile page as a node which I think now is wrong, so the token *\[node:url:absolute\]* was actually a wrong token and hence the menu was not displaying on user page. What I did is changed it simply to *\[current-page:url\]* (as I wanted the user to be on same page, and I suppose we cannot give *#* in the path of the menu to achieve it)as shown in fig below and used the same visibility settings and it worked :)
So, basically the parent menu path was wrong which created the problem. Nevertheless, it was good learning experience!!

# Answer
> 1 votes
Your configuration will work fine, i hove tried a same scenario. See attached screenshot.

There is some miss configuration or Module conflict for sure.

Specify the list of modules + theme

---
Tags: 7, routes, users, navigation
---


# Question
Title: how to add taxonomy vocabulary and terms through code
I have added some taxanomy vocabulary with terms in my local development server which I need in some modules. I want to get these vocabularies with terms auto inserted when ever I install these modules where I have used them. Is there a way I write some code in drupal module which inserts the taxonomy vocabularies and terms when ever I install the module.

Thanks for your suggestions.

# Answer
Rather than writing code, I use the Taxonomy CSV module. It allows you to export and import taxonomy as CSV files. You can use the module's user interface or do it by command line with Drush to speed things up even more.

Initial configuration can be a little tricky, but it's able to preserve tree hierarchies and order, etc. so a bit of complexity is to be expected.
> 3 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I automatically generate meta tags on node creation using the Nodewords module?
I want to create meta tags automatically on node creation. I am using the Nodewords module.

# Answer
The documentation included with the module in the README.txt states:

> Configuration
>
> 1. On the access control administration page ("Administer \>\> User management \>\> Access control") you need to assign:
>
> * The "administer meta tags" permission to the roles that are allowed to administer the meta tags (such as setting the default values and/or enabling the possibility to edit them),
>     * The "edit XYZ tag" permission to the roles that are allowed to set and edit meta tags for the content (there is a permission for each of the meta tags currently defined).
>
> All users will be able to see the assigned meta tags.
> 2. On the settings page ("Administer \>\> Content management \>\> Meta tags") you can specify the default settings for the module. To access this page users need the "administer meta tags" permission.
> 3. You should enable meta tags for editing before they are available for use. The same operation should be done for meta tag output. Only allowed Meta tags are available for editing or exposed in the HTML of your site.
> 4. The front page is an important page for each website, therefore you can specifically set the meta tags to use on the front page meta tags settings page ("Administer \>\> Content management \>\> Meta tags \>\> Default and specific meta tags \>\> Front page"). Users need the "administer meta tags" permission to do this. When there are resources providing meta tags promoted in the front page, you may force the usage of "Front page" meta tags superseding all of them.
>
> Alternatively, you can opt not to set the meta tags for the front page on this page, but to use the meta tags of the node, term or other page the used to control the front page. To do this, uncheck the "Use front page meta tags" option on the main settings page.
>
> Note that, in contrast to previous versions of this module, the site mission and/or site slogan are no longer used as DESCRIPTION or ABSTRACT on the front page!
> 5. Each content type should be configured to control whether certain meta tags should be automatically generated, e.g. the "description" tag can be automatically taken from the node teaser.
> 2 votes

---
Tags: meta-tags
---


# Question
Title: How to make Toolbar unsticky at the top?
Drupal 7

The toolbar is sticky at the top even you scroll down the page.

How can I make it unsticky at the top?

Thanks.

# Answer
The fixed position is hard-coded into the toolbar.css file included with the core module.

To override it add the following to a CSS file that you're including with the admin theme:

```
#toolbar {
  position: static !important;
}

body.toolbar, body.toolbar-drawer {
  padding-top: 0 !important;
}

```

The `!important` declarations may or not be necessary depending on the order of inclusion...try without it first, and if it doesn't work, try adding it.
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: How can we find the js file is included before or not in drupal
I have some functions in template.php file that inside some of them, some js files must be included to the template.

Now, I want to check at first whether a specific js file \[for example jquery.min.js\] is included before or not. (in order to avoid) duplication.

Is there any way to check this issue in drupal 6??

# Answer
A. You should **not** be including jQuery manually in Drupal. Also, jQuery is always loaded on every page. If you need to include a different version of jQuery than the version that is included in Drupal core, you should utilize the jQuery Update module.

B. Secondly, you should be adding your javascript files using the drupal\_add\_js() function. Utilizing this function will take care of a lot of potential issues involved in managing many javascript files across many pages on your site.

C. drupal\_add\_js() returns an array of all javascript files. You could load a javascript file conditionally based on the presence of another javascript file, like this:

```
  $scripts = drupal_add_js();

  if(!isset($scripts['path/to/script.js'])) {
    drupal_add_js('path/to/script.js');
  }

```

D. Be sure to thoroughly read the Drupal.org documentation about using javascript in Drupal. This will answer many of your questions and solve many of your issues regarding javascript in Drupal.
> 6 votes

# Answer
You could use `drupal_get_js()` to get all the JS files thats included through Drupal. You will get an array of all the files which should make the checking pretty easy, you probably still will need to do some reg ex to figure out if the specific file is there or not.
> 0 votes

---
Tags: 6, javascript
---


# Question
Title: Assign a class to an element dependent on multisite domain?
I need to have a special class for example for body element which will be showing me on which site from multisite installation I am in. Here is a solution loading different css files but is there a way to have a simple class?

# Answer
> 1 votes
Well i decided to use different .css files with this code:

```
// Allow a site-specific user defined CSS file (useful for multisite installations):
// If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"),
// it will be loaded after "local.css". SITE is the site's host name, without leading "www".
// For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css"
global $base_url;
$site = preg_replace("/^[^\/]+[\/]+/", '', $base_url);
$site = preg_replace("/[\/].+/", '', $site);
$site = preg_replace("/^www[^.]*[.]/", '', $site);
drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all');

```

# Answer
> 0 votes
I would recommend you to create a custom module where you can store individual settings for each domain. Create for example a simple textfield where you can enter the class you would like to have in your body tag from this site. Use these settings then in your template preprocessor to add for example a class to the body.

---
Tags: 7, theming, multi-sites
---


title: I cannot delete a view

text:
# Question
Title: I cannot delete a view
I installed the module "himuesgallery" in a Drupal 7 site, and created two image galleries. To display them on one page, I created a view. When I try to remove the view, the system is showing me the message: "The view has been deleted." It seems to be ok, but it isn't. The view is still there and can't be deleted.

I also flushed the cache, but nothing changed. DO you have any idea?

# Answer
It happened to me also.

After hours of trying, I removed the records in the database:

1. VIEWS\_VIEW \> remove the view (remember the 'vid' value of the view)
2. VIEWS\_DISPLAY \> remove all the displays with that vid
> 3 votes

---
Tags: views
---


title: How to update jQuery to version 1.4?

text:
# Question
Title: How to update jQuery to version 1.4?
I installed the jQuery Update module, version 6.x-2.0-alpha1, which supports jQuery 1.3.2. I need to update it to jQuery 1.4 or higher, for a jQuery plugin.

I tried replacing the existing `jquery.js` and `jquery-min.js` files in the jquery\_update/replace directory with the latest jQuery files, and made some changes to jquery\_update.module as suggested in Using Newer Versions of jQuery. After doing so, jQuery started loading from misc/jquery.js, which was an older version.

Is there any simple way to update jQuery? I cannot implement the *noConflict* solution since I will be using third-party jQuery plugins.

# Answer
> 3 votes
The dev version of jQuery Update for Drupal 6 will get you up to jQuery version 1.7 (but it does break some of the admin UI).

There are a few patches available, (see Fix jQuery 1.7 for Drupal 6 and the Issue Queue in general), with varying reported levels of success.

If you choose to go down the 'manual' route then you'll have a lot of core/contrib javascript to fix. I think your best bet would be to base whatever solution you come up with on the current dev release of jQuery Update.

If you specifically only need version 1.4.2, then there's some instructions on how to do it here.

---
Tags: 6, javascript, updating
---


# Question
Title: Drupal 7 Views Question - How to pass 2 arguments
Using Drupal 7, Views 3.

I am attempting to pass a node reference "department" as first argument via contextual filter. The department has a number of employees, where I would then want a Views glossary to view by employee name by clicking on a letter. That is:

Department is Finance, the Views glossary will allow them to choose all employees with last name start with 'A'. the url will be:

organization/Finance/department/A/staff-listing or in views path, would be organization/%/department/%/staff-listing

---

I have cloned the glossary view and am able to get the department with employee listing. However when I click on the glossary letter, the url is changed to organization/A/department/%/staff-listing INSTEAD OF organization/Finance/department/A/staff-listing

When I manually enter the URL ../Finance/department/A/staff-listing , I am getting the right results. However, when I click on the letter from the glossary, it goes to the first argument.

I appreciate any advice or thoughts on this.

# Answer
> 4 votes
I think I know the answer.

I suppose the path to your view without any arguments is "organization".

So first you need to add the contextual filter "department" to the "attachment"-display too. This filter needs to be in first position.

Then:

When filter value is not available \> check "Provide default value" \> type= Raw value from url\> Path component= "2" \> save this filter.

Next:

Still inside "attachment"-display open up contextual filter "Content: Title" and change Display a summary \> Base path to "organization/%/department/%/staff-listing".

Hope this helps

---
Tags: 7, views
---


# Question
Title: Table names without using curly brackets
I'm working in a project in Drupal6 and we are removing all the curly brackets from the table names in the queries because we don't need table prefixes and supposedly this will improve performance.

Is this reasoning correct or curly brackets should be used even if we don't need table prefixing?

# Answer
> 2 votes
You should always keep the curly brackets in there, if only for maintainability and portability of your system. What if the next release of Drupal requires those curly brackets? I'm not saying it will, but if a framework gives you guidelines it does so for a reason; you should probably follow them.

As for the performance benefit, I think you'll find it's negligible at best. `db_query()` runs this statement regardless of whether your string contains curly brackets or not in the first instance:

```
$query = db_prefix_tables($query);

```

So `db_prefix_tables()` will get run on the string regardless of whether or not your table names actually need prefixing or not.

I'd advise stepping through `db_prefix_tables()` and using that to decide whether or not you should remove the brackets for performance reasons; you'll probably be making your decision based on the performance of the lower-level `strtr()` function, which does all the string replacement work.

There's a condition in that function that depends on a global variable not being empty to continue...if you want to 'turn off' the database table prefixing (and limit any inherent performance losses), ensuring that the global variable (`$db_prefix`) is empty *when you run your query* would probably do the trick (though that might make your data susceptible to race conditions; it depends on your setup).

Make sure you don't turn `$db_prefix` off for the entire site permanently though, or you'll have to go through all core and contributed modules and remove the curly brackets from their queries too!

---
Tags: 6, performance, database, theming
---


# Question
Title: How do I transfer anonymous data the user when he registers?
I have a system for storing data (e.g. accessibility settings like colour contrast) for anonymous and authenticated users. Authenticated users have the data in a dedicated table.

For anonymous users I'm using CTools object cache so if the person keeps the session he won't lose his accessibility settings. (I might use this for storing searches as well.)

I could use Session API but there is a potential issue with European cookie law - yes, this is about site usability which theoretically trumps that law but it's a very public site so the client doesn't want any trouble, valid or not.

Okay, so here's the point: If a person registers I need to go from CTools to my custom storage. The actual process of doing that is simple enough but when a person registers, their session ID changes, so once they are logged in (e.g. when hook\_user\_register() gets called) the old session ID is dead and gone.

Any ideas how I can keep the old session ID, or transfer the data from not-logged-in to logged-in? (Putting the data in form\_state in the user\_register\_form goes some of the distance, but not all of it.)

# Answer
> 2 votes
In fact it turned out to be simple (after spending a long time trying to be clever).

In `hook_form_user_register_form_alter()` add a value field to the form...

```
$form['mydata'] = array(
  '#type' => 'value',
  '#value' => $mydata,
  // in any form you like
);

```

Then in `hook_user_insert()` that data is in the `$edit` array, and already added to the `$account` object. Make sure you unset it from the `$edit` array otherwise it'll get put into the 'data' field. Anyway by this point the `$account` has a uid so it's possible to save the data.

---
Tags: 7, users, sessions
---


# Question
Title: Vote up/down module undefined constant errors
I recently have been trying to create a site for people to submit encryption algorithms to be tested. I wanted to make a voting process similar to Stackoverflow.

The best looking module I found was called the vote up/down module.

I installed it on a fresh install of Drupal 7, along with the answers module and answers userpoints, however when I enable it on a question, I get the following error:

```
Notice: Use of undefined constant NODE_BUILD_PREVIEW - assumed 'NODE_BUILD_PREVIEW' in vud_node_node_view() (line 147 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Use of undefined constant NODE_BUILD_SEARCH_INDEX - assumed 'NODE_BUILD_SEARCH_INDEX' in vud_node_node_view() (line 148 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Use of undefined constant NODE_BUILD_SEARCH_RESULT - assumed 'NODE_BUILD_SEARCH_RESULT' in vud_node_node_view() (line 149 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Use of undefined constant NODE_BUILD_RSS - assumed 'NODE_BUILD_RSS' in vud_node_node_view() (line 150 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Undefined property: stdClass::$build_mode in vud_node_node_view() (line 152 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).
Notice: Undefined variable: a3 in vud_node_node_view() (line 161 of /var/www/crackmycode2/htdocs/sites/all/modules/vote_up_down/vud_node/vud_node.module).

```

and, when I go into the `voting details` tab, I get a WSOD.

Here is a screenshot of the actual error:

Is this just because I set something up wrong? Is there a library that is missing? Is there a patch that is required to be installed?

# Answer
The module page for Vote Up/Down says (emphasis mine):

> 7.x (**unstable, on development, do not use this version for production**)

`NODE_BUILD_PREVIEW` was a constant in Drupal 6. I imagine that the maintainers of Vote Up/Down have branched off of the old D6 version to create the D7 version...and haven't completed the changes yet.

There's not even a dev/unstable release available for download on the module page so you definitely shouldn't be using this module for the time being.
> 3 votes

---
Tags: 7, rating
---


title: Use or Extend module functionallity

text:
# Question
Title: Use or Extend module functionallity
Recently we started a proyect where we need to implement a webpage that should be able to manage google maps markers and locations, with aditional info on them. However the requirement was to do it as a Drupal module in order for the client to embed it on his existing web page powered by Drupal.

I have a strong background developing web pages using java technologies like JSF, and I have had some previous experience using PHP MVC frameworks like cake php, but that's the reason why I think I'm so confused with the module development process used in Drupal (hook methods and conventions...).

First of all I have been looking at the Drupal 7 module development book by Packt, and I just finished the chapter 4 where you're supposed to implement and theme a single blog module. However by using the techniques showed until that point... I find it extremely difficult to implement a google maps powered (Block???) by just theming it as lists or using the render API.

What I found really interesting was the possibility to use theme templates and create the block content based on them; by just passing variables and priting php statemnets..., but it's not explained very well on the book either. So that's why I wanted to ask you where I could find more resources about theme templates, so that I could just put my html markup and js functions on that template, and pass to it the processed variables.

Anyway I think my best bet would be to extend existing module funcionality. In example for the maps I would use the OpenLayers Drupal module that's already done and tested. However, I need to execute my own code logic when a marker is selected, so that's another question..., how Could I insert a callback or intercept the OpenLayers module's functions so that I can extend them and save the data on my own tables or any operation I needed.

Should I rewrite the module files to add more functionality?? or could I implement my own modules and just intercept method calls?.

I'm just starting Drupal, and I think is really simple... but just for showing content, on the other hand interacting with the user, retrieving data from clients, seems to be really really difficult, because I have no idea how to show custom html markup, or add js functions, and then executing php ajax function callbacks on the server. For all these reasons I'm felling a little bit overwhelmed, and I really really need some guidance, tutorials, resources to focus on..

The other question I had is..., what are the topics that I should focus most in order to start my module fast, what I basically need is the ability to put markers on a map (Using the Javascript V3 API I guess...), and then sending AJAX callbacks to the server in order to update the selected marker info and adding it to my Session?? variables.. (This is really easy using JSF, and a framework like Primefaces.. however in the php world I'm lost) I think I should look at Drupal Entities and Fields next... but also Widgets?? Right???

Thanks a lot.

# Answer
I'm not sure that you need to dive into any theming. The Google js API uses an empty div and javascript to fill it. Your could create a custom module with a block hook to create your block. It would also load the necessary js to engage the Google API. This assumes that you are going to access the geographic information for the map independently - i.e. via accessing the database or whatever on your own. I think it makes most sense to use something like Openlayers if the data is stored in nodes and you want to use a View to access it.

If you need to theme the block outside of the map, you could use a straightforward theming function, also in your custom module. Creating or using a template makes most sense if somebody else who is more of a html/css person with less php/js experience is going to be doing the theming. If the theming is simple, you could just create the needed id and class tags in your module and then theme it via a css file.
> 1 votes

---
Tags: 7, ajax, entities
---


# Question
Title: Load domain-specific CSS file on a multisite
I have a Multisite Drupal 7 install.

I use one theme for all sites, and it lives at sites/all/themes.

Each domain has its own settings for the theme where you specify classes so you can target each in the css. This allows me to not have to copy over the theme to each sites/site1/themes, and to not have to create sub themes for each one. Less overhead.

So I have 1 giant css file, that contains all the css tweaks for each sites look.

But I would like to separate each sites css into its own file.

So I can have site1.css, site2.css, site3.css, and so on. They would all need to be located in the theme at sites/all/themes.

How would I tell Drupal to load site1.css when on site2.com...and so on?

# Answer
> 1 votes
It's kinda messy, but you might be able to do something like the following in a custom module:

```
function mymodule_preprocess_html() {
  $site = $_SERVER['HTTP_HOST'];

  switch ($site) {
    case 'siteurl1':
      //Add your CSS for site 1 here with drupal_add_css
      break;
    case 'siteurl2':
      //Add your CSS for site 2 here with drupal_add_css
      break;
    case 'siteurl3':
      //Add your CSS for site 3 here with drupal_add_css
      break;

  }
}

```

Or if you specifically want it in your theme files you could do the same in `template.php`

```
function mytheme_preprocess_html(&$variables) {
  $site = $_SERVER['HTTP_HOST'];

  switch ($site) {
    case 'siteurl1':
      //Add your CSS for site 1 here with drupal_add_css
      break;
    case 'siteurl2':
      //Add your CSS for site 2 here with drupal_add_css
      break;
    case 'siteurl3':
      //Add your CSS for site 3 here with drupal_add_css
      break;

  }
}

```

To be honest I think you could use hook\_preprocess\_page in the module as well.

Many ways to skin a cat and all that jazz.

# Answer
> 0 votes
I have had somewhat needs with dynamically loaded files. Instead of using a `switch`, I do something like this in an appropriate hook.

Essentially, you name your file based on the criteria you are testing against. In your hook, check to see if that file exists, and if so load it. If not, do nothing or load a default.

Something like this would be a starting point:

```
function mytheme_preprocess_html (&$variables)
{
  $host = $_SERVER["HTTP_HOST"];
  $filename = "something-{$host}.css";
  $default = "something.css";
  $path = drupal_get_path("theme", "mytheme");

  $options = array();

  if (file_exists($_SERVER["DOCUMENT_ROOT"] . "/{$path}/css/{$filename}")) {
    drupal_add_css("{$path}/css/{$filename}", $options);
  } else {
    drupal_add_css("{$path}/css/{$default}", $options);
  }
}

```

In your case, I would likely try to be a little smarter about the `file_exists` thing, and do something to try to save it out as a theme variable.

# Answer
> 0 votes
Another solution :)

```
// Allow a site-specific user defined CSS file (useful for multisite installations):
// If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"),
// it will be loaded after "local.css". SITE is the site's host name, without leading "www".
// For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css"
global $base_url;
$site = preg_replace("/^[^\/]+[\/]+/", '', $base_url);
$site = preg_replace("/[\/].+/", '', $site);
$site = preg_replace("/^www[^.]*[.]/", '', $site);
drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all');

```

# Answer
> 0 votes
Have you tried context + context add assets?

It makes it substantially easier. No hard coding needed either. I haven't tried it with multi-sites though.

*From Project Page:*

> This module will add a reaction within context to add theme, module, or custom folder files to your page(s).
>
> Ever wanted to quickly add a css file to a theme? Include a js file on only one page (or section?)
>
> Make using multiple CSS files a breeze with this module and harness the power of Context in your theme!

---
Tags: 7, theming, multi-sites
---


# Question
Title: Calling a view from code gives no results
I have a view that I use to grab a related node field given a user ID. I only call this view from code. The problem is, I just can't get it to work for a certain case.

To start with, here's the code that I use to call the view. The view accepts one argument (the user ID) and displays one field (the related node field). (I use multiple displays in this view for different code functions, thus why I build 'block\_3'. Also, I'm calling this code from within a "User has logged in" Rule, which is why I use $account instead of global $user.)

```
$view = views_get_view('my_view_name');
$view->set_arguments( $account->uid );
$view->build('block_3');
$view->execute();

```

For the user ID "5", this works perfectly. But for the user ID "14", it returns no results. The frustrating part is that in the View settings, I can enter "14" for the preview argument and it ALSO works perfectly!

I'm at my wit's end. Why would the view work perfectly fine in the preview and for one user ID, but not for another?

### Some notes

I've confirmed with `dpm()` that $account-\>uid is being set properly. I've also changed User ID 14's roles to match User ID 5's, and even swapped the related nodes for the two accounts, but User ID 14 always fails to work while User ID 5 has no issues.
If I pass `$view->result` to `dpm()`, I get empty text; `dpm($view)` returns the `$view` object, where I can see that `$view->result` is an empty text.

# Answer
> 2 votes
The View `set_arguments()` method takes an array as it's first parameter; currently you're passing a string/int.

This code will work.

```
$view->set_arguments(array($account->uid));

```

I think you're right about the C-style access to a string-as-an-array-of-chars in PHP. The following code prints the letter *e*, which would certainly support that theory.

```
$x = 'test';
print $x[1];

```

I must say I'm surprised that Views doesn't check the validity of the parameter passed to it, but hey ho!

# Answer
> 0 votes
Don't you need to print the output, or return it in an output variable?

I've used something to this before.

```
print views_embed_view($name, $display_id);

```

Use `print` in a template file; use `$output =` in a module.

View arguments can follow the display ID.

---
Tags: views, 6, rules
---