# Question
Title: Drush not being found although installed [ubuntu 11.04]
Utilising an Ubuntu (currently 11.04) box for WebDev in my SoHo, it's primarily for Drupal V7 projects using pure Linux LAMP and not any xamp, wamp models. I have a number of Drupal installs for dev and self-learning etc and hence Drupal version installs and modules change. I installed Drush 4.4 via the Ubuntu Synapatic manager and it installed seemingly ok, but when I try to run Drush from the Dash Home (HUD), nothing appears to load or run.

I'm the only user on the computer so I have all priviledges etc and all my Drupal projects are in var/www/ in order to emulate any future live web models. In order to be more efficient in updating Drupal and modules, I'd rather use Drush for Drupal updates as updating 6-8 projects is too labourious. Can anyone shed some light on why Drush is/or not running and what I need to do to simplify it's loading (a simple desktop link creation would be great). My current Linux experience is some 24 months having crossed over 100% from MS Windows O/S, but my DOS CLI experience was also then poor, so my knowledge was limited (but growing). Thank you.

# Answer
> 4 votes
Your problem is probably that Drush is not in your $PATH. I did not try to install Drush-4.4 from Synaptic to test whether or not this is the case; instead, I would recommend that you install Drush via PEAR following the instructions on the Drush project page. If you do this, your $PATH will be set, Drush will be found, and better yet, you'll be able to use the much-improved Drush-5.1 instead of the out-of-date Drush-4.4.

Edit: By "Dash Home", do you mean that you are trying to type "drush" into the Unity Heads-Up Display? If so, instead run "terminal" from HUD, and then type "drush status" from the terminal prompt. Then you should be good to go. I'd still recommend installing 5.1 via PEAR.

---
Tags: drush
---


# Question
Title: How to make my mobile app to work more faster when web services made from drupal7 REST services
We did an app based on drupal web services(REST server). The thing is the app is very slow on the device. The reason for this may be, the app requires 3 webservices to load initially. lile

```
http://myapps/api/node?parameters[type]=Company

```

From the above web service i will get all node under CCk company. then to get the details of the node i need to pass another url as `http://myapps/api/node/5` and then to get the taxonomy term to which ths company belongs to i need to pass another url. there by it is taking much time to load. Is there any solution to make my app faster?

# Answer
> 2 votes
I'm used to create my own resources / module then i can send all the information i need with custom query / joins, following the next tutorial:

http://drupal.org/node/1246470

Also on my module i could enable cache etag and then programming on mobile device the http client with etag support.

---
Tags: 7, services
---


title: CRUD operations with custom fields

text:
# Question
Title: CRUD operations with custom fields
I am using Services 3.x with Drupal 7 and trying to expose a custom field added to the User object through the services. What is the easiest way to implement it for all operations (create, retrieve, update, delete)?

# Answer
After the field has been created you will see the field on retrieve user resource (not index), and you will be able to send data on crud operations.
> 1 votes

---
Tags: users, entities, services
---


# Question
Title: Are HTML strings translatable through admin/config/regional/translate?
I'm on Drupal 7 and to easily add an image to a string, I did this:

```
<img src="/icons/icon_32.png" height="32" width="32" /> My text here

```

I used this technique in several places: field labels, views titles, field values, etc.

Now I'm translating the site.

As it turns out, using the standard translation interface and the i18n modules (views, fields, etc.), field labels containing these img tags can be translated, but field values cannot. I'm also noticing other inconsistencies. Should strings containing HTML not be used with t() or am I doing something else wrong?

# Answer
After looking into this for a bit, here's what I've found so far. t() runs everything through format\_string(), which sanitizes/wipes out HTML such as the IMG tag. Hopefully someone who understands this better is able to provide greater insight into how it all works.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Taxonomy terms won't arrange themselves by ID but will work alphabetically instead
I added a large number of taxonomy terms in the order I want. Their term IDs reflect they are added in the correct order. However, everywhere they are displayed alphabetically. Particularly, inside a hierarchical select widget they are displayed alphabetically - when I see their IDs (856, 847, 843 - not a correct numeric order but correct alphabetic A, B, C) they check out fine so they were added properly. How can I control this?

# Answer
The order in which you enter the taxonomy terms is not important to how they are displayed. Drupal defaults to alphabetic ordering, but you can adjust this order manually.

Go to Content management \> Taxonomy \> Your vocabulary: List terms (via `admin/content/taxonomy/list`) and reorder the terms by dragging the handle on the left. This is also the order Hierarchical Select uses.

You can also try out Taxonomy Manager to see if this provides you with a better interface for reordering large numbers of terms.
> 1 votes

# Answer
What version of Drupal? There's a module for D6 called TagOrder that'll probably do what you want. If you're in D7 you may need to see if there's a port of it or an equivalent: http://drupal.org/project/tagorder
> 1 votes

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


title: Insert Javascript in a node

text:
# Question
Title: Insert Javascript in a node
I can't figure out how to insert a javascript function inside a node.

It's a countdown script that uses an external js file and i need the function to be called from within a node. (each node will have a different countdown target date)

I set the input filter to php but it didn't work. All it does is printing the js file content as node content

I put the js file in a folder inside sites/all/scripts and here's how i use :

```
<?php include('sites/all/scripts/countdown.js'); ?>

<script type="text/javascript">
y: 2012; m: 5; d: 25; h: 10; m: 0; s: 0;
</script>

<div id="countdown"></div>

```

Any ideas ?

thanks a lot

# Answer
> 2 votes
Javascript happens on the client-side so there's no need to use PHP at all here. Using the PHP filter is in fact strongly discouraged as it introduces potential security risks.

To include javascript in an HTML page you use the `<script>` tag like so:

```
<script type="text/javascript" src="/sites/all/scripts/countdown.js"></script>

```

---
Tags: hooks, javascript
---


# Question
Title: How to add a image style to an image in a template file?
I need to change these lines (belong to a tpl.php file) to include a image style called "adaptative\_image\_style" to the generated image.

```
<?php print l(theme('image', $image_attributes), $ad['url'], $link_attributes); ?>

```

I think I should use the function to theme\_image\_style($variables) instead but not sure how to implement it.

Based in Clive's answer I get it working with this code:

```
  <?php
  $image_attributes['style_name'] = 'adaptative_image_style';
  print l(theme('image', $image_attributes), $ad['url'], $link_attributes); ?>

```

# Answer
The docs page has it pretty much covered but here's an example if you're struggling:

```
$style_vars = array(
  'style_name' => $style_name,
  'path' => $image_path,
  'alt' => $alt_text
);

$image = theme('image_style', $style_vars);

$link = l($image, $url, array('html' => TRUE));

```
> 3 votes

---
Tags: theming
---


# Question
Title: Add CSS just to the main content and not to include comments
I'm theming using the Omega HTML5 starterkit theme on Drupal 7, and I want to add CSS just to the main content region in nodes but not to the comments.

How do I do that? What is the class (or ID) for that?

# Answer
> 1 votes
In my own Omega subtheme, which is quite standard, page content with comments has this structure (closing tags omitted for brevity):

```
<article ... class="... node ...">
  <div class="content clearfix">
    <div class="field field-name-body ...">   (node body)
    <div class="field field-name-... ...">    (another node field I'm displaying)
  <div class="clearfix">
    <nav class="links node-links clearfix">
    <div id="comments" class="comment-wrapper">

```

So a CSS selector of:

```
node > content

```

would get you all the fields in the content, but not the comments. Or if you just want to style the body, you could choose it specifically.

Note that the `content` class is used a number of different places in a page. Alternatively you might want to set up some default CSS for most of the node and style the `#comments` or `.comment-wrapper` separately.

This is not profound: I just poked around with Firebug to figure it out.

---
Tags: 7, theming
---


# Question
Title: in drupal 7 's view, how to comment without redirecting to content type page?
I make a view for a specific content type, the path of content type and the path of the view are different. Now I put a form into the view, in order to comment on that content type. However whenever I comment on the view page, the view page will redirect to the path of content type, so the question is how can I comment without redirecting to the content page but staying on the view's page, perhaps working with ajax?

# Answer
> 2 votes
There is an Ajax comments module you can use to post comments without refresh and this post shows how to combine it with views.

---
Tags: views, comments, redirection
---


# Question
Title: In Views, how can I use the rewrite text to include an image in HTML with some text and then translate the text?
I've installed Views along with the Internationalization views module. I have a view of users. The users have some single-value boolean fields in their profiles. I would like to rewrite the results of these fields so that if they are true an image and some text is shown.

Example: If "likes\_soccer field is true, then show an image of a soccer ball with the words "Loves soccer"

This is quite simple to do in Views.

However, I also need to translate the text, and this is where I'm running into problems. Internationalization Views allows the text to be translated, but because it is HTML it ends up being sanitized so that the IMG tag is displayed as code rather than interpreted as HTML (as this answer explains). I can simply ignore the IMG tag in my translation, which will allow me to translate the text, but then I will lose the image in the translation.

Is there an alternative way to do this?

# Answer
> 0 votes
I hit upon a very straightforward solution for doing this-- simply add each field that needs to be rewritten twice. Place the IMG tag in one field and the string to translate in the other. This way, no custom code need be written and everything can stay in Views.

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


# Question
Title: How to allow a client to do specialized styling for a single node?
I'm working on converting an existing website to Drupal, and I'm looking for best practices for creating specialized styling on specific nodes. I have a page that looks like this (baconized for your viewing pleasure):

Can someone advise me as to the best way to accomplish styling a node this way - specifically in a way where the content can be managed by the client?

I've had a few different ideas as to how to accomplish it, but I'm not sure which is best.

**Write raw HTML as the content and add CSS in the template?** \- The downside with this is that I'd prefer my client not have to mess with raw HTML when managing the content, if at all possible.

**Create a custom content type that has fields for each snippet which I can style within the theme?** \- This seems like a reasonable course of action, except that I'll be creating a one-off content type for a single node, and that seems less than optimal.

**Do something with Views?** \- Views is always an option, but I don't know if it's the right one here. Would I create a separate node for the intro snippet, the 3 blockquotes, and the rest of the page, or something else? I'm not sure.

