# Question
Title: How to display messages from a block separately from $messages in page.tpl.php
I have a webform which works as a newsletter subscription form: it displays a textfield for an email and a button. When the button is clicked, a notification message is displayed on top of the page where any other messages are usually displayed.

However because the webform is a block and it's displayed in the sidebar, it would be more usable if the message is displayed right above the block, where visitor's focus currently is, instead of top-middle of the page. Is this something possible to implement?

To generalise: is it possible to display messages from different blocks/modules in different sections of the page instead of the unified `$messages` variable?

# Answer
> 3 votes
If the notification is being set in the $messages variable used in page.tpl.php you can emulate theme\_status\_messages() by adding this to your theme's template.php file

```
function YOURTHEME_preprocess_block(&$vars) {

  $block = $vars['block'];

  if ($block->module == 'MODULENAME' && $block->delta == 'DELTA') {
  $output = '';
  foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
    $output .= "<div class=\"messages $type\">\n";
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach ($messages as $message) {
        $output .= '  <li>' . $message . "</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }

  $vars['messages'] = $output;
  }
}

```

Then in the template file for just your block (e.g. block-MODULENAME-DELTA.tpl.php), print the $messages variable.

---
Tags: 6, notifications, forms
---


# Question
Title: content profile title token issue (trying to write own module)
```
/**
* Implementation of hook_token_values().
*/
function content_profile_token_token_values($type, $object = NULL, $options = array()) {
  $values = array();
  switch ($type) {
    case 'user':
      if (isset($object)) {
        $account = user_load(array('uid' => $object->uid));
      }
      else {
        global $user;
        $account = user_load(array('uid' => $user->uid));
      }

      $node_profile = content_profile_load('profile', $account->uid);
      $values['profile'] = ($node_profile->title) ? $node_profile->title : '';

      break;
  }
  return $values;
}

/**
* Implementation of hook_token_list().
*/
function content_profile_token_token_list($type = 'all') {
  if ($type == 'user' || $type == 'all') {
    $tokens = array();
    $tokens['user']['profile'] = t('Profile title of authors content profile');

    return $tokens;
  }
}

```

I have created a module, and added a .info file as intended, but when I check the token list for a image field title I don't see any of the tokens implemented by my module.
What am I doing wrong?

**UPDATED!!!**

Now i see my token in imagefield token list, but it doesnt works == doesnt add content profile title for img...

# Answer
> 1 votes
It is not appearing because the ImageField module is using user tokens, for the image title, while your module is defining node tokens.
You can see this from the code in imagefield\_widget.inc (`imagefield_widget_settings_form()`), which is the following one:

```
  $form['title_settings']['title_type'] = array(
    '#type' => 'select',
    '#title' => t('Input type'),
    '#options' => array(
      'textfield' => 'textfield',
      'textarea' => 'textarea'),
    '#default_value' => !empty($widget['title_type']) ? $widget['title_type'] : 'textfield',
    '#description' => t('Choose type of field to be displayed to the user.'),
  );
  $form['title_settings']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Default Title text'),
    '#default_value' => !empty($widget['title']) ? $widget['title'] : '',
    '#description' => t('This value will be used as the image title by default.'),
    '#suffix' => theme('token_help', array('user')),
  );

```

The tokens you define in your module are node tokens, which are not shown when the code calls `theme('token_help', array('user'))`.

# Answer
> 0 votes
A couple of checks.

You do have a module name, your not just putting '\[mymodulename\]' in the code.

Is your module enabled?

Have you cleared the cache?

If all of the above is true then you can start to put debug code in to make sure the correct values are being pulled.

---
Tags: nodes, users, tokens
---


# Question
Title: drupal_render not working in views-exposed-form.tpl.php?
I put this in the template:

```
<?php print drupal_render($form['title']); ?>
<?php print drupal_render_children($form); ?>

```

Neither renders anything. If I dsm($form) the variable looks correctly populated.

Any ideas?

# Answer
Ok I noticed that #printed = TRUE on all my form elements, so they are not being printed. Going to make a new question for why they are set that way.
> 1 votes

# Answer
To find the title you need to look at how the Exposed form does it. First it loops through all the widgets in the form `<?php foreach ($widgets as $id => $widget): ?>` then it prints the label `<label for="<?php print $widget->id; ?>">`.

If you explicitly want the title of the view then you are going to have to use a form\_alter or a preprocess function to get it there.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: I was wondering how to make "custom fields" in Drupal 7?
I want to have a extra input field, called "URL" when adding content in drupal admin, and then print that out in the template if something was inserted there.

My guess is that custom module is needed, but that's how far I got, as I have no idea what hook I need to use and how. Or am I trying to solve this the wrong way?

# Answer
No custom module is needed for this in Drupal 7.

Go to Admin \> Structure \> Content Types, click on "Manage Fields" by the content type you want to add the field to (e.g. admin/structure/types/manage/page/fields), select a type (e.g. "Text"), give it a name, and you're done. (There are some field settings you can change, but you don't need to.)

If you want something that does validation on the URLs, I'd recommend installing the link module, then choosing "Link" as the field widget type in the instructions above.
> 3 votes

---
Tags: entities
---


# Question
Title: Allow a node to have many dates attached to it
I am stumped trying to figure out how to set up a node to have many dates attached to it without having to just add a lot of date fields to it.

The scenario is that we have a show, and that show occurs on multiple days at different or multiple times each day.

I'd like to be able to have a content type of 'Show' with *a* date field and then just add multiple dates to it. However, the Date field doesn't seem to support multiple values.

How do I make this work?

# Answer
*Just answering this myself so it doesn't count towards the unanswered total.*

Turns out the answer is relatively simple - as long as you don't choose a Widget for the Date field that handles repeating dates, the 'Number of Values' field appears and you can choose 'Unlimited'.

So choosing either of the following Widget types:

* Select List with Repeat options; or
* Text Field with Date Pop-up and Repeat options

will not allow you to have multiple values. Any other options should be OK.
> 4 votes

# Answer
Office hours is a module that can help you. It's built for entering complex opening hours for a physical place. It minded for a per week display, but it does support some custom entries, by entering week numbers but this is not well docented

I'm not sure how well it will work for your case, but it can at least give you a head start.
> 2 votes

---
Tags: nodes, entities, datetime
---


# Question
Title: Language selector for Apache Solr search form
How can I do something like this with Apache Solr in Drupal 7?

This will be the front page of my site, and depending on the language the user chooses, he will be redirected to the language-specific subdomain of my site with the respective search results:

* en.mysite.com/search/search=type+here&lang=en
* es.mysite.com/search/search=type+here&lang=es
* jp.mysite.com/search/search=type+here&lang=jp

Of course, only results with the user's language should be shown.

# Answer
> 3 votes
The Solr Multilingual module should do what you appear to want.

> ... provides a way to offer language-specific searches for different languages at once on multilingual websites ...

I'm using the not-yet-released 7x dev version with some success. A registered-user's primary language selection, or override from a drop-down in the site-wide menu sets a $var which I carry through to the Solr search module, language-specific content, and Drupal language overlays for standard markup, etc.

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


title: Adding custom code on flagging a node

text:
# Question
Title: Adding custom code on flagging a node
I am using the Flag module on my site. In which function should I add my custom code that is executed when users click on the flag button?

# Answer
> 3 votes
If you enable the Trigger and the Flag actions modules, you can assign a group of actions that is executed when a user or a node is flagged by a user.
Flag integrates also with Rules, and it allows to execute rules when a flag is used for users or nodes.

---
Tags: flags
---


title: Add field to login block in drupal 7

text:
# Question
Title: Add field to login block in drupal 7
I am trying to add a custom field to the user login block in drupa 7 for the zen theme. That is, in addition to the username and password fields, I need another field called code. Most of the available documentation on the net is targeted at drupal 6. From what I've read, the template.php file and the block--user--login.tpl.php files need to be modified for the particular theme. Is this right? Also, what functions need to be modified/added?

Any help appreciated.

# Answer
> 3 votes
Drupal forms don't reside in any particular template. They are defined in the code. When a form is displayed, the code is read, it is then made available for modification by other modules before being rendered by a function called drupal\_render() this will then use various template files to build the form which its displayed to the user.

It is fairly simple to add a field to the login form using hook\_form\_alter().

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form['myfield'] = array(
      '#type' => 'text',
      '#title' => t('code'),
    );
  }
}

```

What is perhaps more tricky is deciding what to do with this, are you using it for a second form of authentication?

A final note is on where to put the code. Drupal is fairly flexible, in that you can put theme files in modules and functionality in themes. However best practice is to keep features in modules, it leeds to a more manageable system in the long run.

---
Tags: theming, users
---


# Question
Title: Create an advanced search that searches only on a field with search_api in drupal 7
I've successfully installed the search api module in drupal 7. I installed solar and it works fine. I need to create a custom search form that has various fields and those fields performs search only on the relitive field.

This means that if i have a content type with the following fields:

"job requested"

"previous exerience"

"city"

I want a searchh page with the same fields and when the user enter a value in the "city" field, it searches for that data only in that field: if I search the "city" field for "milan" I want to find only nodes with the word "milan" entered in the field "city" and not with the word "milan" entered in the body.

I think I need separete indexes for each fields, but structure the two forms?

# Answer
You don't need separated indexes. In you callback handler, you need to build a new `SearchApiQueryInterface` instance and set conditions on the field using its `condition` method.

```
$index = search_api_index_load('custom_index_machine_name');
$query = $index->query(array(
  'language' => $GLOBALS['language']->language,
  'search id' => 'custom-search',
));
foreach($form_state['values']['filters'] as $field => $value) {
  if (!empty($value)) {
    $query->condition($field, $value);
  }
}
$result = $query->execute();