**Do something with Panels?** \- I'm still figuring out how to use Panels, and it seems like a possibility here, but an overly complicated one. Additionally, how will the client manage it?

Any insight or advice here would be immensely helpful. Thank you!

# Answer
> 1 votes
If it is a page with unique structure and no other pages will have same structure, I usually do this by creating an empty page (not a node, just a page - an item in drupal menu system).

You can create a page in your module like so:

```
function YOUR_MODULE_menu() {
    $items = array();
    $items['your-page-url'] = array(
        'type' => MENU_NORMAL_ITEM,
        'title' => t('Page title'),
        'page callback' => 'your_callback_function_name',
        'access callback' => TRUE
    );
    return $items;
}

function your_callback_function_name() {
    return '';
}

```

the code above will provide an empty page. If you need custom page structure for this page you can always declare a template specifically for this page just put:

```
page--your-page-url.tpl.php

```

to your theme template folder.

Then you can create blocks for each piece of content and assign them to proper regions. Your users will be able to edit content through blocks edit while all styling and layout tags will be built into template file.

# Answer
> 0 votes
In most simple case you can use CKEditor module and some css in your theme for blockquote tag inside node content. Also you can define your custom element style for CKEditor that will wrap disred text into tag with class or inline style. This way allow you to avoid metting your user with raw HTML. Panels and Views or blocks is good approach for small amounts of pages with complicated structure(for example), but not always it is appropriate way.

# Answer
> 0 votes
You might consider whether Skinr meets your needs. The idea is that you can apply extra CSS selectively, and your client can, too.

# Answer
> 0 votes
I like using views to output content, but this could be done in lots of ways. One way could be to create your columns as taxonomies and then in a newly created content type, create an existing term reference to the taxonomy. Then create the other content from fields and then once all your content is in the node, style it accordingly with CSS. A second way could be to use a combo of blocks and views. In this solution your could create a view of taxonomy terms that displays them as list items in a block, so you could specify what URL's to route your block to. After you have the columns as views you could create the bottom content as a block and the top content as view with a field for the body and a field for the image (from a referenced content type). You can always move your elements around on your page with a bit of CSS. Hope this helps.

---
Tags: nodes, theming
---


# Question
Title: Is it possible to show 403/404 messages on the front page?
Is it possible to have - instead of a dedicated 403/404 page - just a custom div inserted into the front page? 'Cause when I think of what I'd like to show up at 403404, I want everything that the front page has. So, whatever the front page looks like over time, I would just want it to adopt a 403/404 message div.

# Answer
In D6's Error Reporting, if you set your 404 page to 'node', eg the standard front page, you should be able to do something like this in your hook\_preprocess\_page():

```
function YOURTHEME_OR_MODULE_preprocess_page(&$vars) {

  // all your other stuff

  if ($_GET['q']=='node' && !$vars['is_front']) {
    $vars['YOURTHEME_OR_MODULE_404_on_front']='<DIV>404 ON FRONT</DIV>';
  }
}

```

and then just do a:

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

```

inside your page.tpl.php where you want the information telling your users about the 404.

The only reason I think the above silliness works is because drupal's 404 handler builds the 'node' page manually and displays it, but the theme layer sees what you really typed (eg, myhost.com/foo/bar/baz/bing) and doesn't think it's the front page and sets $is\_front accordingly.

I'd assume all of the above would work for a 403 as well, but I haven't figured out a way to pass in which error actually happened, so, you'd have to have this "block" information pretty generic, eg "Oops. You are in a maze of twisty little passages, all alike..." :)
> 1 votes

# Answer
You can make this with the following configuration and using Rules module. 1. create a page with a custom path ex, "404" and set this page as 404 on configuration -\> site information 2. create a rule, if the request page its "404" then 2.1 system page redirect 2.2 system show a message
> 1 votes

---
Tags: theming
---


# Question
Title: How to have parent taxonomy terms include their children terms' nodes?
I have a hierarchical taxonomy, and I'm currently using the Taxonomy Menu module to display navigation links. E.g.

```
+ Dairy
  * Milk
  * Cream
+ Fruit n Veges
  + Citrus
    * Lemon
    * Lime
  * Pumpkin
  * Tomato