```
> 2 votes

---
Tags: search
---


# Question
Title: When can uid 1 get an access denied page?
I am having a very strange problem that I can't track down.

We have been working on a custom site for a client now for several months. Theme is a Zen subtheme.

I can't remember the last time I tried to access it, but I am getting an "access denied" when I try to view /admin/build/themes/settings/mysubtheme, even as uid 1. It is getting logged this way, too, so I think it really is an access denied. I can access this page for Zen, Rootcandy, and other enabled themes.

I have done all of the usual tricks for attempting to fix this (run cron, clear cache, rebuild node perms, assign all perms to my superuser role, etc) without luck.

A `theme-settings.php` exists for the theme and all of the hooks are named properly for the theme.

How is this possible since user\_access returns `TRUE` when `uid==1`?

Thanks.

# Answer
> 6 votes
After trying to fix this for an hour, I tumbled on the solution right after I posted this. Apparently, it is possible to set a theme as "default" but not have it "enabled", and have a site function normally. Enabling the theme fixes the problem.

---
Tags: 6, users, theming
---


title: Drupal pager, go to specific page

text:
# Question
Title: Drupal pager, go to specific page
I have a form in pager, so user can enter page he want's to view. But I can't figure out how to go to that page number in form submit.

# Answer
Most drupal pagers work by setting a `?page=XX` in the url. So a simple solution would be to set the url to mimic that, entering the number entered by the user in the url.

This might break if the pager argument in the url changes (like if you have multiple pagers on a single page etc), but this might cover your needs.
> 2 votes

---
Tags: forms, paging
---


title: Using t() with langcode in Drupal 7

text:
# Question
Title: Using t() with langcode in Drupal 7
I have a Drupal 7 setup with multiple languages (en and fr). In my template files I have a lot of t() texts which im translating using the i10n\_client module. This works perfect for translating texts from en to fr IF the t() texts are written in english. However, what if I want to write my t() texts in Danish and being able to translate them to both en and fr? Meaning that the Danish version never will show up as long my Drupal setup only have en and fr as languages.

I tried using the options parameter with the langcode like this:

```
print t('Min tekst', array(), array('langcode' => 'da'));

```

But the translate-text interface (provided by i10n\_client module) wont show up when I'm on the en site. Only on the fr site where I can translate it from en to fr.

Is this possible? And how?

# Answer
> 5 votes
The string (first parameter) always needs to be in English, from the Drupal 7 API:

> $string A string containing the English string to translate.

The langcode just means that the string will always be translated to Danish, no matter what the active language is. So if you'd be surfing the French site, you'd see the Danish string.

I'm afraid you'll have to translate your Danish strings back to English strings.

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


# Question
Title: Where is a resource for theming drupal 7 views?
I needed to theme a view in drupal 7 for example the slider in this site: http://fourkitchens.com/

What file must i create to costumize a view slider and the relative button? In drupal 6 there were theme information and i could create a new "view-example.tpl.php" and costumize it very well but in drupal 7 ? Thank you you are great,Drupal Answers!!

# Answer
Views for Drupal 7 also provide theme information. See the advance section or follow the URL (in my case) `example.com/admin/structure/views/nojs/display/[my_view]/[type]/analyze-theme`
> 2 votes

# Answer
You can check out the skinr project. It'll allow you to skin views. I would be very careful though as the D7 version of skinr is still very experimental as stated on the release notes page.

Drupalcon 2010 session on skinr: http://www.archive.org/details/ThemingWithSkinr
> 1 votes

---
Tags: theming
---


# Question
Title: Drupal 6: Having a menu where more than one Item is active
I'm trying to build a menu where a node can be a child of more than one item. That's not really an issue because Drupal 6 can handle it. However only one parent menu item will be active.

It's some sort of a portfolio where a client-node can be a child of photography and design and when the page of the node is opened the entry for photography and for design should be active.

Does anyone have an idea?

# Answer
Drupal has built in the assumption that only only one item in a single menu can be active.

You hack the core menu system or create your own, but both would not be recommended.

The best workaround I can think of, is to expend the menu and use css and JavaSript to show/hide the menus and mark them as active. This could be doable but might be quite hard if you have a complex menu structure.
> 1 votes

---
Tags: routes
---


title: Views not updating?

text:
# Question
Title: Views not updating?
Using d7.4 - I have views within some quicktabs that will not update. It only shows the results for everything created BEFORE the view was created- but not after. The views are for 'most recent, most comments, most viewed, most votes'. The views wont display any content created after the views were created. I have cleared all caches and turned them off- both in the performance config and the views caching set to NONE. Quicktabs are not the problem as the views don't update in the Views preview display (without quicktabs). Any ideas as to what I'm missing here?

# Answer
Check the filters?

Here I found this, but no solution: http://drupal.org/node/1193616

I think the best would be filling an issue http://drupal.org/project/issues/views
> 2 votes

---
Tags: 7, views
---


# Question
Title: WYSIWYG not appearing for custom content type
I am working on a re-work of Drupalerp (D6), as I found so many problems with it...but have run into an odd issue. As drupalerp creates it's extra content types programatically, I am unsure if it is doing it correctly. For content types created in the GUI, the Drupal way, I can get the Wysiwyg to appear.

In the node\_type table the drupal nodes that work have 'node' in the module column, and has\_body = 1. The erp ones have their individual module names instead of 'node'. If I switch the module to node for those ones, I get wysiwyg, but of course lose the custom programmed handling of those types.

So my question is, does that have to be 'node' in the module column of node\_type in order to get wysiwyg, or is there another element missing from the programming of those custom types?

# Answer
Using the CKeditor module, you can apply the editor to any textarea on the site. However, it doesn't apply this by default. You have to set up the settings to either appear on ALL textareas or selected ones only.

Underneath every textarea, it gives you an element ID which you can use to isolate specific ones and get the editor to appear.

Assuming you're using CKeditor of course. :o)
> 0 votes

# Answer
I know that wysiwyg is related to input filters, are these available on the body (if there is one) of the custom nodes?
> 0 votes

---
Tags: 6, nodes
---


# Question
Title: Validation error, please try again. If this error persists, please contact the site administrator
I've been searching google and I'm about to start surfing through the code, but we all know how useless searching through drupal code is.

People are running into this problem everywhere, including on my website today. So I figured it was worthy of stackexchange.

Basically, I run into this error when trying to send the contact form from my website. Others have run into it with a variety of forms.

I want to know what we're running into that is causing this error.

# Answer
The form token associated to forms created with the form API is a value that is used to verify the data are submitted from a user who filled a module form, and not forged data.

The drupal\_valid\_token() function that validates the token is validating it using the user session; this means that, if the user session used when the data are being submitted is different from the session used when the form was created, the validation of the token fails. This could happen also when a module calls session\_destroy().
> 1 votes

---
Tags: 6
---


# Question
Title: get rid of dropdown list on views exposed filter
I created a view with an exposed filter, that I set to autosubmitt. So when I start typing in the filter field, the list of items does get filtered live. So far I'm happy.

What I don't like is the dropdown list that also gets updated while typing. How can I tell this field to stop showing a dropdown list at all?

# Answer
> 1 votes
the 2 general options in the view are autocomplete and dropdown. the autocomplete will give you a list of matching queries as you type. keep in mind that if you remove that and somebody spells something incorrectly they will not get any results from the exposed filter.

if you have to get rid of the dropdown feature, use CSS to hide it.

---
Tags: 7, views, navigation
---


# Question
Title: Alternate solution to avoid handling a huge number of menu items
I am on Drupal 7 and I am facing a dilemma with a project I am building. It will be a content-rich website, which means lots, lots, tons of articles. When user enters an article page, I want him to see the website area (menu item) it is associated with selected on top of the page. Drupal will handle it if the content is associated with the correct menu during node creation.

My concern is that I will have a huge menu page. When I have 1,000 articles or so, the menu admin page will be a terribly long list of articles associated with the top menus. I would rather have only the top two levels in my menu structure but I still need the subpages (articles) to be shown as associated with a menu item.

The question is: is it possible to associate a content type with a menu item so that it isn't actually in the menu, but it can interfere with the menu rendering so as to add ACTIVE or ACTIVE-TRAIL classes to the desired menu items? Do I have to play with template.php in order to achieve that?

Also, if you think that associating these many articles with a regular menu item is the correct approach and that there is no problem to end up with a monstrous menu list, please, tell me.

I am sorry if the question isn't enough clear, I will try to clarify further if necessary.

# Answer
> 1 votes
Context will handle it, but needs some template.php additions.

and it looks like Menu Position will too.

# Answer
> 0 votes
Menu Trails allows to set the active menu trail per content type.

I *think* Context allows to do this too, but I'm not 100% sure. Especially if you are using Context anyway, then that might be a better option.

---
Tags: nodes, routes
---


# Question
Title: how do I get my module to install a view?
I have developed a module in a dev environment. I built a view for it using the UI. I've exported the view, but I don't know where to put it so that an installation of the module in a fresh environment will also create the view.

How do I do this properly?

Bonus: how do I have the module uninstall the view on `hook_uninstall`?

# Answer
> 10 votes
Create the MODULENAME.views\_default.inc file (replace MODULENAME with the name of your module), and copy the exported code in the implementation of `hook_views_default_views()` you write in that file.

For example, the Views module implements `node_views_default_views()` for the Node module. The relevant parts for the front page view are the following ones.

```
  $views = array();

  // Omissis

  $view = new view;
  $view->name = 'frontpage';
  $view->description = 'Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Front page';
  $view->core = 0;
  $view->api_version = '3.0';
  $view->disabled = TRUE; /* Edit this to true to make a default view disabled initially */

  // Omissis

  $views['frontpage'] = $view;

```

The hook then returns the content of `$views`.

If the view has not been overwritten by a user, it should not be shown in the view list, once the module implementing the hook is uninstalled.

---
Tags: views, importing-exporting, installation
---


# Question
Title: Allow users to set permissions for profile fields
I would like users to be able to determine whether a field is displayed publicly. For example, their real name is required for the site, but I don't want to force users to display it.

# Answer
Without information on what version of Drupal you are using or what you are using for profiles, here is a suggestion for each type of profile on Drupal 6:

Using the core profile module, check out Profile Privacy

Using Content Profile, take a look at CCK Privacy
> 1 votes

---
Tags: users
---


title: XML-RPC Custom Hooks Request

text:
# Question
Title: XML-RPC Custom Hooks Request
I have developed my own xmlrpc hook, which have certain functions.

Basically I need to call that functions outside Drupal. So I can't use xmlrpc() function.

What is most simple method to call that functions through Drupal's xmlrpc.php?

# Answer
PHP has an extension for XML-RPC, but it's not enabled by default. If your PHP installation doesn't have the extension, you can use one of the PHP libraries that handle XML-RPC requests, such as XML-RPC for PHP, and The Incutio XML-RPC Library for PHP; if you have downloaded the Zend Framework, you can use its XML-RPC classes.
> 1 votes

# Answer
Without having more information (see my comment), the only advice I can give you is: Use an XML-RPC library for your language/plattform. Whatever language you are using, it is very likely that a library (or many) exists for it.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: IMCE module button not showing for Editor role?
I have given the Editor role literally every single permission, yet the button still only shows for admins. Am I missing a setting somewhere?

# Answer
I was indeed missing a setting somewhere. You have to assign a user profile to the role before they see the button in site configuration -\> IMCE.
> 1 votes

---
Tags: 6, users, files
---


title: Add translatable text in template file

text:
# Question
Title: Add translatable text in template file
I am going to add a custom string by **t**() function in node.tpl.php. However, where should I add the translated string for the original string?

# Answer
You can go to admin/build/translate and translate your defined words, it's search is case sensitive
> 2 votes

---
Tags: i18n-l10n
---


title: Can I change pager.inc theme?

text:
# Question
Title: Can I change pager.inc theme?
can I theme output of includes/pager.inc using drupal template system?

I want invert page links, I don't want any edit on pager.inc or CSS.

maybe invert items passed to theme\_pager function

# Answer
Not sure what you are asking here, you can override theme\_pager() like any other theme function in Drupal. It is however quite a bit of code.

It's also relying on global functions, so you probably can't simply call the original fuction with reverted arguments.
> 0 votes

---
Tags: 6, paging
---


# Question
Title: Importing products via Feeds csv import is generating error: "General error: 1366 Incorrect string value:"
I'm trying to import products using the import via csv functionality within feeds and am getting the following errors:

```
SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB7 The ...' for column 'field_description_value' at row 1
Error message SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB7 The ...' for column 'message' at row 1

```

I also have the commerce-feeds module installed.

There is quite a lot of stuff on this on drupal.org, but it all seems to be contradictory and I am more than a little lost. I am a non-coder and a relatively inexperienced configurator at best.

My csv is definitely encoded UTF-8. I have opened it in Notepad++ and converted it to UTF-8.

I found this post on stack overflow utf-8 database problem The line "It seems your connection is not set to UTF8 but some other 8 bit encoding like ISO Latin" seems to indicate to me that there may be a bug in the Feeds or Commerce Feeds modules in that the database connection cannot cope with csv input files encoded UTF-8. Could that be correct?

I'd really appreciate some sage advice on this. I am completely stuck.

# Answer
Maybe the csv is encoded in UTF8, but everything else needs to be UTF8: UTF8 all the way through

I don't know exactly in what step is failing, did you check the databases and tables collation?
Drupal has by default the "SET NAMES="utf8", http://drupal.org/node/310447

Hopefully the Feeds maintainers have a look to your case here. http://drupal.org/node/1140194 , it seems you are not alone.
> 1 votes

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


# Question
Title: Custom module integration with Views3 for D7?
I have a custom module named ta\_module which alters the user registration form. But since I updated Views to version **7.x-3.0 - rc1**, I have like a hundred errors barely the same as the following :

`Warning: include_once(/{PRIVATE - DRUPAL ROOT FOLDER}/sites/all/modules/ta_module/views/theme/theme.inc) [function.include-once]: failed to open stream: No such file or directory in _theme_process_registry() (line 413 of /{PRIVATE - DRUPAL ROOT FOLDER}/includes/theme.inc).`

`Warning: include_once() [function.include]: Failed opening '/{PRIVATE - DRUPAL ROOT FOLDER}/sites/all/modules/ta_module/views/theme/theme.inc' for inclusion (include_path='.:/usr/local/lib/php') in _theme_process_registry() (line 413 of /{PRIVATE - DRUPAL ROOT FOLDER}/includes/theme.inc).`

It seems like I need to create a /views/theme/theme.inc in my custom module folder. BUT TWO QUESTIONS REMAIN :

**\- Do I leave this file blank or am I supposed to put things in it ?**

**\- Do I have to create other folders/files for Views not to interfere with my module ?**

Thks for reading ! ;)

# Answer
Have you tried clearing the cache?

The error is there because some module, expects that there is such a file and tries to include it. It could be a direct result of whatever views integration you are doing.

The error will go away if the file exists, an empty file with `<?php` is enough.
> 1 votes

---
Tags: views, 7
---


# Question
Title: I get a syntax error when I try to execute a query
Each time I run the following code, I get an error.

```
$result = db_query(“SELECT nid FROM 'msg'”);
foreach ($result as $record) {
  // Do something with each $record
}

```

The error is the following one:

> Parse error: syntax error, unexpected T\_STRING

How do I fix the error?

# Answer
You should do

```
$result = db_query("SELECT id FROM {mg}");

```

It doesn't look like you should get parse error unless you really use `“”` and not `""`
> 1 votes

# Answer
I copied the following code in a text file named "test.php."

```
<?php
  $result = db_query(“SELECT nid FROM 'node'”);
  foreach ($result as $record) {
   dsm($record->nid);
  }

```

When I executed "php -l test.php," I got the following error message:

> PHP Parse error: syntax error, unexpected T\_STRING in test.php on line 2

I then changed the code to the following one, and "php -l test.php" didn't report any syntax error.

```
<?php
  $result = db_query("SELECT nid FROM 'node'");
  foreach ($result as $record) {
   dsm($record->nid);
  }

```

The problem is then the fact you are using  as string delimiter.

The query you are using is not correct in Drupal, where the table name is surrounded with curly brackets, not string delimiters.

The code should be written as the following one:

```
<?php
  $result = db_query("SELECT nid FROM {node}");
  foreach ($result as $record) {
   dsm($record->nid);
  }