```

Each of the links refers to a taxonomy page, which is nice, but the page for "Dairy" only includes nodes that have the term "Dairy". It doesn't include "Milk" and "Cream" nodes, for example, which is what I want.

What's the best way to implement this? And "what's the point" of sub-terms, if they don't seem to have any semantic meaning?

# Answer
Install the module http://drupal.org/project/hierarchical\_select and check its configuration and you will find an option to "Save term lineage" select it and all the level of terms will be saved with the node.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How to set/display select options in selectbox using form-api
I have created a form to allow users to enter some details but I also need to display some mysql data into that form. The contents and fields of the form are displayed in a tabular format. I just want to know the right way to display mysql data in one of the table columns along with the form fields. How can i display select options in selectbox using form-api ?

# Answer
You can make use of `theme_table` to make a table view. You can use `form-api` inside the table as you wish.

Sample code for creating table.

```
$header = array();
$rows = array();
$rows[] = array(
    array('data' => 'Head1', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head2', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head3', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head4', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head5', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head6', 'colspan'=> 6, 'header' => 1),
);
$rows[] = array(
    array('data' => 'SubHead6-1', 'header' => 1),
    array('data' => 'SubHead6-2', 'header' => 1),
    array('data' => 'SubHead6-3', 'header' => 1),
    array('data' => 'SubHead6-4', 'header' => 1),
    array('data' => 'SubHead6-5', 'header' => 1),
    array('data' => 'SubHead6-6', 'header' => 1),
);

```

return `$output .= theme('table', $header, $rows);`

To make a select box with db values you can try this

```
$query = "SELECT * FROM {tablemanme}";
$query_result =  db_query($query);
while (($data = db_fetch_object($query_result )) !== FALSE) {
  $opt[$data->id] = $data->name;
}

$form['select'] = array(
    '#type' => 'select',
    '#options' => $opt,
);

```

Good luck.
> 2 votes

# Answer
You can check on this link
> -2 votes

---
Tags: 6, forms
---


title: How to add class to a language field?

text:
# Question
Title: How to add class to a language field?
In drupal 7 there is a field which displays the node\`s language.

I have a multi-site installation and plenty of content types on each of sites. I don\`t want to click for hours hiding this field. By default it is generated with "form-item form-type-item" classes.

How could i add a class to this field to be able to hide it in css?

Thanks

# Answer
> 1 votes
The easiest way to do that in my situation was just adding to node.tpl:

```
hide($content['language']);

```

---
Tags: 7, i18n-l10n
---


title: Send parameter to another page

text:
# Question
Title: Send parameter to another page
I want to build a page that will be my player.
That page.tpl.php will include code like the following one:

```
<object bla bla ... idmedia="**the parameter that i want to get**"></object>.

```

I want to call this page with various parameters that play other videos. I can I do it?

# Answer
you can your page with a GET variable appended in the url, something like

```
www.mysite.com/node/1?videoId=123

```

then inside your template you use a GET variable like this

```
$videoId = $_GET['VideoId'];

```

then you could do this

```
<object bla bla ... idmedia=" $videoId "></object>.

```
> 1 votes

# Answer
If you are looking to have a block that provides links to other related content you would do it like this:

1. Create a content type to contain your player and whatever other information you want.
2. Add fields to contain any sorting categories that you want to use to relate the content such as subject categories, media author etc. These fields can me created as Taxonomy fields which will provide the list of options you wish as input in the fields.
3. Create a View definition using the Views module to select the content type along with any other filtering or sorting criteria you want to apply to the main page for your media content.
4. Add a contextual filter to the view and apply it to a block so that the block will provide a list of the related content available for the contextual filter.

This sounds simple, but is not to someone new to Drupal. There are excellent videos and other information on using Views at Nodeone.se
> 0 votes

---
Tags: theming
---


title: Language dependant sidebars vice-versa

text:
# Question
Title: Language dependant sidebars vice-versa
Due to lack of php knowledge i cant find where i am mistaken and how it\`s better to do this. I have several languages one of them LTR and the other RTL and i need sidebars to be displayed vice-versa. It means that in LTR menu would be in the first and in the RTL it would be in the second sidebar. The code returns '1' somehow and breaks the markup. Please help me to modify this code:

```
global $language;
switch ($language->language) {
case "en":
if ($page["sidebar_first"]):
print "<aside id='sidebar-first' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_first'])."</aside>";
endif;
if ($page["sidebar_second"]):
print "<aside id='sidebar-second' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_second'])."</aside>";
endif;
break;
case "ar":
if ($page["sidebar_second"]):
print "<aside id='sidebar-first' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_second'])."</aside>";
endif;
if ($page["sidebar_first"]):
print "<aside id='sidebar-second' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_first'])."</aside>";
endif;
break;
}

```

# Answer
> 1 votes
You missed the position of the string operator `.` You can try the code mentioned below.

```
    global $language;
    switch ($language->language) {
    case "en":
    if ($page["sidebar_first"]):
    print "<aside id='sidebar-first' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_first'])."</aside>";
    endif;
    if ($page["sidebar_second"]):
    print "<aside id='sidebar-second' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_second'])."</aside>";
    endif;
    break;
    case "ar":
    if ($page["sidebar_second"]):
    print "<aside id='sidebar-first' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_second'])."</aside>";
    endif;
    if ($page["sidebar_first"]):
    print "<aside id='sidebar-second' role='complementary' class='sidebar clearfix'>".print render($page['sidebar_first'])."</aside>";
    endif;
    break;
    }

```

---
Tags: 7, i18n-l10n
---


# Question
Title: How can we render graphviz diagrams in drupal pages?
I'd like to be able to allow users to insert Graphviz images in Drupal comments and Wiki pages.

What's involved it doing this?

The benefit is that users could enter something like the following snippet to see a graph.

```
[code lang=graphviz]
  digraph G {
    a  [label="Hello", shape="square", URL="http://en.wikipedia.org/wiki/graphviz"]
    F1 -> a[label=".63"]
  }
[/code]

```

# Answer
> 3 votes
There's the Graphviz Filter module, which provides an input filter that will convert Graphviz DOT syntax to the required diagrams. You can find more information in the Drupal documentation on graphing modules.

---
Tags: 7
---


# Question
Title: drupal 7 wildcard and parameter replacement?
How can i use \_load() function in drupal 7 ? Please look at this one.

```
function sample_menu() {
  $items['node/%hotel_node/images'] = array(
    'title' => 'Images',
    'weight' => -10,
    'page callback' => 'show_tab_page',
    'page arguments' => array(1, 'images'),
    'access callback' => TRUE,
    'access arguments' => array(1),
  );
  return $items;
}

function hotel_node_load($nid)  {
  //$node = node_load($nid);
  $node = node_load(array('nid' => $nid));
  return $node;
}

function show_tab_page($s1='',$s2='') {
  return('s1 is @s1 with $s1 @s2 with $s2',array('@s1' => $s1,'@s2' => $s2));
}

```

while trying in the url : http://localhost/drupal/user/2337/images

**Am getting Page not found The requested page "/drupal/node/232/images" could not be found.**

Please help me out. thanks

# Answer
There seems to be some disparity in your naming conventions here. Your functions should be named with `MODULENAME_` as a prefix, including all hooks that you implement.

For example, if your module is called 'sample' then as well as the folder the module files are in being called 'sample', your files will need to be named similarly (sample.info, sample.module, etc.). If you don't follow this convention your hooks won't be called; and it's just good practice to prefix your module's functions with the module name.

The other thing here is that you don't actually *need* to use your own router load function...the node module has already done it for you (with the `node_load()` function). You can simply re-use that:

```
function sample_menu() {
  $items['node/%node/images'] = array(
    'title' => 'Images',
    'weight' => -10,
    'page callback' => 'sample_show_tab_page',
    'page arguments' => array(1, 'images'),
    'access callback' => TRUE
  );
  return $items;
}

```

You should be aware that `node_load()` returns a node object, so the first parameter to your page callback function will be that object. The second will be the string 'images', as per the arguments you've provided in `page arguments`.

Your page callback (which I've renamed :P) would then look more like this:

```
function sample_show_tab_page($node, $arg1) {
  // Use whatever you need from the node object
  $nid = $node->nid;
  $title = $node->title;
  // etc...
}

```

Finally, and perhaps most importantly to commit to memory, make sure you clear Drupal's caches once you've added/edited any hook. Such implementations are cached, and the system won't pick up these changes until you tell it to.
> 2 votes

# Answer
The code as it is written doesn't work because you are passing the wrong parameter to node\_load(): In Drupal 7, the function needs:

* the node ID
* (optionally) the revision ID
* (optionally) a flag to reset the cache used from the load function

Also the node ID is optional, but you generally call the function to get a node.

The parameters you are using are the ones required from Drupal 6, although it is possible to pass the node ID to the function, instead of an array, as the function executes the following code:

```
  $cachable = ($revision == NULL);
  $arguments = array();
  if (is_numeric($param)) {
    if ($cachable) {
      // Is the node statically cached?
      if (isset($nodes[$param])) {
        return is_object($nodes[$param]) ? drupal_clone($nodes[$param]) : $nodes[$param];
      }
    }
    $cond = 'n.nid = %d';
    $arguments[] = $param;
  }

```

If the first parameter is not an array, it is considered the node ID.

As already said from Clive, there is not need to use such a load function that just calls `node_load()`; you just need to use the appropriate wildcard argument, which (in this case) is "%node"; replace it to the menu path, and you get *node/%node/images*. Clearly, it makes sense to use a custom load function if, for example, you need to check the content type of the returned node; `node_load()` returns the node object for every object.

```
function sample_menu() {
  $items['node/%sample_hotel/images'] = array(
    'title' => 'Images',
    'weight' => -10,
    'page callback' => 'sample_images_page',
    'page arguments' => array(1, 'images'),
    'access arguments' => array('access content'),
  );

  return $items;
}

function sample_hotel_load($nid)  {
  $node = node_load($nid);

  if (!empty($node) && ($info = node_type_get_type($node)) && ($info->type == 'hotel')) {
    return $node;
  }

  return FALSE;
}

```

To what already said from Clive, I would add that the code of `show_tab_page()`, although I understand it's debugging code, it doesn't make sense. It is probable you are trying to call `t()`, and in that case your function should be the following one:

```
function show_tab_page($s1 = '', $s2 = '') {
  return t('s1 is @s1; s2 is @s2', array('@s1' => $s1,'@s2' => $s2));
}

```

The code you are wrote causes a parse error. The `return` statement is expecting a single value, which could be:

* the value returned from a function
* the value of a variable
* a string literal
* an array
* an integer
* a constant

In any cases, `return` is not expecting two values separated from a comma; that is the reason of the parse error.

If that is debugging code, there is no need to use `t()`, as debugging code doesn't need to be translated; if you just want to be able to replace parameters in a string as `t()` does, you should use code similar to the following one.

```
function show_tab_page($s1 = '', $s2 = '') {
  return format_string('s1 is @s1; s2 is @s2', array('@s1' => $s1,'@s2' => $s2));
}

```
> 1 votes

---
Tags: 7
---


# Question
Title: Drupal 6 custom theme development using Zen starter kit
I am trying to develop a custom drupal 6 theme with zen starter kit. I installed and configured Zen starter theme kit. My objective is to develop a liquid layout theme from this starter kit. Anybody please tell me how to give layout widths for particular elements and if you have any useful tutorials, please share it.

# Answer
> 1 votes
For setting up a Zen sub-theme check here. And there is a good podcast there ;-)

---
Tags: theming
---


title: Adding meta data to user

text:
# Question
Title: Adding meta data to user
I would like to store meta data about users.

At first this I tried by adding fields to the user, but this is not exactly what I want, because the user himself should not be able to manipulate or view the data.

The data I want to store is based on actions a users takes in the application. Its is similar to a status which I want to write and read programmatically. E.g. has the users phone number been validated by the system?

What is the best way to store such data?

# Answer
Fields are definitely the best method for storing this data.

You can combine fields with the Field Permissions module:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

With that module you'll be able to specify exactly which fields the user should be able to view/edit.
> 1 votes

---
Tags: 7, users
---


# Question
Title: What variable will let me access user profile info?
I'm using prepopulate to prepopulate a feild of a `node/add/content`. I'm trying to generate a URL using some PHP code that willl generate a URL like:

```
http://mysite.com/node/add/content_type?edit[title]={$some_var}

```

Each of my user profiles will have this link at the top of the page and I would like `$some_var` to hold the username of the user whos profile we are currently viewing. I was wonder how to populate `$some_var` with the username of the user profile being viewed.

Something like:

```
$some_var = $username;
print("<a href=\"http://mysite.com/node/add/content_type?edit[title]={$some_var}\">Content Type</a>");

```

# Answer
If this link is to be on the user profile page then you can grab the related user ID from the internal URL (using the `arg()` function), and then use `user_load()` to load a user object that contains the username:

```
// Get user ID from internal router path (this isn't necessarily the URL shown in the address bar, it's the internal path that Drupal is using to serve the page).
$uid = arg(1);

// Load the user account and extract the username
$account = user_load($uid);
$username = $account->name;

```
> 1 votes

---
Tags: 7, users
---


title: Drupal 6 with mongodb, any success?

text:
# Question
Title: Drupal 6 with mongodb, any success?
There is a mongodb module which is in develeopment stage. As usually find MySQL as my bottleneck, wondering whether anyone has actually implemented mongodb on D6 with success? And if so what are good resources on how to implement mongodb?

# Answer
> 1 votes
MongoDB is not a full replacement for MySQL, you still need it. You can only move certain pluggable systems to MongoDB, like sessions, watchdog and in Drupal 7 also the field storage.

---
Tags: performance, database
---


# Question
Title: Form is not calling custom submit function
From my understanding, and as I've seen it in other examples of code, all I need to do to call a custom submit function is include the `"#submit" => array("myModule_submit");`.

I use a drupal\_set\_message to post a message on the site so I can know if the myModule\_Submit is being called from the form submit button:

```
function myModule_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['name']);
}

```

When I click on the "Send" button nothing happens, and it seems the page just refreshes.

```
function myModule_form_builder($form, $form_state){
  $form['myModule_message'] = array(
    '#type' => 'textfield',
    '#title' => t("Outgoing Message"),
    '#size' => 150,
    '#maxlength' => 150,
    '#required' => TRUE,
    '#description' => t("Type your message"),
  );

  $form['buttons'] = array(
    '#type' => 'button',
    '#value' => t("Send"),
    '#submit' => array('myModule_submit'),
  );

  return $form;
}

function myModule_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['name']);
}

```

To my understanding `drupal_set_message()` will display a message to the user on the current page somewhere given the parameters. When I put information in the fields and press submit though there are no messages. I have seen other examples on the web that use this method and they say it works.

# Answer
> 4 votes
Try next:

```
function myModule_simple_form($form, &$form_state){
  $form['firstname'] = array(
    '#title' => t('First name'),
    '#type'  => 'textfield',
  );
  $form['lastname'] = array(
    '#title' => t('Last name'),
    '#type'  => 'textfield',
  );

  $form['submit'] = array(
    '#value' => t('Search'),
    '#type'  => 'submit',
  );
  return $form;
}
function myModule_simple_form_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['firstname']);
}

```

Any rendered drupal form already have a submit function. Also try: `drupal_set_message($form);` in your hook\_from\_alter when `$form_id = 'myModule_simple_form'` too see where is default submit function. You can also add a custom submit funtion in array but it is necesary only if you need more than 1 submit function for your form. In all othre cases use just form\_id\_submit.

# Answer
> 2 votes
The only problem in your code was using `'#type'=>'button'` instead of `'#type'=>'submit'`

---
Tags: forms
---


# Question
Title: Different node / entity templates based on display type
Is it possible to have different template files for different display modes of the same entity without using template\_preprocess\_page()? If not, how can I get all the available display modes for a certain entity type so I can create some sort of automatic template suggestion?

Eg: For a node I have by default the 'Full' and 'Teaser' display types. I can add more display types using Display suite module or by creating a custom module. I need to create multiple template files like `node--content-type--teaser.tpl.php` to keep everything clean and not use lots of IF statements.

Thanks :)

# Answer
I'll go with this solution after all:

```
function MYMODULE_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__' . $vars['view_mode'];
}