```

The database API functions will replace the curly brackets with the string set as table prefix in settings.php.
> 1 votes

---
Tags: database
---


# Question
Title: Make a copy of the live site for localhost testing
I'd like to copy my live site so I can run it on localhost and test some modules before installing them on the livesite.

Is there a step-by-step way to do this? I have access to PHPyAdmin, so I can easily export the database. I know there's more to it than just exporting, thought.

# Answer
> 3 votes
You can easily do this with the backup and migrate module. If you have lots of dynamic content you should be using this module to schedule a backup on cron jobs too.

Before I learned how to use the MySQL command line, because phpmyadmin has an import file size limit, I would compress a whole website with the backups in a private file path and move it to a new server. Then I just remove the database settings and install a new installation of Drupal. After I will enable the backup and migrate module and restore that last database.

# Answer
> 2 votes
If you're ever so inclined you could also use drush to sync and deploy websites.

If you're not familiar with drush (*drupal shell*) it's a command line that provides a plethora of functionality via the command line.

More specifically related to your question, check out this drupal node on sync'ing.

Drush even has a built in command for exporting databases:

`drush sql-dump {database name} >> {path}`

For a full list of commands checkout the drush website.

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


# Question
Title: Add administration menu item for one role only
I have a module that has configuration pages in the administration side. I want to have one role that's just for administrating that module, but doesn't have any other administrative privileges.

I can give this role access to the path `admin/settings/module/configuration` and they see the form, but since they can't see see the administration menu, they can't navigate to it. They have to paste the URL to it.

I would like to have that path show up as a link in their black admin menu bar at the top. But I don't want it to show up for any other admin, just the Module Administrator role, to keep that bar uncluttered. I can get a custom menu item showing up in the admin bar, but how do I get it to redirect to another page, and how to I stop users without the role from seeing it?

# Answer
> 2 votes
> I can get a custom menu item showing up in the admin bar, but how do I get it to redirect to another page, and how to I stop users without the role from seeing it?

You can set the page callback to `drupal_goto`, pass the redirect path and other arguments as `page arguments`, and use the `access arguments` to set permissions.

I love admin menu, but I'm not sure it's something I particularly like putting in the hands of the clients. It's easy to find yourself giving too many perms to the client, and you can't use the menu module to add items to it. I've not used it yet, but on my next project I'm going to try something like SimpleMenu.

---
Tags: 6, routes, users
---


# Question
Title: How do you allow a user to set the audience of a node to any Organic Group without giving them the "administer nodes" permission?
I have a group of users that I need to be able to set the audience of story nodes to any of the Organic Groups within our systems. Is there a way to do this without giving them the "administer nodes" permission.

I am currently assuming this isn't possible with my current set-up but was hoping there is a module out there that would allow it.

If there isn't a module where would I begin to look at creating a module that created this permission? What Drupal API hooks would I begin with?

# Answer
> 1 votes
I created a patch to the Organic Groups module to add the "administer audience" permission. The patch can be found here, http://drupal.org/node/1211974

Here's the patch inline,

```
diff --git og.module og.module
index 38cc452..0206115 100644
--- og.module
+++ og.module
@@ -558,7 +558,7 @@
  * Implementation of hook_perm().
  */
 function og_perm() {
-  return array('administer organic groups');
+  return array('administer organic groups', 'administer audience');
 }

 /**
@@ -1833,7 +1833,7 @@
   }

   $node = $form['#node'];
-  $required = variable_get('og_audience_required', 0) && !user_access('administer nodes');
+  $required = variable_get('og_audience_required', 0) && !user_access('administer nodes') && !user_access('administer audience');
   $is_optgroup = FALSE;

   // Determine the list of groups that are shown.
@@ -1843,7 +1843,7 @@
   foreach ($subs as $key => $val) {
     $options[$key] = $val['title'];
   }
-  if (user_access('administer nodes')) {
+  if (user_access('administer nodes') || user_access('administer audience')) {
     // Node admins see all of groups.
     $all = og_all_groups_options();
     $other = array_diff_assoc($all, $options);
@@ -1900,7 +1900,7 @@
   elseif (!empty($gids)) {
    // populate field from the querystring if sent
    $groups = $gids;
-   if (!user_access('administer nodes') && $simple) {
+   if ((!user_access('administer nodes') && !user_access('administer audience')) && $simple) {
      // filter out any groups where author is not a member. we cannot rely on fapi to do this when in simple mode.
      $groups = array_intersect($gids, array_keys($options));
    }
@@ -1949,7 +1949,7 @@
     // show multi-select. if less than 20 choices, use checkboxes.
     $type = $cnt >= 20 || $is_optgroup ? 'select' : 'checkboxes';
     $max_groups = variable_get('og_max_groups_'.$node->type,'');
-    $description_max_groups = ($max_groups && !user_access('administer nodes')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
+    $description_max_groups = ($max_groups && !user_access('administer nodes') && !user_access('administer audience')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
     $form['og_nodeapi']['visible']['og_groups'] = array(
       '#type' => $type,
       '#title' => t('Audience'),

```

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


# Question
Title: SFTP Can't upload module despite using owner's credentials
I'm new to both Linux and Drupal, but I can see that the owner and group assigned to the drupal modules directory is one of my SU accounts on the server. When I log on to SFTP I use that same credential.

I tried to upload a module using Aptana studio and it tells me it can't create folders.

Do you feel that there's additional ownership info needed on the server side? Would my folder rights not be applicable when connecting via SFTP?

# Answer
> 2 votes
Using `ssh` you can log in to the system to check about directory permissions using the same credentials you use with `sftp`.

try..

```
ssh user@host

```

to login and then use a number of commands to check permissions

```
ls -l                      //Lists files with permissions for user, group and other
chmod 755 dir/file         //Change file/directory permission
chown user:group dir/file  //Change the user/group ownership of file(s)

```

`scp` command can also upload file from local (\*nix) machine to server.

```
scp path/to/local/file user@host:/path/on/server

```

---
Tags: 7, files
---


# Question
Title: Drupal 6: Allow external site to authenticate via Drupal
How would I allow a simple PHP site, which already has a user db, to let Drupal handle the logging in of users? I guess I could use services (but I would need help on this) or alternatively is there some way that users are passed to the Drupal login form to log in, but the simple external PHP site knows, through some kind of cookie arrangement, that the user is logged in?

The main priorities are that the user should only have to log in once for both sites, and the existing users on the external site can be maintained and transitioned smoothly. I want Drupal as the main user db because it's more secure and I think it's easier to have the external authenticate off Drupal rather than the other way around.

Any thoughts?

# Answer
If you have access to the same cookies as the Drupal site, you can pull the session ID out of the SESS\* cookie. Then check the sessions drupal table for the uid.

The session cookie name is a little more challenging to predict as it is "SESS"+ an md5 hash of the session name from the host domain URL or cookie\_domain setting in settings.php file. Given your full control over the site, it shouldn't be hard to work with that though.
> 3 votes

---
Tags: users
---


# Question
Title: Approach of building a website for local basketball league?
I am asked to build a local basketball league website.

Functionality is quite simple:

* League news/articles
* Different team page with team news, player info, gallery
* Each player has profile. such as name, height, position, photo.

Module OG seems to be a good match in this case, but I am wondering if it can be done **without OG**.

Are there any other easier approaches?

Thanks for any suggestions!

# Answer
> 1 votes
I see you tag this as Drupal 7. You don't need OG unless you want to have groups where members of the group can chat with one another.

Content Types: League, team, news/articles (maybe Players) Modules: Image field, Viewes.

* News & Articles are self explanatory.
* Create node reference fields for Teams & Players
* Teams would node reference league, players would node reference a team.
* You may only have 1 league or multiple.
* Add fields to players (name, height, position, photo)
* May want to use image style to set defaults size for photos
* Depending on your use, Players can be users or a content type
* Then you will use views to display everything the way you want, such as, team gallery, teams in league, etc.

Also you may want to embed a view into a node. Use embed\_views module

---
Tags: 7
---


# Question
Title: Alternative admin-side content browsing - module?
Does anyone know of, or is working on a Drupal 7 module which would provide alternative, hierarchical content browser on the admin side?

While the filter in the Find Content section is a great aid for unrelated pages, I'd really love to be able to browse through taxonomy-bound PAGES (rather than terms), just like I browse through folders and files in Windows Explorer or Mac's Finder.

What bites me most is that in default Drupal installation, the taxonomies are too much separated (in terms of managing and reviewing the content) from the actual pages. And the pages bound to vocabulary terms are browsable as unrelated ones.

I would be curious to see if anyone found a solution for that. Regards,

Artur

# Answer
I'm not sure if I understand what you're looking for in the admin pages, but I do know that Views is a great tool to build custom admin pages, especially when combined with Views Bulk Operations.
> 1 votes

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


# Question
Title: How to costumize the input fields but only in the page /user?
I want to create a particular style with css for input style in the field of login, register and request new password. The css if i see it width firebug is only one and i must adding a type only for the form of the /user page, but not for all page that containes form. Thank you for help!

# Answer
Check out the classes added to the opening body tag in the HTML. It will help you narrow down styles to just that page.

I know one of my D6 sites, there is a class in the body tag 'page-user' so you can use some CSS such as...

```
body.page-user .form-text {
  /* Add styling */
}

```

Inspect the HTML and style as necessary. :o)
> 2 votes

---
Tags: 7, theming
---


# Question
Title: Re-creating complex CSS footer layout in Drupal
I've been given some HTML & CSS files by our university web designer and need to replicate essentially the same layout into the library website I'm creating in Drupal. The footer (pleased see attached link) has been the biggest hurdle so far. With this type of column-based inline layout consisting of menus (which I haven't created as menus yet), should I be creating new regions in my .info file to handle each menu? Also with the university address info. and icons, should this be another region or should I add custom variables and HTML so it is just part of the main footer region? Or is there a way using Blocks, Panels or another module to create this layout more efficiently?

One last thing-as you can see the columns have three headings (Who Are You?, Quicklinks, and Admissions) so I plan to create a menu with each name as title. What's the best strategy to deal with the overflow of menu items over more than one column without having to create six separate inline regions for layout purposes?

Thanks for any assistance, guidance, or suggestions. This site has been an invaluable resource in learning Drupal over the past few months and I've learned a lot from all your posts, responses & comments to each other.

**The footer design:** footer http://dl.dropbox.com/u/664958/footer.png

# Answer
> 4 votes
I'd set up one region for those menus, in that region have 3 x menu blocks (http://drupal.org/project/menu\_block), 1) Who Are You, 2) Quicklinks 3) Admissions.

CSS will be your friend to get the required layouts.

The "Who Are You" menu should be easy, float the menu block left and fix the width. The same for the "Admissions" menu.

The middle menu will be similar but all you need to do is have a wider fixed width menu block, fix the width of the menu items and float them left. Then you'll have to order the menu items to make them appear in the correct columns.

The text below the menus should simply be 2-3 more standard text blocks just styled appropriately.

I hope this makes sense. I'll be interested to see how other developers would attack this.

Cheers.

# Answer
> 0 votes
The Skinr module can help with this kind of thing: http://fusiondrupalthemes.com/support/documentation/layout/adding-menu-your-sites-footer

If you are using Drupal 6, I would try it out. It is not quite ready for 7, but it is probably worth looking at anyway. There are a lot of other things that it can make easier, and many base themes have some built in support for it.

---
Tags: theming
---


# Question
Title: How to remove comma between taxonomy terms?
I style my taxonomy terms as boxes, so I don't need comma between them.

Could somebody give me any advice?

# Answer
Here's a nice blog post on styling taxonomy in node.tpl.php (or node-contenttype.tpl.php): http://oliverdavies.co.uk/blog/how-style-drupal-6s-taxonomy-lists-php-css-and-jquery

Looks like you should check your node.tpl.php for something like `<?php if ($terms): ?>` and then you might see where the commas are being added and strip them out. This will depend on what theme you are using.
> 1 votes

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


title: How to add script to <head>?

text:
# Question
Title: How to add script to <head>?
I want to add a call for 2 external scripts in the page.tpl.php.

The scripts are:

```
 <script type="text/javascript" src="http://use.typekit.com/12345.js"></script>
 <script type="text/javascript">try{Typekit.load();}catch(e){}</script>

```

Now in D7 you can call them directly from page.tpl.php like

```
drupal_add_js()

```

right?

But I'm working on a D6 site right now.

So within mytheme directory I add to my template.php file

```
function mytheme_preprocess_page(&$vars, $hook) {
    drupal_set_html_head('<script type="text/javascript" src="http://use.typekit.com/12345.js"></script>');
    $vars['head'] = drupal_get_html_head();
  }

```

It doesn't work. The page no longer loads.

So the question is, How do I get both those scripts in the head? What should the code look like? I know the real answer is learn php, but in the meantime

# Answer
> 5 votes
You should concatenate `$vars['head']` no replacing it: Your code should be:

```
function mytheme_preprocess_page(&$vars, $hook) {
    drupal_set_html_head('<script type="text/javascript" src="http://use.typekit.com/12345.js"></script>');
    $vars['head'] .= drupal_get_html_head();
}

```

Notice the `.=` after `$vars['head']`.

---
Tags: 6, javascript, theming
---


# Question
Title: Add Additional Submission Processing To "Create Node" forms
Which hooks can I implement in Drupal 7 to add additional processing steps to the node creation process. For example, to run a snippet of PHP code after the node has been successfully saved to the database. I'm assuming hook\_form\_alter, but I only want to add to the process, not replace the default node save process.

Specifically, I'm looking to make an immediate external API call to SmugMug.com and then trigger an email upon a successful node save.

# Answer
> 2 votes
In Drupal 6, this was done in hook\_nodeapi.

In Drupal 7, this is done in hook\_node\_update & hook\_node\_insert

hook\_node\_update($node) This hook is invoked from node\_save() after the node is updated in the node table in the database, after the type-specific hook\_update() is invoked, and after field\_attach\_update() is called.

hook\_node\_insert($node) This hook is invoked from node\_save() after the node is inserted into the node table in the database, after the type-specific hook\_insert() is invoked, and after field\_attach\_insert() is called.

there is also hook\_node\_presave($node) if you want to do something before its been save

More information on api.drupal.org & link to the D6 to D7 upgrade changes

---
Tags: 7, forms
---


title: Custom List of all items in Webform

text:
# Question
Title: Custom List of all items in Webform
After 10 webforms have been added. How could we creat a HTML report to list all items inside drupal ?

# Answer
> 1 votes
Yeah, it sounds like you need to create a view to output submissions.

Webform helps you here by integrating fully with views so you can pull out whatever data you need. You can also create a view per webform which will enable you to have a separate page for each.

Failing that, if you go to Content Management \> Webforms it gives you a summary of all webforms on the site with links to view submissions, export them, etc.

Hope this helps.

# Answer
> 0 votes
Perhaps the Site Documentation module is close to what you are looking for.

---
Tags: webforms
---


title: Ajax on textfield keeps me from typing

text:
# Question
Title: Ajax on textfield keeps me from typing
I have the ajax property set on a form element. Its like an autocomplete except it displays the results in a div. It works great except the textfield gets greyed out by drupal during the ajax call. I end up having to type one character at a time between ajax calls. Is there a way to fix this?

Here's the code for my element:

```
$form['auto_complete'] = array(
  '#title' => 'Auto Complete',
  '#type' => 'textfield',
    '#ajax' => array(
      'callback' => 'k_test_ajax',
      'wrapper' => 'searchresults',
      'method' => 'html',
      'event' => 'keyup',
    ),
 );

```

# Answer
> 1 votes
Your best bet is to either

* use the `#autocomplete_path` and tweak the behavior by overriding the JavaScript (prototyping)
* Don't use the ajax framework, but create this with custom JavaScript.

The AJAX framework can do a lot of things for you, and works very great for most things, but there are some cases like this one, where it doesn't work as intended. The problem is that you will get too many ajax requests at once if you do one for every `keyup` event, which most likely will mess things up if you could actually do it. This is why you need an autocomplete functionality which usually caches the results for improved performance.

---
Tags: 7, ajax
---


# Question
Title: Path (URL) to call custom module function
I am developing a custom module and I need an URL that would trigger an action when called.

The purpose is for an external server to call this address passing some variables through `$_REQUEST['message']`, and then return a STRING with the success/error string. So the URL in question is only supposed to be called by a machine.

I now have a PHP file in the root that does the job, but I'd like to integrate it to the Drupal way through this custom module.... Is there a way to do this?

Thank you

# Answer
> 8 votes
The best way to do this is to build a custom module and implement the hook hook\_menu().

You'll need to implement:

* a .info file with metadata about your module
* a .module file containing hook\_menu() and your callback

foo.module should look like this:

```
function foo_menu() {
  $items = array();
  $items['foo/myurl'] = array( // change 'foo/myurl' to the url you want
    'title' => 'Callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function custom_callback () {
  // Parse $_REQUEST parameters
  return 'success';
}

```

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


title: Block: DRUPAL_NO_CACHE not working

text:
# Question
Title: Block: DRUPAL_NO_CACHE not working
I have a block that displays an item fetched from the database at random. The block has DRUPAL\_NO\_CACHE as cache parameter. However, when visiting the page as anonymous user with the cache on, the item never changes.

Some code:

```
function foo_block_info() {
  $blocks = array();

  $blocks['foo'] = array(
    'info' => t('Foo'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function foo_block_view($delta = '') {
  if ($delta == 'foo') {
    $block = array(
      'content' => theme(
        'foo_block',
          array(
            'item' => entity_get_controller('foo')->get_random_foo(),
          )
        ),
    );
    return $block;
  }
}

function foo_theme($existing, $type, $theme, $path) {
  return array(
    'foo_block' => array(
      'template' => 'foo-block',
      'arguments' => array(
        'item' => NULL,
      ),
    ),
  );
}

```

I suspect it's a Drupal Core bug, I've checked the forums but can't really find a solution for Drupal 7.

I know I could insert the item in the DOM with AJAX, but that's a last resort.

# Answer
> 5 votes
If you are caching the whole page (which is off by default in D7) then BLOCK\_NO\_CACHE will not make a difference on a block. Because while the block is not cached, the page is.

I think what you may want is the esi api module it allows you to use ajax to render the blocks.

---
Tags: 7, blocks, caching
---


# Question
Title: Accessing $language inside node content in drupal 7
Normally I would use $language to get the active language on my drupal 7 page. Now I'm doing some changes to a node content (set to PHP code) and I can't seem to get any variables working? I badly need to get the active language inside the node content - how?

# Answer
> 10 votes
If I understand your question:

```
global $language_content;

```

This will return a language object with the current language.

# Answer
> 3 votes
It also works within a block. I created a PHP block where I wanted to customize a link with the language variable, and placed this code inside:

```
<?php global $language_content; print $language_content->language; ?>

```

Thank you for sharing!

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


# Question
Title: is $node always available in page.tpl.php
I'm periodically getting an error about $node being undefined in one of my template files.I have a simple if condition that checks the node type being displayed. I assumed $node is always available, or am I wrong?

# Answer
> 12 votes
$node isn't necessarily defined, from the page.tpl.php Drupal 7 API:

> $node: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

# Answer
> 8 votes
By default, only on node pages is the $node variable defined. For the front page (a feed), view pages, comment, etc, they are not.

If you want a $node variable defined on a page that it is not a node, then you will have to edit/create the MYTHEME\_preprocess\_page(&$variables) function in your theme template.php file.

To avoid your error, in your template file wrap the $node variable in an

```
if (isset($node)) {
  // do something with $node
}

```

Or remove it completely

---
Tags: 7, theming
---


title: Etiquette for module feature requests

text:
# Question
Title: Etiquette for module feature requests
I am relatively new to Drupal, and I am thinking of posting a feature request on Drupal.org for one of the Drupal modules that I'm using. Before I do it, I wonder if there is any convention or etiquette that I should know about.

What is the convention for asking a feature request to the module developer? Is it bad to ask for the feature if it's a small thing that I might be able to write myself after some tinkering?

# Answer
If you have the ability to write the patch, even if it's not "right", it can often encourage the developer to jump in and help. If you're not as comfortable writing the patch, you can also explicitly offer to test it.

Overall, just be polite, and be prepared to be patient. We're almost all volunteers!
> 7 votes

# Answer
Number 1 is to make sure that it hasn't been asked for before. Duplicate issues are very annoying as a module maintainer.

The second thing is that you should provide as much information as possible. As to why the feature is needed and how it will benefit the module.

Also remember that just because you need it it may not be a good fit for the module, if it is something very specific for your needs the maintainer is unlikely to spend time on it.

As Tim said providing patches is very helpful. It also shows that you have put time and effort into the request.
> 6 votes

# Answer
The issue system does have categories for "feature request" and "support request".

For larger things, I would poke around and see if anyone else has made a similar request. Check the issue queue and the official group, if there is one.

For smaller things that you can take care of, I would submit a "feature request" and attach a patch.
> 2 votes

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


# Question
Title: How do I add dropdowns in Filter Criteria in Views module?
I was at a local Drupal group meetup last week where a member ran through a presentation of the Views module. I was really excited when I saw that he was able to add dropdowns to the Filter Criteria that he was using as I need exactly that functionality for something that I am building.

The thing is: I can't find the settings at all in my build. I remember that there was a 'settings' link at the bottom of his Filter Criteria area, but I have nothing like that.

Could anyone explain where I can find this? Am I missing and additional module?

# Answer
> 10 votes
The filters in views and how they are exposed to the user reacts a bit differently depending on the type of filter that is used. The type of filter that used, is controlled by defining the data to views using `hook_views_data` and `hook_views_data_alter`. This is a bit code heave and not always something you need to do your self as many modules including views does a lot of this for you.

Two common filters used is

* `views_handler_filter_in_operator`
* `views_handler_filter_string`

The two are are fundamentally different because their assumptions and requirements are very different.

The first one, is the one that you would like to use. It's used when you store a value that has a defined list of possible values. An example could be content types which is the example that @Danielle used in her post. Since nodes can't have any random value for their content type, it's possible for views to display a list of checkboxes in the Admin interface when using this filter and a select list / multiple select list for the user when it is exposed.

The second one is used when a string is stored in the database. Using nodes as an example, the title field would be a good candidate for such a filter. Since titles can be any text, it doesn't make sense to expose title selection of a node as checkboxes or select lists, instead you get some other options like you are seeing in your view. You can filter by if the string contains a word (beginning /end / somewhere), it's length etc.

If the one that did the views integration didn't bother using the `in_operator` type of filter, and describe to views (by using a php function) which options are available, you will have to do it using hook\_views\_data\_alter.

What you need to do is:

1. Create a subclass of `views_handler_filter_in_operator`
2. Implement `get_value_options`
3. Tell views about your new handler.

In code it would look like this

```
/**
 * Define my custom in_opeator
 */
class my_custom_in_operator extends views_handler_filter_in_operator {
  // overwrite the get_value_options function.
  function get_value_options() {
    if (isset($this->value_options)) {
      return;
    }
    $this->value_options array('option_1' => t('Option 1'), 'option_2' => t('Option 2'));
  }
}

/**
 * Implements hook_views_data_alter().
 */
function my_custom_views_data_alter(&$data) {
  $data['entity_type']['property']['filter']['handler'] = 'my_custom_in_operator';
}

```

And you're done. In reality it's actually quite simple. But finding out how to do is not as views is quite complex.

# Answer
> 5 votes
Are you allowing multiple values in your exposed filter? If so, the selections will appear in a select box with a scroll bar by default. If you force single selection only, your exposed filter will appear in a drop-down by default. I hope this helps!

---
Tags: 7, views
---


# Question
Title: How to onclick-trigger a non-native jQuery plugin's action?
I've installed a 3rd-party jQuery plugin (it's an accordion). It displays on my page, and works as expected.

I want to trigger one of the plugin's actions (open a particular slide) when I click on an image on my page.

I can't seem to get the code &/or syntax for doing that right.