```
> 7 votes

---
Tags: 7, theming
---


title: Trying to access node content with PHP

text:
# Question
Title: Trying to access node content with PHP
I have the following code to load a different node into my homepage:

```
<?php $node = node_load(2); ?>
<div class="modal hide fade" id="security">
    <div class="modal-header">
      <button class="close" data-dismiss="modal">×</button>
      <h3><?php echo $node->title; ?></h3>
    </div>
    <div class="modal-body">
      <?php render( $node->content ); ?>
    </div>
    <div class="modal-footer">
      <a href="#" class="btn" data-dismiss="modal">Close</a>
    </div>
</div>

```

The title displays, but the content doesn't. I get the error `Notice: Undefined property: stdClass::$content in include()`

Based on what I read here I feel this should work. What do I need to do to make the node content display? (it's just a basic page w/ title and body)

# Answer
> 3 votes
The node's content isn't built when you load the node, you need to invoke it manually with `node_build_content()`:

```
$node = node_load(2);
node_build_content($node, $view_mode);

// You now have access to $node->content

```

---
Tags: 7, nodes
---


title: Url length, how short it?

text:
# Question
Title: Url length, how short it?
Our website have a large Url when paste as a link, now we want to short it.

for example

http://www.awene.com/article/له%E2%80%8C-ژێرناونیشانی-ئه%E2%80%8Cو-شته%E2%80%8C-چیه%E2%80%8C-كه%E2%80%8C-ره%E2%80%8Cوشته%E2%80%8C؟-كۆرێك-بۆ-ئازاد-حه%E2%80%8Cمه%E2%80%8C-ساز-ده%E2%80%8Cكرێتوك

# Answer
> 4 votes
It looks like you're using path auto to create these urls but the problem is that the transliterated version of your title in the url is too long. Couple easy answers are to either use the shorten module as jimajamma suggests (which is probably the best answer since it helps users with these long, complicated URLs) or you can update your automated alias settings to remove the title and use something else (ex. article/\[\[nid\]\]).

However, if you really want to keep the long title, you're going to need to truncate it when used by pathauto. I ran into a similar problem with custom breadcrumbs and long titles so I created a quick token hook to truncate the title. Here's how you could do that:

In your site module (if you don't have one you can create one and name it whatever you like), add the following (this code below was for 6.x) to register a new token to the token list:

```
function MYMODULE_token_list($type = 'all') {
  $tokens = array();

  if ($type == 'node' || $type == 'all') {
        $tokens['node']['MYMODULENAME-truncate-title'] = t("A truncated title token.");
  }

  return $tokens;
}

```

Next, add a processing function to tell token what to do with this new token value:

```
/**
 * Implementation of hook_token_values().
 */
function MYMODULE_token_values($type, $object = NULL, $options = array()) {
  $values = array();

  switch ($type) {
    case 'node':
      $values['MYMODULE-truncate-title']  = _MYMODULE_truncate_title($object->title);
  }
  return $values;
}

```

Finally, we can add a function to do the operation:

```
function _MYMODULE_truncate_title($title) {

   if (strlen($title) > 30) {
       $title = drupal_substr($title,0,30)."...";
   }

   return $title;
}

```

Now, in your automated alias settings you can use this new token instead of the default title token, ex:

```
article/[[MYMODULE-truncate-title]]

```

A little more involved than the other options (again, checkout shorten) but thought this code might be of use to others with similar issues.

---
Tags: uri
---


# Question
Title: Add link to view data if no matching record
I have a view that shows taxonomy terms with a relationship to show nodes that have a term reference to that term (relationship not required, aka LEFT JOIN).

For terms that don't have a matching node I would like to show an "add content" link.

The usual "no results" behavior doesn't seem work in this situation. What's the trick?

# Answer
Views PHP to the rescue:

```
<?php
if (is_null($row->nid)){
    print '<a href=node/add/mytype?edit[field_mytype][und]='.$row->tid.'>add node for this term</a>';
}
?>

```

I can even pass the tid through the URL and have it prepopulated on the form (using prepopulate).
> 0 votes

---
Tags: 7, views
---


# Question
Title: Linking in views with multiple fields displayed
I am making a view in Drupal 7 to display grants: the name, the description, the amount of the grant, and the due date for submission.

It's easy to make a view that displays the name, the amount and the date in each row of a table, with the name linking to the full node display.

I've also learned how to display the description below the title, using the rewrite rules for the title, like:

```
[title]

[body]