The plugin I've installed is "EasyAccordion" (http://www.madeincima.eu/blog/jquery-plugin-easy-accordion/). It's .js source is posted here: http://pastebin.com/55JB4pr2.

I'm using the plugin on a Drupal7 page.

I don't think that the specific plugin, or the fact that it's been used in Drupal, is relevant to the proper jQuery usage.

jQuery's bundled with Drupal. I init the plugin on my page with:

```
    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
            }
        };
    })(jQuery);

```

In my markup, I have

```
    ...
    <div id="accordion1">
     ... EASYACCORDION MARKUP ...
    </div>
    ...

```

Again, with this init & markup, the accordion appears/works as expected.

On the same page, in another I've added an image-link, i.e.,

```
    ...
    <div id="myImg">
        <a><img src="myimg.png" /></a>
    </div>
    <div id="accordion1">
     ...  EASYACCORDION MARKUP ...
    </div>
    ...

```

I want to click on the image in the "myImg" div, and have the EasyAccordion snap to a specific open 'pane'. The activation of a particular pane is addressed, I think, by the

```
    line #127                jQuery.fn.activateSlide = function() {

```

function, as seen at the pastebin-link I provided above.

Iiuc, I need to add code to the init function above, to tie the image-click to an action execution in the EasyAccordion.

My question is -- how?

I think I need to fire off (e.g., for slide #3),

```
    jQuery(this).activateSlide(3);

```

adding some variation of,

```
    $('#myImg').click(function () {
      ...
    });

```

to the init, attaching it to the EasyAccordion init's function(). Something like?

```
    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
 ---->          $('#myImg',context).easyAccordion({ ...
 ---->          ?????????
 ---->          });
            }
        };
    })(jQuery);

```

So far the right syntax has eluded me. At least, I can't get the click-on-image to actually cause the specified item to 'activate' in the EasyAccordion.

These two posts,

```
http://stackoverflow.com/questions/5492258/easyacordion-jump-to-desired-slidenum-jquery-plugin
http://stackoverflow.com/questions/6243870/easyaccordion-jquery-plugin-callbacks

```

I think are close. But I'm still not getting the syntax to crowbar into my Drupal.behaviors... stanza right.

Any guidance?

# Answer
> 0 votes
This works.

Adding a targetable class to each slide, so that markup's:

```
    ...
    <div id="myImg">
        <a><img src="myimg.png" /></a>
    </div>
    <div id="accordion1">
    <dt class="slide_1" >
         ...
    <dt class="slide_2" >
         ...
    </div>
    ...

```

then, in the init,

```
    ( function ($) {
        Drupal.behaviors.myEasyAccordion = {
            attach: function(context,settings) {
                $('#accordion1',context).easyAccordion({
                    autoStart:     false,
                    ...
                });
                $('#myImg',context).click(function() {
                    $("dt.slide_1").activateSlide();
                });
            }
        };
    })(jQuery);

```

Now, a click on the img in the #myImg div opens the target slide ... here, 'slide\_1', as intended.

---
Tags: 7, theming, javascript
---


# Question
Title: How do I pass a specific argument from a rules event to a condition?
I am setting up a default rule for my custom Drupal 7 module, as follows:

```
$rule->event('commerce_cart_product_add')
->condition(
  'mymodule_condition_1',
  array('something' => 'something_else'))
->action(
  'drupal_message',
  array(
    'message' => t('Example message'),
  ),
));

```

I have written a function, mymodule\_condition\_1, which returns TRUE or FALSE based on what product is being added to the cart. I need to be able to get the product from the rules event, and pass this to the condition. I have looked through all the documentation and example code but I can't seem to see a way to do this.

In the above example, 'something' and 'something\_else' need to be specific values, but I can't see what I can refer to in order to find out what they should be.

# Answer
In a case like this, you'd going to have to use what Rules calls a data selector. If you were building this Rule through the UI, you would click the "Switch to data selection" and enter some token that corresponds to the type of parameter required. In this case, the commerce\_cart\_product\_add event provides the arguments commerce\_order, commerce\_product, quantity, commerce\_line\_item, and commerce\_line\_item\_unchanged. (See all this in the event's definition in commerce\_cart.rules.inc.) So when trying to select the product passed to the event through the UI, you'd use commerce-product as the value for your condition's product parameter.

When building this Rule in code, you specify a data selector by appending :select after your condition's parameter's name. So, if the name of the product parameter for your condition (as defined in hook\_rules\_condition\_info()) is commerce\_product, your "something" would be commerce\_product:select. The "something\_value" would be the same token you'd enter through the UI, commerce-product (as that's the name of the product argument passed to the Rule).

And touching on one more aspect, the event info defines the variables that must be passed to Rules when an event is invoked. Your condition can use any, none, or all of these - it doesn't really matter. A condition or action's definition simply states what kind of parameters it needs, and the Rule configuration is responsible for passing the parameters to the condition from the pool of available variables (or from variables you load as part of the configuration).
> 2 votes

---
Tags: 7, rules
---


title: attach file to a node by code

text:
# Question
Title: attach file to a node by code
I wanted to associate a file to a node. so far so good. create a cck type file, and the problem was solved. but I can not do this, I do not want the user to choose the file. the file in question is already in the system. I have tried to place the file as # default\_value field and hide it with the hook\_form\_FORM\_ID\_alter, but failed.

```
function my_module_form_node_form_alter(&$form, $form_state, $form_id) {
    if(isset($form['type']) && isset($form['#node'])) {
        $type = $form['#node']->type;

        if(stripos($type, 'node-type') === FALSE)
            return;

        switch($type) :
            case 'node-type_xyz':
                $fid = arg(3);
                $file = file_load($fid);

                // make a cck field_invoice a hidden field
                $form['field_invoice']['#prefix'] = '<div style="display:none;">';
                $form['field_invoice']['#suffix'] = '</div>';

                $form['field_company']['und'][0]['value']['#default_value'] = 'ABC';
                $form['field_account_number']['und'][0]['value']['#default_value'] = '09879';
                break;
        endswitch;
    }
}

```

anyone have any suggestions?

# Answer
This can be a bit tricky, there are a few steps to get right. First create and save the node, then add the file to the node as a second pass. Here's an example implementation.

```
/**
 * Add a file to a field on a node
 * @param int $nid  node ID to add the content to
 * @param string $field_name the machine name of the field to add to
 * @param string $filedata the raw binary data as a string
 * @param optional boolean is the attachment an image (should image validation
 *        be performed)
 */
function mymodule_addfile($nid, $field_name, $filedata, $is_image = FALSE) {
  $node = node_load($nid);

  $field = content_fields($field_name, $node->type);

  // Load up the appropriate validators
  $validators =
  filefield_widget_upload_validators($field),
  if ($is_image) {
    $validators = array_merge(
      $validators,
      imagefield_widget_upload_validators($field)
    );
  }

  // Where do we store the files?
  $tmp_files_path = file_directory_temp()."/$file_name";
  $files_path     = filefield_widget_file_path($field);

  // Put the file in the temp folder
  $ret = file_put_contents($tmp_files_path,$filedata);
  unset($filedata);
  if ($ret === FALSE) {
    watchdog('mymod_error',"Could not write $nid ($file_name) to temp: $tmp_files_path");
    drupal_set_message("Could not write $nid ($file_name) to temp: $tmp_files_path", 'error');
    return FALSE;
  }

  $path = $files_path.'/'.$file_name;

  // Create the file object
  $file = field_file_save_file($tmp_files_path, $validators, $path);

  if ($file == 0) {
    watchdog('mymod_error',"Failed to save file $file_name");
    drupal_set_message("Failed to save file $file_name",'error');
    return FALSE;
  }

  // Apply the file to the field
  $node->{$field_name}[0] = $file;

  node_save($node);
  return TRUE;
}

A variation on the bottom works too, just assign the result to the file field.

function _fhi_add_existing_file($file_drupal_path, $uid=1, $status=FILE_STATUS_PERMANENT) {
  $fs       = filesize($file_drupal_path);

  $res = db_query("SELECT fid FROM files WHERE filepath = '%s' AND filesize = '%s'", $filepath, $fs);

  $fid = db_fetch_array($res);

  if ($fid) {
    //drupal_set_message("$filepath already found. fid: $fid");
    $fid = $fid['fid'];
    return field_file_load($fid);
  } else {
    $file=(object)array(
      'filename'  => basename($file_drupal_path),
      'filepath'  => $filepath,
      'filemime'  => file_get_mimetype($file_drupal_path),
      'filesize'  => $fs,
      'uid'       => $uid,
      'status'    => $status,
      'timestamp' => time()
    );

    drupal_write_record('files',$file);
    return field_file_load($file_drupal_path);
  }

}

```

This code drawn from memory and without interpreter (I've got too much time on my hands this morning) so be wary of typos I may have introduced. As with anything, not responsible for death of poodles as a result of the use of this code.
> 3 votes

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


title: Node creation with parameters

text:
# Question
Title: Node creation with parameters
I have a form that when submitted and validated, needs to be redirected to a page to create a node (node/add/factura-tmn), but I want to send a parameter to this page. Is it possible?

I currently have the following code:

```
function add_invoice_file_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/add/factura-tmn';
  drupal_redirect_form($form_state);
}

```

# Answer
> 1 votes
the solucion is very simple:

```
function add_invoice_file_form_submit($form, &$form_state) {
// files validations...
...
  $form_state['redirect'] = 'node/add/factura-tmn/' . $fid;
  drupal_redirect_form($form_state);
}

function paperless_planning_form_node_form_alter(&$form, $form_state, $form_id) {
    if(isset($form['type']) && isset($form['#node'])) {
        $type = $form['#node']->type;
        switch($type) :
            case 'factura_tmn':
                $fid = arg(3);
                $file = file_load($fid);
                ...
        endswitch;
    }
}

```

# Answer
> 1 votes
Why not just use a modified node add form? You can change it to have whatever fields and validation you want.

# Answer
> 0 votes
If you want to process a form, you can use drupal\_form\_submit(). The example reported in the documentation page shows how to use the function.

```
// Register a new user.
$form_state = array();
$form_state['values']['name'] = 'robo-user';
$form_state['values']['mail'] = 'robouser@example.com';
$form_state['values']['pass']['pass1'] = 'password';
$form_state['values']['pass']['pass2'] = 'password';
$form_state['values']['op'] = t('Create new account');
drupal_form_submit('user_register_form', $form_state);

```

Inside a form submission handler, it's not necessary to call `drupal_redirect_form()`; the code just need to set `$form_state['redirect']`. See what is done from form submission handlers implemented by Drupal core modules, such as system\_modules\_submit(), aggregator\_form\_opml\_submit(), and comment\_multiple\_delete\_confirm\_submit().

---
Tags: 7, nodes, forms
---


# Question
Title: Detect translatable strings in custom module code
I have a D6 site with several custom modules. The site now needs to support multiple languages.

All my strings are wrapped in t() and I'm pretty familiar with locale.module and the i18n modules. I know that all translatable strings get written to the 'locales\_source' table, and that from there I can export a .pot file to send to translators.

What I can't figure out, however, is how I can get all of the translatable strings in my custom modules into the 'locales\_source' table. I know that the t() function calls locale(), which in turn will write a newly found string to this table, but how can I make *all* translatable strings get into the table at once? I think I need a function that will parse the PHP source for t(), watchdog, hook\_menu, etc to find everything that's translatable and write it to 'locale\_source'...?

# Answer
> 4 votes
You can install the Translation template extractor module.

> The Translation template extractor provides a web based and a command line Gettext translation template extractor interface for Drupal as well as a reusable API to look for translatable strings and translatability errors. This tool is used under the hood at http://localize.drupal.org/ as well to serve as a parsing machine for Drupal.org project releases.

If you want a user interface that allows you to translate in any language the strings provided by your custom module, then you can install the Localization server.

> It provides a generic translation database backend with a community localization user interface, which allows people to collaborate on translating projects to different languages. It currently contains tools to translate Drupal projects as well as general Gettext based sources.

The difference is that the first module allows you to create the translation template files necessary to translate the strings provided by any module running on your server, including any custom module. Those files need to be edited to create the actual translation files that provide the translated strings.
The second module, which depends from the first one, allows to create the translation files using a user interface. While the first module requires you to manually edit the translation template files to obtain the translation files, with the second module you can do it using Drupal.

---
Tags: i18n-l10n
---


# Question
Title: How to list only the latest revision of all nodes in a view?
I currently have a view that lists all of our nodes which is what we use for a content dashboard. It shows the most recently updated nodes, their workflow status, and a few other details.

The problem we seem to be having is that we're using Revisioning which creates a new pending revision each time a user updates a node. When a user updates a node, the workflow state (custom CCK field) switches to **Review** automatically. Since the current published node has the workflow state **Live**, the view's workflow field does show "Review". I'm assuming this is because the view is only pulling the currently published content and not the pending revisions content.

When using the view type **Node Revisions** it lists every revision of a node, not just the latest one. This is a problem because our dashboard would be filled with a single node's revision history instead of all the current nodes.

Is it possible to create a view that lists only the latest revision (pending, or current) of all nodes on our site?

**Version info**
Drupal 6.22
Views 6.x-2.12

# Answer
In the view you should have it sort by revision id (vid) descending, then use Views Group By to group by node id (nid).
> 2 votes

---
Tags: views, workflows, nodes
---


# Question
Title: Views argument to match single date with date range field
My content type has a date field with an end date. So an example node has a date range, say from 2011-01-01 to 2011-01-30.

In my view, I want to add an argument/contextual filter that shows any nodes covering a specific day. So if the argument value is 2011-01-15, the node shows (it falls within its range). If the argument value is 2011-02-01, the node doesn't show.

In the Date (node) argument settings, I've played around with selecting both from and to date fields and the OR/AND settings, but can't find a way to do this?

# Answer
> 1 votes
It's a known bug, please see Multi-day events don't show up on day view of spanned days.

---
Tags: 7, datetime, views
---


# Question
Title: Best way to drop a field from a content type
What is the best way to remove a Drupal 7 field from a content type defined via the GUI? I want to use hook\_update\_N so the changes can be propagated to multiple servers upon running update.php. However I cannot seem to find a solution. db\_drop\_table() would make sense to me for custom defined schemas, but not for a content type/field defined through the GUI.

# Answer
There are two api functions to delete fields:

If you don't want to reuse the field, it might be a bit cleaner to delete the entire field instead of only delete the instance of it on the content type in question. Only you can be the judge of that.
> 18 votes

# Answer
Yes, field\_delete\_instance() is the function to delete field instances.

Note that `field_delete_instance()` automatically calls `field_delete_field()` if there are no remaining instances, so `field_delete_instance()` is most likely all you'll ever need.

`_update_7000_field_delete_instance()` is designed for core update functions. Example: in update function `x_update_7000()`, you are using `field_delete_instance()`. Then in `x_update_7001()`, you change the `{field_config}` table in an inconsistent way and `field_delete_instance()` obviously needs to be changed as well.

But now `x_update_7000()`'s call to `field_delete_instance()` would result in an error because the table is still in the old structure. However, the situation for contributed modules is different, since they should always be executed *after* all core updates and therefore need to work with the most recent core version.

But, this is a pattern that you might want to use for your own API functions which you are using in update functions.

Additionally, these \_update functions do not execute hooks because the outcome is not predictable (for example because the module for which the update is run might be disabled).
> 9 votes

---
Tags: 7, entities, hooks, updating
---


# Question
Title: How to make View setting changes happen simultaneously with deployment of a template
Making View setting changes happen simultaneously with deployment of a template. Where can I look to solve this problem?

Is there something that puts Views settings into Version Control, like Subversion?

# Answer
> 1 votes
You can export a view, via the views interface or the Features module. Both will version control the view, updating the view but chaining/updating the code (if no alterations have been made in the UI).

What I usually do, is to use a script that

* Updates the code on the
* Reverts features
* Clears cache
* Runs cron

This is done calling drush commands and works very well for updating sites that doesn't rely heavily on cached data.

---
Tags: views, version-control
---


# Question
Title: Views Slideshow only shows one static image and doesn't cycle in IE8
I have a slideshow that runs through numerous images on the homepage of a site. The slideshow works perfectly in Chrome and Firefox, but simply shows a static image in IE8. On IE8, a Javascript error is returned as follows:

> Message: Object doesn't support this property or method
>
> Line: 160
>
> Char: 5
>
> Code: 0
>
> URI: /sites/all/modules/views\_slideshow/contrib/views\_slideshow\_singleframe/views\_slideshow.js

The Drupal settings JS is as follows:

```
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, { "basePath": "/", "admin_menu": { "margin_top": 1 },
"admin_menu_dropdown": { "key": "`", "default": 1 }, "colorbox": { "transition":
"elastic", "speed": 350, "opacity": "0.85", "slideshow": false, "slideshowAuto":
false, "slideshowSpeed": 2500, "slideshowStart": "", "slideshowStop": "", "current":
"{current} of {total}", "previous": "« Prev", "next": "Next »", "close": "Close",
"overlayClose": true, "maxWidth": "100%", "maxHeight": "100%" }, "CTools": {
"pageId": "page-4d858fb47100047beb7ca4246959a972" }, "extlink": { "extTarget":
"_blank", "extClass": "ext", "extSubdomains": 1, "extExclude": "", "extInclude": "",
 "extAlert": 0, "extAlertText": "This link will take you to an external web site. We
are not responsible for their content.", "mailtoClass": "mailto" },
"viewsSlideshowSingleFrame": { "#views_slideshow_singleframe_main_main_panel-block_1": {
"num_divs": 7, "id_prefix": "#views_slideshow_singleframe_main_",
"div_prefix": "#views_slideshow_singleframe_div_", "vss_id": "main_panel-block_1"
, "timeout": "5000", "sort": 1, "effect": "fade", "speed": "700", "start_paused":
null, "delay": "0", "fixed_height": "1", "random": "0", "pause": "2",
"pause_on_click": "0", "pause_when_hidden": 0, "pause_when_hidden_type": "full",
"amount_allowed_visible": "", "remember_slide": 0, "remember_slide_days": 1,
"controls": "0", "items_per_slide": 1, "pager": "0", "pager_type": "Numbered",
"pager_hover": "1", "pager_click_to_page": 0, "image_count": "0", "nowrap": "0",
"sync": "1", "advanced": "", "ie": { "cleartype": "true", "cleartypenobg": "false" }
} } });
//--><!]]>