```

What I want is having only the title as link to the full node, not all the text. Can I do this?

# Answer
Try this:

---

# Format

* Format: table
* Show: fields

# Fields

* Content: Title
    + under "settings" check "exclude from display"
* Content: Path
    + under "settings" check "exclude from display"
* Content: Grant Amt
* Content: Due date
* Content: Body

+ under "settings" choose to rewrite output as follows:

    \<a href="\[path\]" title="grant page for \[title\]"\>\[title\]\</a\>
    \<br /\>
    \[body\]

---

... and then add filter and sort criteria as desired.
> 3 votes

---
Tags: views, navigation
---


title: How to list categories dynamically

text:
# Question
Title: How to list categories dynamically
Is there a way of creating lists of categories dynamically?

For instance, say I currently have 2 TVs on the site. If I then add a DVD player product, is it possible to automatically generate a DVD player link (in a block etc)?

I've been playing with Views as I thought it may have done the trick, but I've had no success. Any pointers would be great.

# Answer
It sounds like a View of Taxonomy terms would meet your needs.

If I wanted to create a block with a list of items tagged with term in the category "Electronics" then I would do something like this:

1. Create a View with the following options:
    * Show Taxonomy Terms
    * of type Electronics
    * sorted by \[unsorted\]
2. Check the "created a block" box.
3. Add terms "DVD player", "DSLR camera", and "LCD monitor" to my "Electronics" vocabulary.
4. Add the relevant terms to the relevant product pages
5. Enable the block

Now, if I start selling Zunes next month (hah) then I can add term "mp3 player" to the "electronics" vocabulary and it will show up in the list of electronics-related terms in my block.
> 0 votes

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


# Question
Title: Expose only a specific content type to Views
I've been playing with Views in trying to expose only a certain content type to the View, but I cannot find a way to do so.

For example:

I have a content type called `Regions` and I have 3 nodes of type `Regions`.

When I create my View, is there a way to only expose the 3 nodes of type `Regions`?

Currently, it displays all the entries in my `node` table, which is not what I want.

# Answer
You want to add a filter to your view that is a content type filter, and then select "only show" and check off "Region" in the checkbox list.

So, edit your view, and on the left under "Filter criteria" click add. Then, scroll through the list of available fields to filter on and find "Content: Type", check that off, click "Apply". Then, on the left, select "Is one of" and on the right in the checkbox list select "Region", click "Apply".

After you've done that you can save your view. The changes should be applied and should be showing only nodes in the view that are of type Region.
> 1 votes

---
Tags: views
---


# Question
Title: Is It Safe to Delete Content Types "Article" and "Basic Page"?
It is highly unlikely we will ever use these in our CMS that we're implementing. They're just cluttering things up. Any reason why I shouldn't delete them?

# Answer
If you're not going to use them feel free to delete them. There will be no impact if you remove them.
> 7 votes

---
Tags: nodes
---


# Question
Title: How to include XML file in node for js map rendering?
I have a clickable map that uses js, css and xml to display. I previously was provided solutions in a previous thread How do I implement a clickable JavaScript map? using `drupal_add_css()` and `drupal_add_js()`.

1. Can I add multiple CSS files with `drupal_add_css()` using an array? Or, do I need to list these as separate commands?
2. The other problem is I need to have an XML file to feed the data into the JavaScript file. I attempted to edit the JavaScript file by hardcoding the XML file location, but that doesn't seem to work.

```
$.ajax({type: 'GET',url: 'sites/default/files/repfinder/xml/usaMapSettings.xml'

```

What should I be doing so that the JavaScript code recognizes the XML file? Without it, no map is displayed.

# Answer
> 0 votes
It looks like, according to the demo page you showed, the URL is relative to the path where the JavaScript is loaded; adding a slash in front of URL passed to `$.ajax()` should work.

```
$.ajax({type: 'GET', url: '/sites/default/files/repfinder/xml/usaMapSettings.xml'

```

---
Tags: 7, javascript
---


# Question
Title: Remove the extra headers from the e-mails sent
My site is made of book(book pages) and any authenticated user is able to send the book page as an e-mail to anybody (other user in the site / external user using e-mail) he wishes. The mail system is working fine but when (lets say) User1(user1@example.com) is sending mail to anyone, the sent mail headers are as follows:

> site\_admin@example.com on behalf of user1@example.com

I want that a user should be able to send the email directly by his e-mail id.

I am using Drupal 7, with Print and SMTP configured to send to book pages.

# Answer
> 5 votes
Apparently someone came up with code to put in a custom module that will remedy this issue:

http://drupal.org/node/461324

I've yet to try it though.

UPDATE:

I tried out an altered version and it worked for me. Here's what I had:

`email_sender_override.info`:

```
name = E-mail Sender Override
description = Overrides the 'Sender' of an e-mail message with the 'From' address.
core = 7.x
package = Webform

```

`email_sender_override.module`:

```
<?php
/**
  * @file
  *
  * Mail altering function to override the 'Sender' of a mail message with the address
  * in the 'From' field.
  *
  */

/**
  * email_sender_override_mail_alter
  *
  * Alters the sender of the e-mail message to be the same as the 'From' address.
  * Taken from: http://drupal.org/node/461324
  * See also:   http://api.drupal.org/api/drupal/includes!mail.inc/function/drupal_mail/6#comment-3243
  *             http://drupal.org/node/656472
  *
  * @param message
  *    the full e-mail message being sent -- this will be altered
  */
function email_sender_override_mail_alter(&$message)
{
    $message['headers']['Sender'] = $message['headers']['From'];
}
?>

```

# Answer
> 2 votes
Nothing much you can do about it. I've had issues with this in the past as well. This is a known issue, and here is a related ticket from drupal.org

It looks like the drupal\_mail() function that many modules (like rules) use purposefully sets the user email you specify as the 'From' field in the email, but still puts in your site's default email in the email's 'Sender' information. This causes different email clients to display the email differently. So, for example, Outlook displays the email in the format you're seeing, but Gmail will just display the 'From' information as you were hoping it will do.

Another good comment on this issue can be found in this thread.

Hope this helps clarify the issue a bit!

---
Tags: 7, emails
---


# Question
Title: How do I turn off clean URLs only for logged-in users?
The end-goal is to use filters to support AWS' new CDN dynamic content feature.

# Answer
This isn't possible in Drupal core because the clean url check occurs so early in the bootstrap phase, i.e. before you would be checking for permissions, settings, etc. One hacky possibility is to try and determine in your settings.php file if a session is open and then enable the clean\_url settings dynamically:

```
$conf['clean_url'] = 0;

```

But even that would probably be swamped by your htaccess settings and mod\_rewrite.
> 3 votes

---
Tags: uri
---


title: Custom Field For a Content Type

text:
# Question
Title: Custom Field For a Content Type
I have a field in my content type for blood pressure which, as you may or may not know, is measured ##/###. Currently, I have one text box and I ask the users to enter data in the form ##/### which works well but, on phones the '/' characters is annoying to navigate to. I was wondering how I could split up the field some that it would be 2 input fields separated with a '/' like:

Blood Pressure \[ \] / \[ \]

Where \[ \] represents a input field.

Any other suggestions to solve this problem would be great as well.

Thanks

# Answer
Honestly, I'd recommend creating two separate fields, one for systolic pressure and another for diastolic pressure. Then, use CSS to organize the fields the way you want. It actually makes more sense to do it this way since they represent two distinct values, even though they're used together conventionally to represent blood pressure.

To expand on the answer, specifically on the CSS side, here are some additional tips.

Once you've found a way to isolate the two fields with classes, I recommend displaying both of their div wrappers as `display: inline-block;` and, for the first field (systolic pressure) give it a rule that uses the `after` pseudo-class to add the '/'.

```
.classes .isolating .systolic-field:after {
  content: "/";
}
.classes .isolating .systolic-field {
  display: inline-block;
}
.classes .isolating .diastolic-field {
  display: inline-block;
}

```

If you're not familiar with CSS I can provide a more "concrete" example, but this should be sufficient.
> 5 votes

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


title: Feeds CSV import error

text:
# Question
Title: Feeds CSV import error
I am trying to import a CSV from a url using the feeds module, I set everything up but when I start the import I get the following error:

An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: XXXXX StatusText: OK ResponseText: Fatal error: Unsupported operand types in XXXXX/sites/all/modules/feeds/includes/FeedsConfigurable.inc on line 149

I have traced that error to this code, specifically the last line:

```
  public function getConfig() {
    $defaults = $this->configDefaults();
    return $this->config + $defaults;
  }

```

Any idea why I am getting this error?

I removed the default mappings because they were for an RSS feed, with GUID title etc....Could this have something to do with it? Are those required?

# Answer
> 1 votes
Are you running the alpha-4 or the current dev version of the feeds module? There have been a number of tickets discussing the same error condition you are having with node\_save on import that coalesced around this issue on Drupal.org with a resulting patch committed to the current dev branch. You can try downloading the current dev branch of feeds (almost a year older now than alpha-4) or applying the patch at #25 in the above issue if you don't want to accept all of the updates since the last alpha release.

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


# Question
Title: Changing the file of a file field (drupal 7)
I have a content type that contains a file field which is always a .zip file. When a file is uploaded I have a module that unzips the file to make a few changes then re zips the file to a new location. I would like to associate this newly created .zip file with my content type but so far I have not been able to find a way to do that. I initially tried to change the url of the file field in which it worked temporarily but it seems that the file field was later re-saved with the initial value.

I do my unzipping and re-zipped from hook\_node\_presave (I also tried to do from hook\_node\_insert) but neither seemed to work. Could anyone offer me any advice about how to change the file of a file field?

# Answer
File fields are referenced by their ID in the `file_managed` table; as well as updating the field in your presave hook, you'll probably need to update the file entity that relates to that id with the new filename/path.

This is just a basic example but it should give you a starting point:

```
// Get the file id from the field
$fid = $node->field_file[$node->language][0]['fid'];

// Load the file
$file = file_load($fid);

// Update the filename
$file->filename = basename($new_path);

// Update the uri (this must be in the format of a schema uri, e.g. public://folder/file.jpg
$file->uri = $new_path;

// Save the changes
file_save($file);

```

You might also want to update the `filesize` field; it's used in a few places in the system.
> 3 votes

---
Tags: 7, files
---


# Question
Title: (OG) Example function to detect User's roles?
Using Open Atrium 6.x-1.2 (Organic Groups 6.x-2.3 inc it's access control.mod), would someone be as kind to provide an example function that would detect the current user's role? It's my understanding OG overrides the standard Drupal permissions page. My end goal is to allow certain roles access to groups they don't specifically have membership (eg: Executive) for a custom OA/OG access control policy/module.

Would some implementation of Rules be possible here?

My skill level: no PHP but just started studying module dev

# Answer
> 0 votes
To test whether the currently-logged-in User has a specific Role, you can do this:

```
global $user;
if (in_array('Executive', $user->roles)) {
  drupal_set_message("I have the 'Executive' role.");
}

```

---
Tags: users, organic-groups, distributions
---


# Question
Title: How can I exclude the link for the current page when I have a list of links in Views?
I'm using Drupal 7 with Panels and Views.

I've configured a view to list several links to different panels. This view is displayed as a content pane on each of the respective panels to allow for easy navigation. However, this means that the link to each page is shown on that page as a link, which is unsightly and confusing.

Within Views, is there a way to configure the filters, etc. to hide or (best case) rewrite the link so that it is shown as plaintext rather than a link if it is pointing to the page being shown?

# Answer
> 1 votes
I had a similar problem with displaying node revision links on a node page, views would display the link to the current node being displayed. To fix this I edited the views template file and checked myself whether the link pointed to the current page or not and only displayed a link if it wasn't to the current node.

---
Tags: 7, views
---


# Question
Title: Allowing users to 'follow' taxonomy terms. Then creating a view which displays a list of nodes which are assigned the 'followed terms'
I'm looking for the recipe which emulates a feature from the popular tech blog: Mashable.com

Here's what I'm looking for:

1. Nodes are assigned taxonomy terms.
2. Users may view a node, and see the taxonomy terms which are assigned to this node.
3. Users may 'follow/subscribe' to each taxonomy term assigned to this node.
4. A custom view (called "My Custom Stories") will be configured, for each user, which displays a list of nodes which are relevant to the taxonomy terms to which he subscribed.

For example:

1. A node X is created which is assigned the terms 'Politics', 'Apple', and 'China'.
2. User A follows/subscribes to 'Politics', while User B follows 'Apple'.
3. User A's 'My Custom Stories' view will only contain a list of nodes which are assigned the 'Politics' taxonomy term, while User B will see a list of 'Apple' nodes.

I'm particularly interested in the 'taxonomy term follow' modules required for this recipe, as well as how the 'Custom Stories' view will be configured.

I'd appreciate any tips. Thank you!

# Answer
> 0 votes
My idea:

You could create a new content type Taxonomy Subscriptions, using taxonomy and user reference (you will need References module).

Then with Rules module you could manage (create) the subscriptions for terms and then you view will be joined with the created content type.

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


# Question
Title: how to preserve interface language for a multilingual website?
I have a multilingual website with five different languages represented. I have to manage and maintain all the languages, but each time I switch to a particular translation for a piece of content the interface changes too.

I speak English - how do I maintain the interface language in English while managing the translated content?

This too is true for coworkers - the native Japanese speaker needs to be able to maintain the Japanese while he works.

The language preferences for each user is set to their native language - is there a way to have that enforce the interface language we are working in when administering the site?

thanks

# Answer
> 2 votes
Your best bet might be the Administration Language module. It allows you to set the general and user specific administration language. The module doesn't seem to be maintained currently/anymore though and there's only a dev version for the Drupal 7.x branch so you may want to check the bug reports and test it first. I've used it on a few sites without running into any major issues so it should be worth a shot still.

# Answer
> 1 votes
I might be mistaken, but I think if you set your default language editing your own user, it will be preserved when editing content on localized versions of the site.

---
Tags: 7, i18n-l10n
---


# Question
Title: How to add additional tabs to user profiles
I'm trying to find a way to add another tab to the tabbed menu under each user's username on the user/\* page.

I want to have View, Edit, and an additional link. I'm not sure where I need to be looking in the code to edit this menu and I can't find any documentation thus far. Any help would be great.

Thanks

# Answer
I believe you can implement `hook_menu` in a custom module and use `MENU_LOCAL_TASK` as the type, and the path needs to start with `user/`

```
function HOOK_menu() {
  $items['user/mypage'] = array(
    'title' => t('My Tab'),
    'type' => MENU_LOCAL_TASK,
    //'page callback' => 'mymodule_mypage', //mymodule_mypage should be a function that returns HTML for the content area
    //'page arguments' => array(0, 1, 2), // 0 is arg(0), 1 is arg(1) etc...
  );
  return $items;
}

```

For all the array elements see this page
> 2 votes

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


# Question
Title: EntityRegistration: How do I show who is registered to other registrants/members
Actually I am relatively new to Drupal - so maybe for a Drupal-Crack this is chicken-food - but not yet for me :-)

I'm building a new Drupal 7 (7.14) site using "Views" and "Entity Registration" (Beta1) to build a event system where members can join events and leave some comments. Therefore I've set up the "Event" entity using Drupal fields and the Views module. Then I've created registrations for the events and added them to the "Events" as a field. No problem so far - works great and users can join events incl providing their additional registration information (Events are "Scuba Dives" and additional information is the Equipment Configuration, Gasmixes, Body-Team, etc).

As an event organizer (creator) I can see a tab with the list of registrants (divers) but I don't see this tab/information as a normal member/registrant.

This is where I got stuck: How can I show the list of participants to all members (role)? I like to show them on the same "page" as the eventdetails are. Maybe creating a block or so? Maybe create a view for a block (with fields, sorting and grouping) and show this as block on the events.

I already know that I can customize a nod by adding a theme-template for a specific content-type. Don't know if that would work to bring the list of participants to my events...

As you see I am not really sure what way I should go with this and what make most sense. Any help/hint would be great!

Cheers, Marc

# Answer
I've got it work by creating a View with a contextual filter for the event-id. Then in the event-page (using Panels) if added the event-id to the arguments when rendering the view into a pane.
> 0 votes

---
Tags: 7
---


# Question
Title: Form field with support for multiple values
I'm building a costum form using Drupal (7) Form API

I want to create a text field with possibility to add multiple values through autocomplete. The idea is to allow the user to add taxonomy terms to my instance that is to be saved through the form.

Final goal is to present selected values in a table with fields

Term name | Vocabulary | Actions

Where Term name is a input field with autocomplete. When a term is selected, Vocabulary name is appended through JS, and actions just contains a "Remove" button.

And finally under this table I'll have a button with "Add another value". I'm seeing this done through the Fields API, if I'm setting a field to allow unlimited values. But I want to build this my self, as I'm not using a field, but my own costum database.

How do I accomplish this through Form API?

# Answer
> 4 votes
Found the solution in AHAH

With AHAH you can dynamically add new fields to the form using JavaScript. Be sure to read http://drupal.org/node/331941 with examples of implementations from e.g. the Poll module.

---
Tags: forms, 7
---


# Question
Title: Using RegEx with Rules to compare email addresses
I have a client content type with an email address and when a user creates an account I want to verify the users email address with the email address of the client content type to make sure that the user is an employee of the client and if so let them create an account.

My question is, can I make a rule which uses Regular expressions to compare the domain name of the two email fields?

Thanks

Kieran

# Answer
> 1 votes
You can use access rules which is built into core drupal.

Go to "/admin/user/rules" and add a new rule, for example `%@domain.com`, this will allow anyone to register who has that specific domain.

---
Tags: 7, rules
---


# Question
Title: Which Drupal 6 theme framework is good for creating a responsive web design?
Which Drupal 6 theme framework is good for creating a responsive web design? Is it advisable to use Zen starter-kit to develop a responsive theme?

# Answer
> 1 votes
Omega offers good responsive features. "Fully Responsive Grid layouts based on 960.gs standards."

I have used this for many 7 projects but not tried 6, if this is a new project you are starting I would recommending starting with 7.

# Answer
> 1 votes
We used Adaptive Theme for a few D6 websites.

---
Tags: theming
---


# Question
Title: How to limit db_update() to update first n rows
I want to update first n rows using db\_update(). Is it possible?

I know we can use db\_query(). something like

```
UPDATE <table_name> SET <field_name> = <value> LIMIT <num_rows>

```

I want to know whether this is possible using db\_update()

# Answer
> 5 votes
It doesn't look like it's possible I'm afraid.

`db_update()` uses the `UpdateQuery` class, which doesn't support the `range()` method that a `SelectQuery` does.

You could probably subclass `UpdateQuery` and add that behaviour, but for the amount of work that would take you might be better off just using a raw SQL statement with `db_query()` like you've suggested.

---
Tags: 7, database
---


# Question
Title: I edited the database but the site's showing old content no longer in it
I needed to find-and-replace text across several nodes in my database, so I exported it via PHPMyAdmin and then ran the find-and-replace on the resultant .sql file. I then dropped all tables in my database and imported the edited .sql file. Now when I inspect my database with PHPMyAdmin I see that the text I removed with the find-and-replace is no longer there; however when I view or edit a node with the text I've replaced I see the replaced text still there. This is despite the fact that if I search for that text in the .sql file I imported (or a fresh .sql export after the import) I don't find it anywhere.

Why is this? How can I fix it, and successfully find-and-replace text in my site with the method above (or some better method, though that's slightly changing the question)?

## Example

If you view source on http://gwwc2.centreforeffectivealtruism.org/node/546 you'll see at the start of the node content:

```
<style type="text/css"> <!--        @page { margin: 2cm }       P { margin-bottom: 0.21cm }         A:link { color: #2198a6; text-decoration: none }    -->     </style>

```

However when I run `SELECT body_value FROM field_revision_body WHERE entity_id=546` (which seems to be the right query as I'm using D7) I don't see this anywhere in what's returned, which instead starts:

```
<p>A perennial criticism

```

# Answer
> 1 votes
Have you refreshed your caches? Configuration -\> Development -\> Performance -\> Clear all caches

---
Tags: database
---


# Question
Title: How to get the field settings in drupal 7
Here is the scenario.

I have a taxonomy term reference field, which is referenced to a taxonomy vocabulary, for example it is associated with category vocabulary. Now I need to fetch the vid of the category vocabulary which is associated to that particular field.

or is there a way to fetch the field settings in drupal 7?

# Answer
> 13 votes
You can use a combination of field API and taxonomy API functions to get this info:

```
$field_name = 'field_FIELD_NAME';

// Get the field info
$info = field_info_field($field_name);

// The link to the vocab is stored as it's machine name
$vocab_machine_name = $info['settings']['allowed_values'][0]['vocabulary'];

// Load the vocab by machine name
$vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);

// Finally, get the vid
$vid = $vocab->vid;

```

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


# Question
Title: Detecting one account being accessed from multiple computers at the same time
I need to detect member access to the same account from different computers or web browsers at the same time with same email and password?

Are there any options or modules to get this information?

# Answer
If you just want to log the user out to prevent multiple logins at the same time, then you could use the Session Limit module.

> Session Limit allows administrators to limit the number of simultaneous sessions per user.

Also taken from the project page:

> Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.
> 2 votes

# Answer
I haven't seen any modules that do this, but you can see the user status login status. Have a look at how the admin menu module does this.

You can then build your own little module and deny or allow access to the site based on the status.

I can only speak for d6 as I haven't looked at d7/d8 as of yet.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Does drupal_add_css not load duplicate filenames by design?
If I try to add a css file using drupal\_add\_css to a custom module where there is already a css file loaded with the same name elsewhere (in my case in the theme, based on Zen), the module version does not load at all. Nothing to do with overriding styles - the two files contain completely different style information. If I change the filename in the custom module to something else which does not conflict, it loads correctly.

The question is is this by design? If not, is it a known bug? In my opinion this should not happen as a module developer has no idea what css files will be called in any custom theme.

# Answer
Looking at the `drupal_add_css()` function, it seems this behaviour is by design.

For any CSS that you add using the function *without* using 'inline' as an argument, the array of files is keyed by the first argument (string) that you pass in. So if you were to run:

```
drupal_add_css('file.css');

```

And another module has also called `drupal_add_css()` with the same file name, the original will be overwritten.

As Marius Illie mentions in a comment above, the best way to avoid this is to prefix any CSS files you add with your module name.
> 2 votes

---
Tags: 7, theming
---


title: I can't access the modules page

text:
# Question
Title: I can't access the modules page
I have installed a few modules for the site; one of them is causing an error, and I can't access the modules page.

The error I see is the following one:

> Fatal error: Call to undefined function ctools\_include() in /var/www/vhosts/haweraprezchurch.org.nz/httpdocs/sites/all/modules/features/includes/features.ctools.inc on line 226

How can I access the module page?

In my case I am using Drupal 7.

# Answer
I always find the simplest way to deal with this is just to go to the `system` table in the site's database, and set the `status` column for the problematic module to `0`.

After clearing the cache tables (either with Drush, or manually) you should be able to access the modules page again.
> 2 votes

# Answer
Your error message means that the Features module is looking for Chaos Tools function that it can't find.

It looks to me like you haven't got Chaos Tools enabled, as the `ctools_include` function does exist in the latest version.

If you use Drush, head to the terminal and type `drush en ctools` to enable Chaos Tools, or `drush dl ctools` to actually GET Chaos Tools if you don't have it and see if the error message persists.

If you don't use Drush, then go and get Drush :-)
> 1 votes

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


title: Organizing common functions/classes

text:
# Question
Title: Organizing common functions/classes
Currently I have a common.module for storing common functions. This file is getting way to long and I'd like to start breaking it up by similar functionality or by class:

```
common.inc
common.query.inc
common.taxonomy.inc
Node.php
etc...

```

I thought I could add `files[]` entries to my common.info file but this doesn't seem to source these files.

I need these files to be always sourced: on any page load, on full drupal bootstrap, and on update.php.

# Answer
In your `.module` file add the following to the very top of the module (just after the opening `<?php` tag):

```
module_load_include('inc', 'common', 'common.query');
module_load_include('inc', 'common', 'common.taxonomy');

```

For your reference:

`module_load_include();`

**EDIT**

Seeing as how you're not going to be needing these on cached pages, then putting them in `hook_init()` is much better practice.

Like the following:

```
function common_init() {
  module_load_include('inc', 'common', 'common.query');
  module_load_include('inc', 'common', 'common.taxonomy');
}

```
> 0 votes

# Answer
You can split out class definitions into separate files and then use `files[]` to cache those class definitions. That's what files\[\] does.

On top of that you could have a common.module file that minimally implements `hook_help()`, and would `require_once()` all the files you want. This is of course not the best way to go; consumers should require\_once() the files on their own, for only the files they need.

Also if you're trying to use an external library, you might consider taking a look at the Libraries module.

EDIT: Uh, didn't see that it was tagged 6. :-) Drupal 6 doesn't support `files[]` in the .info file at all.
> -1 votes

---
Tags: 6
---


# Question
Title: Programmatic user registration not forcing user to activate account
I'm manually creating a user and then sending a notification email as follows:

```
$new_user = array(
  'name' => $username,
  'pass' => $password,
  'mail' => $email,
  'status' => 1,
  'init' => $email,
);

$account = user_save(drupal_anonymous_user(), $new_user);
 _user_mail_notify('register_no_approval_required', $account);

```

However, the user is able to login right away. How can I enforce account activation? I have it enabled in the admin panel

# Answer
You can use the LoginToboggan Prevent preauth module is available for Drupal 6 and 7. And it realy does all the stuff. We can have "Email account activation without admin approval and also a user set password".

Code:

```
    $new_user = array(
      'name' => $username,
      'pass' => $password,
      'mail' => $email,
      'status' => 1,
      'init' => $email,
      'roles' => array(logintoboggan_validating_id() => TRUE)
    );
   $account = user_save(NULL, $new_user);
   // Send mail with account confirmation
   _user_mail_notify('register_no_approval_required', $account);

```

P.S. Don't forgot to uncheck 'Immediate login' option.
> 3 votes

# Answer
This can't be accomplished directly with Drupal.

When a user registers and 'email verification' is enabled for the website, Drupal creates a random password for the user and sends them a password reset link via email. The user CAN login, but that would require knowledge of the random password.

The only way I was able to accomplish this was by setting the users' status to `0`, then sending a custom email with a link to a custom verification page. The link contains the ID of the user and a hash of a private key concatenated with the user's email. On the verification page, I pull the user's email from the database based on the ID in the URL, concatenate the private key to the email and hash it, if the hash matches the hash in the URL, I set the user's status to `1`, enabling the user to login.
> 2 votes

---
Tags: 7, users
---


# Question
Title: how to check in ajax form callback if form for failed validation
I have a form and on and implemented a ajax submit callback which calls this function:

```
function popover_ajax_callback($form, &$form_state) {
    // watchdog("ajax_callback", "testing ajax callback", array(), WATCHDOG_ALERT);
    return '<div id="ajaxchanger">' . $form_state['values']['first']['field_firstname'] . '</div>';
}

```

How do I check if the form failed or passed validation within this function?

# Answer
> 5 votes
```
function popover_ajax_callback($form, &$form_state) {
  $errors = form_get_errors();
  if( $errors ) {
    // error detected, do something
  } else {
    // everything is ok
  }
}

```

but your return value is not ok. You need to return an renderable array. You may want to try someting like this:

```
return array('#markup' => '<div id="ajaxchanger">' . $form_state['values']['first']['field_firstname'] . '</div>');

```

---
Tags: 7, ajax, forms
---


# Question
Title: Commerce: is there something in the basket?
Is there a global variable of sorts that can be used as a bool to determine if something is in the basket?

# Answer
> 1 votes
This is what i use :)

```
function items_on_cart(){
  global $user;
  $cart = commerce_cart_order_load($user->uid);
  $line_items = count($cart->commerce_line_items) ? true : false;
  return $line_items;
}

```

# Answer
> 0 votes
Commerce Cart has the following function `commerce_cart_order_session_exists()` which you could probably use to set a boolean value.

> Checks to see if any order ID or a specific order ID exists in the session.

To answer your question directly though, there is no global variable to detect carts.

---
Tags: commerce
---


# Question
Title: Fatal error: Call to undefined function menu_load_all()
I have (D7) code that uses menu\_load\_all() to get a list of menus to pass as options for checkboxes to the admin interface of a module I'm writing.

To test and make sure my little snippet was returning the correct values for menu titles, I pasted it into a block of eval'd code in the content of my staging site, and it was fine. It returned a nice little array of titles and so I straight copy/pasted it into my module's code.

Now when I enable my module, I get this error:

```
Fatal error: Call to undefined function menu_load_all()

```

WTH? Why did this work in eval'd and not in my module, and what do I do to get my module access to this API function?

Full code of module available for your perusal.

# Answer
> 1 votes
The only thing I can of is that you're calling `menu_load_all()` in `hook_install()` or `hook_enable()`; all system module files aren't necessarily included when those hooks are invoked.

If that's the problem, you can force the file with the function to be included by adding the following line of code to the top of your `hook_enable()`/`hook_install()` function:

```
module_load_include('module', 'menu');

```

---
Tags: routes
---


title: Comments as a block

text:
# Question
Title: Comments as a block
I need to display the comments for a node as a block. For drupal 6 there the comment block module but it's not available for drupal 7 as well.

It there a way to achieve the same functionality in drupal 7 or I'll have to build a custom module for this?

Thanks :)

# Answer
You could use Views to display comments associated with a node. No coding required.
> 1 votes

# Answer
Panels module will give you a solution
> 1 votes

---
Tags: 7, comments
---


# Question
Title: drupal gridview drop down menu - showing all menu and sub menus under one parent
I would like to show drop down menus in gridview format. ideally it should show all sub menus and sub sub menues under one parrent. any module which can service this purpose?

# Answer
> 0 votes
Maybe you could use the Superfish module? Here is a quote about it (from the module's project page):

> ... integrates jQuery Superfish plugin with your Drupal menus:
>
> * Unobtrusive JavaScript.
> * Keyboard-accessible, screen reader friendly.
> * Multi-column sub-menus. (Megamenus)
> * Easing effects with the jQuery Easing plug-in.
> * Automatic width calculation (sfAutomaticWidth plugin) (Use the development release)
> * Automatic sub-menu width calculation (Supersubs plugin), automatic sub-menu placement (Supposition plugin; prevents sub-menus from appearing off-screen.)
> * Touch-screen compatible. (almost)
> * Small-screen compatible. ( and vertical accordions)
> * Window width (client-side) and UA string (client-side and server-side) detection for touch and small screen plugins (no CSS3 media-queries)
> * RTL (Right-to-left) language support.
> * Plenty of built-in options for designers.
> * And a whole lot more...

# Answer
> 0 votes
I think, the Megamenu module is more useful. Demo is here.

Here is a quote about it (from the module's project page):

> Mega menus are a type of drop-down, which seeks to overcome some of the usability drawbacks to traditional style drop-downs. Primarily, mega menus have two advantages:
>
> * The information architecture of your navigation is made clearer and is visible all at once
> * The amount of clicking, searching, and navigating is reduced
>
> This module allows you to build mega menus by leveraging jQuery and the existing Drupal menu system. Megamenu takes a Drupal menu that is 3 levels deep, and converts it into a categorized 3-level mega menu, which is placed into your site as a block.

---
Tags: views, 7
---


# Question
Title: Drupal Commerce: How to theme Product Field
On the product display node of Drupal commerce, you have the "Product field". This displays all the products that are attached to the product display. The products are displayed in a drop down menu.

By default, any fields on the product are displayed above the drop down menu. How can I theme this field, so the field are displayed below the drop down menu.

# Answer
> 3 votes
I have figured this out.

1) Create a file named: `node--NAME-OF-CONTENT-TYPE.tpl.php`

2) Insert the following in the file:

```
<?php print render($content['field_product']); ?>
<?php print render($content['product:NAME-OF-FIELD-ATTACHED-TO-PRODUCT']); ?>

```

`<?php print render($content['field_product']); ?>` is the add to cart drop down menu, so if you put the fields below it, they will appear under the add to cart drop down menu.

3) Clear cahces (at YOURSITE.com/admin/config/development/performance)

---
Tags: theming, commerce
---


title: Drupal 7 Omega - js file not working

text:
# Question
Title: Drupal 7 Omega - js file not working
Okay so I have a headache trying to figure this one out. I am working in Drupal 7 with the Omega theme. Trying to get a js file to work.

I have a js file that is set up through the .info file and is showing in view source. The file contents are below. I can get this to work when I place in the wysiwyg on the page however it won't work when I set it up properly as a .js file.

```
 (function ($) {
// All your code here
  $('#block-menu-menu ul.menu').removeClass('menu').addClass('sub-menu');

// Create the dropdown base
  $("<select />").appendTo(".menu");

  // Create default option "Go to..."
  $("<option />", {
     "selected": "selected",
     "value"   : "",
     "text"    : "Go to..."
  }).appendTo(".menu select");

  // Populate dropdown with  items
  $(".menu a").each(function() {
   var el = $(this);
   $("<option />", {
       "value"   : el.attr("href"),
       "text"    : el.text()
   }).appendTo(".menu select");
  });

  $(".menu select").change(function() {
    window.location = $(this).find("option:selected").val();
  });

})(jQuery);

```

My issue is it works when placed in the page, but when I place in the .js file and call it through .info it won't work. Again the file shows up in the view source so it is there. I have to be missing something. NOTE * I am not a developer.

Any thoughts? Thank you!

# Answer
> 2 votes
You need to wrap your javascript in a Drupal Behaviors handler. You can read the Javascript Documentation for more information (scroll down and look for the heading "Behaviors").

Basically, your code will end up looking something like this:

```
    (function ($) {

      Drupal.behaviors.exampleBehavior = {
        attach: function (context, settings) {
         // All your code here
       }
     };

   })(jQuery);

```

If this does not solve your issue, you use check your site for any javascript error messages and update your original post to include them. The way I recommend to do this is to install the Web Developer plugin for Firefox and open up the Error Console (tools -\> web developer -\> error console) and look for messages highlighted in red.

---
Tags: javascript, theming
---


title: Date countdown without javascript

text:
# Question
Title: Date countdown without javascript
I have a content type that when created is "due" 10 days later. I'm looking to create a field that has a numerical value of the days left before it is due and if it is past due, show a negative integer value. This field will be used for Views sorting, so I can't use javascript counters like the countdown module.

Can anyone help on how to do this?

# Answer
I would start with a standard date field and then create a new field formatter that displays the date in the way you describe.

Before you dig in I would look around for someone that has already done this, it seems like a pretty common use case for working with a date.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: General template (node.tpl.php) being used instead of specific template (node-article.tpl.php)
I'm creating my sub-theme based on Zen's starterkit. I copied node.tpl.php from zen to my theme and started making some customizations. Then I realized that I really only wanted those customizations to happen to the Article content type, so I renamed my subtheme's node.tpl.php to node-article.tpl.php but when I do it doesn't get used when I'm viewing my front page which has a list of articles. If I rename it back to node.tpl.php then it immediately gets used again. Back to node-article.tpl.php and I get nothing.

What am I doing wrong?

# Answer
Are you using Drupal 7? If so, you should just leave `node.tpl.php` as it was originally and call your customized version `node--article.tpl.php`.

If you are using D6 you are naming the file right, you should just leave a copy of the original `node.tpl.php` in your subtheme folder.
> 4 votes

---
Tags: theming
---


# Question
Title: How to read a Drupal 7 node as a css file?
I know that this isn't how Drupal is meant to be used, but I have this special case where I created a node that ends in a .css extension and need to have that file be used as the css file for the whole website.

So what I've got are:

1. a node named styles.css residing at the url "http://www.mysite.com/styles.css"
2. all of my regular nodes linking to that file. the "" is hardcoded into page.tpl.php

Drupal appears not to read styles.css as a css file; any ideas?

# Answer
> 3 votes
If you know that Drupal isn't meant to be used this way, then why would you do it? Are you trying to allow the end user to edit the CSS through the UI? There are better tools for that! (eg. Live CSS, Sweaver, Live Themer...)

If you update your question and tell us which problem you're trying to solve, we can help you much better.

---
Tags: theming
---


# Question
Title: Checkout page not found when order created through Drupal Commerce API for not authenticated (anonymous) user
I have the following code inside rules - action (being triggered by webform submission)

```
<?php
global $user;
$product_id = 1;

// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid , 'checkout_checkout');

// Save the order to get its ID.
commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);
?>

```

the code works perfectly when i am logedin, however when i submit the webform as not authenticated user, i get sent to checkout/12, I get page not found.

there is no errors in the log, and i see in the backend that the order was created... please help...

# Answer
> 7 votes
You need to add the order to the session, see commerce\_checkout\_access().

Something like this should work:

```
$_SESSION['commerce_cart_orders'][] = $order->order_id;

```

between saving the order and redirecting.

---
Tags: 7, webforms, commerce, rules
---


title: Image array on a node page

text:
# Question
Title: Image array on a node page
Is there a simple way to add an array of images to a node page?

I would be using the file directory that I am using to upload my images to, using IMCE (sites/theme/files). The array would return all the images I have stored in that folder. I just need a very simple solution, being very new to PHP.

# Answer
> 1 votes
Are you using Drupal 6, or Drupal 7? You should look into the Content Construction Kit module, which would easily allow you to add images to nodes and arrange them. You can set the number of allowed elements to "unlimited" for multiple images. If you want to be able to place your node images on different parts of the node page, try the Panels module.

### Update in answer to first question, below

Why yes; one of the great strengths of Drupal is its ability to let you just plop down some php anywhere in the page you need to put it (but please, don't put your php in the database, if you can help it!). If all you wanted to do was display images from a folder at a given URL, rendered in your own code, all that you would need would be a menu with 'page callback' set. If you want to modify a node, though, then you will need to learn about the scary render array. When you find something in the page that you want to change, the easiest thing to do is to set the #markup element to the exact HTML content you want to display. If you do not want to replace an element, you can use #prefix or #suffix to put HTML before or after the given item.

If you make yourself a theme, you can add a preprocess hook to it (in template.php):

```
function MYTHEME_preprocess_node(&$variables, $hook) {
  if ($variables['node']->type == 'page') {
    $variables['content']['field_document_file']['#prefix'] = '<div class="document-wrapper clearfix">';
    $variables['content']['field_document_file']['#suffix'] = '</div>';
  }
}

```

This snippet, simplified from the above-quoted article on render arrays, adds a div around the CCK field called 'field\_document\_file'. In your case, you'd probably just want to put some HTML into #suffix after the node body, which I believe is simply $variables\['content'\]\['field\_document\_file'\]\['#suffix'\]. To find out what's in a render array, install the devel module, and add a `dpm($variables)` to your preprocess function. You're also likely to find the search krumo module to also be highly useful.

As far as actually getting the images onto the page, I trust that you can write your own code with file\_scan\_directory. Just remember to write secure code when outputting any data that was supplied by the user.

Anyway, that is what you would do; in general, just adding cck image fields and populating those with the images you currently have stored in folders might be easier. drush entity might help out here. If you have a special need to keep your images in folders, then it's render arrays for you.

An easier option might be to just put your php code in a node-page.tpl.php. I rejected this as an option at first because I felt it would not give you enough flexibility to position your elements in the html output. However, with node-page.tpl.php, you could put your images before or after the node contents, and perhaps adjust the positioning to your satisfaction with css. This would be easier than fixing up the render array.

---
Tags: media
---


# Question
Title: Displaying a table from local menu (Drupal 7)
I have added a menu item to one of my nodes and I would like to display a table when the user selects this menu. Here is my menu implementation:

```
function arcade_projects_menus_menu() {
  $items  =  array();
  $items['node/%/versions'] = array(
    'title' => 'Versions',
    'description' => 'Configuration for the User Warn Module.',
    'page callback' => 'versions_view',
    'access callback' => 'arcade_versions_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

```

and here is my page callback:

```
function versions_view() {
  $block = array();
  $rows = array();
  $header = array('Project Name', 'Screenshot' , 'Updated');
  $format = 'l, F j, Y  - G:i';
  $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');
  $block['content'] = theme('table', $table);
  return $block;
}

```

I would expect this code to display an empty table saying 'No terms found' but instead I get a blank white page. Is it possible to display a table from a page callback?

# Answer
> 1 votes
From a page callback you need to return something that can be run through the `render()` function. This will either need to be a string, or a properly formatted render array.

You can use:

```
$block = theme('table', $table);
return $block;

```

or

```
$block['content'] = array(
  '#markup' => theme('table', $table)
);
return $block;

```

or even

```
$block['content'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No terms found')
);

```

The last method is probably the most preferable in terms of extensibility, as it potentially allows other modules to alter the table before it's rendered. Using either of the other methods will render the table into an HTML string, and other elements in the system will no longer be able to alter it before it's displayed.

---
Tags: 7, routes
---


# Question
Title: How to hide taxonomy terms from node display and still have them indexed by Drupal search?
I use content type with a term reference field. I would like users to search by taxonomy terms in that field so I keep the field visible in the main node display. However due to other reasons I would like to hide these terms from the view but keep the content searchable by these terms.

For example I would like to have synonyms searchable I will keep in my term reference field but I don't want users to see all possible variant of the word.

How to hide taxonomy terms from the node display and still have them indexed by Drupal search?

# Answer
I would recommend the Search API. You end up with much more control over the search results, and you have the extra flexibility of using it with views.

You can configure it to also include taxonomy term descriptions in the index which would be an excellent place to store your synonyms/alternate search terms. You could even create a new vocabulary that is never displayed on the node (just set it to hidden in the display tab for the content type), and is limited to only search terms.
> 1 votes

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


# Question
Title: Way to see the date roles were assigned?
Is there a way to setup a view in drupal 6 that shows me users assigned new roles in the last month and who assigned the role?

I have video products that sell both through the online store and at the front desk of various martial arts schools. Currently the online portion is handled with ubercart granting access to appropriate roles. However tracking the sales from the front desk is messy, using the role watchdog module and filtering the email notifications.

Being able to see all role modifications in the last month would simplify tracking of sales to each school greatly.

# Answer
For D6, check out the User Role History module
> 0 votes

# Answer
You could create a content type User Role, then with Rules module register when a role it's assigned.
> 1 votes

# Answer
Not currently possible; see http://drupal.org/node/1263032
> 0 votes

---
Tags: ubercart, users
---


# Question
Title: Which modules should be listed as dependency of my module?
If my module calls a function of another module, that other module should be listed as a dependency of my module.

Now my module only provides some field handlers for the Views module. On the one hand, my module is useless without the Views module. On the other hand, my module does not call any functions or methods provided by the Views module.

Should I add Views to the list of dependencies for that module? If yes, would that change if my module provides other functionality unrelated to views (like custom pages)?

Note that I used Views only as an example. The question applies to all optional modules, that define hooks.

# Answer
> 3 votes
As I see it, you only **need** to list a module as a dependency if it's possible for your module to cause errors or bugs if the other module (Views in your example) is not enabled.

That said, if your module really doesn't do much without Views as you say, it seems to make sense to list it as a dependency. At this point it's mostly about user experience. You want it to be clear to users that Views is essentially required in order to use your module.

Note that there are other options in the middle also: you could use hook\_enable to check whether `module_exists('views')` when your module is enabled, and if it's not you can use drupal\_set\_message() to tell the user that it's probably a good idea to install Views.

# Answer
> 3 votes
The Drupal.org .info file documentation does not define a dependency in itself other than stating a module cannot be enabled if a dependency is not present.

I guess you have to decide for yourself what you would consider a dependency. Personally, if a user needs to use Views in order to use your module than you would want to make sure it is installed.

If you don't want to make a module a dependency because it only supports secondary functionality in your module, you can use module\_exists() to make sure your module doesn't die if the function it is calling is not there.

# Answer
> 0 votes
If your module implements any views API hooks, then you should declare views as a dependency.

Also, consider that at some point in the future, if you don't declare views as a dependency, there will be a user who will send you an email asking you why your module doesn't do anything. :-)

---
Tags: .info
---


# Question
Title: How can I create some specific content with a cron job
I need to create a specific content, for instance, a Page, every 15 days.

Of course that goes into some cron job.

But how can I do that? Do I need to implement the hook\_cron at my `.module`?

# Answer
> 2 votes
You got it! Implement hook\_cron and inside that function create a node using the node\_save().

Each time you run cron by going to /cron.php or each time it is called from your cron job, your hook will automatically be called.

Here's some sample code, partly borrowed from http://drupal.org/node/1111514

So your .module file should at least have the following,

```
// Implementation of hook_cron
mymodule_cron {

  // add node properties
  $newNode = (object) NULL;
  $newNode->type = '{NODE_TYPE}';
  $newNode->title = '{NODE_TITLE}'
  $newNode->uid = {USER_ID};
  $newNode->created = strtotime("now");
  $newNode->changed = strtotime("now");
  $newNode->status = 1;
  $newNode->comment = 0;
  $newNode->promote = 0;
  $newNode->moderate = 0;
  $newNode->sticky = 0;

  // add fields
  $newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
  $newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

  // save node
  node_save($newNode);
  }

```

After you enable your new module, just run cron by hand (go to /cron.php) and test it out to see if your node was created!

---
Tags: hooks, nodes, cron
---