```

# Answer
It turns out that this was caused by something in the template. The developer had called the JQuery library from the page.tpl file when it was already being called by core, so it caused the error in IE. See this page on drupal.org for more information.
> 1 votes

# Answer
Try turn off some modules and check it then. I have problem with devel module. After turn it off my views slideshow started to work.
> 1 votes

---
Tags: views, 6, javascript
---


# Question
Title: How to prevent displaying the theme on a custom page callback in hook_menu()
I am developing a custom module with a callback script at `foo/myurl`:

```
function foo_menu() {
  $items = array();
  $items['foo/myurl'] = array( // change 'foo/myurl' to the url you want
    'title' => 'Callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function custom_callback () {
  echo 'success';
  return;
}

```

But this URL is to be called by a 3rd party script, and I only want to return the `echo`ed string, how can I prevent the rest of the theme from loading?

Thank you

# Answer
> 7 votes
Simply don't return any value, and exit.

In Drupal 7, that can be done by calling drupal\_exit(). In Drupal 6, you use code similar to the following one:

```
function custom_callback() {
  echo 'success';
  module_invoke_all('exit');
  exit();
}

```

When you call `drupal_exit()` you don't need to use `exit` too, as it is already used by the function.

`exit()` (or `drupal_exit()`) avoids other hooks are invoked after `hook_exit()`.
Drupal normally calls `drupal_page_footer()` after the menu callback returns its value; using `exit()` (or `drupal_exit()`) avoids that function is called, too. The effect is that the output of the menu callback is not cached. If caching the output is desired then the call to `module_invoke_all('exit')` and `exit()`, or `drupal_exit()` can be removed. As far as the menu callback doesn't return any value, the Drupal page will not be rendered, as it is evident in the Drupal 6 code contained in the index.php file:

```
$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_page_footer();

```

# Answer
> 7 votes
You can use the `delivery callback` property of your menu entry to specify the function to be used to *render* the results of your `page callback`. The default delivery callback is `drupal_deliver_html_page`. The page handler for the AJAX callback page at `system/ajax` uses `ajax_deliver` to return a JSON data.

This allow you to properly separate the page logic (ie. getting to data to output) from the rendering (ie. formatting the data).

---
Tags: hooks, theming
---


# Question
Title: add watermark to all images uploaded in the site
I am trying add watermark to all the images uploaded by users. Is there any preprocessor for the same? or any module to achieve it ?

# Answer
> 15 votes
Module ImageCache Actions is a well supported module that can add watermarks for Drupal 5,6,7. It does this all by caching the image using imagecache.

---
Tags: hooks, theming, media
---


# Question
Title: Auto node redirct depending on a cck field's content
When a visitor goes node/123, I need them to be redirected to the url that is specified in that node's cck field. I know there are plenty of modules that do redirects, but I need this specific type of automation. What would be the best way to go abut this?

# Answer
There is multiple way of doing this. Probably the best one is create a custom module and

Using hook\_menu\_alter(), alter the page callback for node/%node. In your page callback, check the type of the node to invoke node\_page\_view on the node or redirect to the referenced node.

```
MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

MODULE_node_page_view($node) {
  if ($node->type == MODULE_NODE_TYPE) {
    //if fixed_x is a node nid
    $reference = $node->field_x;
    drupal_goto('node/'. $referenced_node->nid);
    //if fixed_x is a path
    drupal_goto($node->field_x);
    //etc
  }
  else {
    return node_page_view($node);
  }
}

```
> 3 votes

---
Tags: 6, redirection
---


# Question
Title: How to print a variable set in my custom module's inc file in node-contenttype.tpl.php
I am trying to grab all links under `id="ctl00_ctl00_MainPlaceHolder_MainPlaceHolder_TaobaoLink"`.

Here is the function used in my custom module file:

```
function _taobao_add_tovar($url){
  $url = str_replace('&','&',$url);
  $tovar_page = _taobao_get_page('http://rutaobao.com/pages/item_detail.aspx?ItemId='.urldecode($url));

  $linkz = _taobao_get_block($tovar_page, '"ctl00_ctl00_MainPlaceHolder_MainPlaceHolder_TaobaoLink" title="Открыть оригинальную страницу этого товара на taobao.com">');
  preg_match_all('%<a [^>]+href="(?P<url>[^"]+)"[^>*]*>(?P<text>[^< ]+)</a>%si', $tovar_page, $linkz);
}

```

I've set the `$linkz` variable. How can I print it in node-mycontenttype.tpl.php?

# Answer
To get a variable to a custom node.tpl.php you need to do this in `MODULE_preprocess_node(&$variables)` usually this is done in your template.php file located inside your themes directory, however, because you are calling a private function `_taobao_get_page()`, I think you need it inside your module.

Something like

```
MODULE_preprocess_node(&$variables) {
   if ($node->type == 'mycontenttype') {
      $variables['linkz'] = X;
   }
}

```

Now you can call $linkz inside your tpl.php file
> 2 votes

---
Tags: theming
---


title: Tournament or competition module

text:
# Question
Title: Tournament or competition module
I'm running Drupal 7.2 web site embedding a multiplayer card game and am looking for a module, which would help me to run a tournament between users.

It should at least show **a list of participants** and **a tree of games** with 3 players and 1 referee.

I've searched around already and suspect there is no such module waiting for me (surprise suprise), so my question is more about how would you try to program such module yourself or maybe adapt some core module (seemingly there aren't many non-core modules for Drupal 7).

I have a bit experience in programming custom blocks and menus. I've read, but haven't understood the documentation on programming nodes yet.

# Answer
> 3 votes
You will need to create a custom module to do this. Not having experience with Drupal development it will be hard.

Since you are doing this in Drupal 7 you should not use nodes for this, but instead create your own entity. It takes a bit of extra effort, but it will help you, as you can design your entity to fit your needs. The entity API will help you do create an entity without having to think about much of the boring CRUD stuff.

You will also need to define a database table, where you entities can be stored, you will need a unique identifier, store the participants and the referee, the outcome and other useful data like when the entity was create, when the game was held etc.

Using the entity API module you can also create views integration for you entity which will allow you to display lists of games, like the 5 most recent and those sort of things, For displaying a *tree of games* you might need to do some custom coding. I'm guessing you want to display a tournament style list, which won't be easy. If that is the case you'll need to create some relationship between the games and use advanced CSS to create the display you want.

# Answer
> 0 votes
Your description is a bit vague really. It sounds like what you're trying to implement is very specific: "a list of participants and a tree of games with 3 players and 1 referee."

It does sounds like it is going to be very custom I'm afraid. One option might be picking up a copy of Pro Drupal 7 Development and learning how to write the module yourself. Another is paying a Drupal shop to write at least the basic framework for the module on your behalf.

I am struggling to think of contrib modules, already written, which would serve your purpose. There might well be some, and you could possibly use those in conjuction with rules to cobble something together, but it's my opinion that you probably wouldn't get quite what you want with this approach.

---
Tags: 7
---


# Question
Title: Apache URL aliases not working with the visibility settings for blocks
I have a page like example.com/abcd.php?url=efg with Apache aliasing it to example.com/product/efg. I don't want certain blocks to be visible on this page; when I use product/efg in the block section, it does not take any effect. I wanted to know how to go about this issue.

# Answer
If example.com/product/efg is a path alias, then you need to use the path that uses that alias in the block visibility settings.

For example, if example.com/product/efg is the alias for example.com/node/1, then you need to add node/1 in the list of pages where the block should not be shown.

If you have more path aliases for the same internal URL, then instead of setting the pages where the block should not be shown, you need to use PHP code that returns `TRUE` when the block needs to be shown. Code similar to the following one should work:

```
<?php
  return request_uri() != '/product/efg';
?>

```

If Drupal is executed in a subdirectory of the web server root directory, e.g. dr6, the code needs to be modified as follows:

```
<?php
  return request_uri() != '/dr61/product/efg';
?>

```

The reason I didn't use drupal\_get\_path\_alias() is that the function returns just one of the path aliases existing for the internal path passed as argument; in the case there are more path aliases, this would be a problem.
> 1 votes

---
Tags: blocks
---


title: Adding a clickable area to the logo

text:
# Question
Title: Adding a clickable area to the logo
At my Drupal 7.4 website with the default Bartik theme and no contributed modules, I have a big logo (715 x 280 px) and no slogan. These are my settings:

I'm trying to figure out the best way to add a sponsored link to the rectangle orange area (with the white example text "Plastikovie okna !!") at the screenshot below:

If a tilted rectangle isn't possible, I can live with a straight rectangle too.

If there is a CSS/JS solution, it is welcome too, but please tell me which CSS and JavaScript files to edit, so that the solution works at every page of my site.

# Answer
Try this: use the logo as a background image and not use the default logo at all. DO show the site name by checking the "site name" box. Use CSS to position the site name over the clickable area and hide the text, and use padding-top to make a clickable area. example:

```
#header .inside{
    background: url(images/my-header-image.png) center center no-repeat #48A9E4;
    height: 450px;
}
#site-name, #site-name a {
    display: block;
    height: 0!important;
    line-height: 1!important;
    overflow: hidden!important;
    position: absolute;
    top: 150px;
    left: 425px;
    padding-top: 175px;
}

```

Of course you will need to alter the values to fit your theme, but I have used this method many a time. Hope this helps!!
> 1 votes

# Answer
When you add a logo this way, the entire image is a link back to the homepage. The only answer I can think of is to place a link over the image. using css the link will be

* Float over the image using margin, position, etc
* Text indent -9999px;
* z-index higher than the logo img
* pad the link to be the size of the image

I would probably custom code this in page.tpl.php, however it looks like you are looking for a non-custom code solution. To do this create a new custom block, with the link being its content (remember to have a input filter that will take HTML tags). Move this block into header region.
> 1 votes

---
Tags: 7, javascript, theming
---


title: Change published date to 12 hour time

text:
# Question
Title: Change published date to 12 hour time
Right now my nodes say published by "author name 19:02". How can I change it to display 12 hour time 7:02?

# Answer
> 5 votes
It uses the default date format of the site, which is medium. You can configure that at admin/settings/date-time and choose a format which uses am/pm.

You can also implement `hook_preprocess_node()` in your theme or module and then override the 'submitted' variable set by template\_preprocess\_node(). That allows you to use a different date format just there.

# Answer
> 2 votes
In Drupal there are specific theming functions to customize this:

This is the default (for nodes):

```
function theme_node_submitted($node) {
  return t('Submitted by !username on @datetime',
    array(
      '!username' => theme('username', $node),
      '@datetime' => format_date($node->created),
    ));
}

```

This is the default for comments:

```
function theme_comment_submitted($comment) {
  return t('Submitted by !username on @datetime.',
    array(
      '!username' => theme('username', $comment),
      '@datetime' => format_date($comment->timestamp)
    ));
}

```

To override them, add these functions in your template.tpl.php of your theme, and change the name to `MYTHEME_node_submitted`. And now you can customize it:

Drupal 6 uses by default the format 'D, m/d/Y - H:i' , to understand the meaning of these letters, see full PHP doc here

To display in 12 hour format, replace H by h like this:

```
format_date($node->created, 'custom', 'D, m/d/Y - h:i');

```

API reference about format\_date()

---
Tags: 6
---


title: I cannot change the temporary Directory

text:
# Question
Title: I cannot change the temporary Directory
I cannot change the temporary directory under file settings. Everytime I change it, it says the changes have been made, but it reverts back to the setting it previously had.

I even went as far as deleting the 'dbo.variable.file\_temporary\_path' value in the database, but it is still not working.

Do you have an idea about where this is being stored?

# Answer
> 3 votes
It was hard coded in the settings.php file. This will override any settings you do in the UI.

---
Tags: 7
---