# Question
Title: Where can I find complete documentation of hook_field_info?
When I looked into the API documentation page of hook\_field\_info, it seems to be quite complete. But I could not see the complete details of the return array ingredients.

Why cannot I find the allowed values and detailed descriptions of the following values? Did I miss any documentation page that explain them more in detail?

* settings
* instance\_settings
* default\_widget
* default\_formatter

# Answer
> 3 votes
The only documentation you find about those arguments is the one you already linked (hook\_field\_info()).
The reason that documentation is not very specific is that each field implemented from a module can use any value it needs. For example, the Image field implemented from the Image module uses the following keys for the settings (see image\_field\_info()):

* uri\_scheme
* default\_image

Vice versa, the Decimal field implemented from the Number module uses the following keys (see number\_field\_info()):

* precision
* scale
* decimal\_separator

The default formatter, and the default widget are (respectively) the machine name used for the default formatter, and the machine name of the default widget. The different between formatters, and widgets is that a formatter shows the value of the field, while a widget requests the values necessary for a field.

If you want to see which values are used from a field, you need to check the implementations of the following hooks done from the module implementing the field:

# Answer
> 1 votes
Really, the values in `settings` and `instance_settings` are not set in stone; they will contain keys for settings specific to that particular field type.

They're arbitrary variables whose values will be used as the default for the field settings form. Exactly the same goes for `instance_settings`.

When you visit a page to edit settings for a field (e.g. `admin/structure/types/manage/page/fields/body`) you'll see 2 fieldsets. One (the top one) is the `instance settings` and the other is the `field settings`.

The default values for the instance settings are garnered from `instance_settings` on that field type's `hook_field_info()` implementation, and the same goes for the field settings.

The only way to find out what each one of the pre-defined field settings names is, is to read through all field-providing modules. I can't imagine that information having been summarised anywhere as it wouldn't really make sense to do so.

For the specific example you gave, the authors of the text field module decided that there was a setting required for that field called `text_processing`. So they defined that setting in `hook_field_info()`, and it perpetuates its way across the system.

I don't think `default_widget` and `default_formatter` need any more explanation, the docs cover those completely (nothing more to be said about them really, they both accept a string and what that string should be is obvious if you read the argument descriptions).

---
Tags: entities, hooks
---


# Question
Title: Integration of two sites (one is Drupal-based, the other isn't)
I'm trying to integrate two sites (one is Drupal-based, and the other isn't), and I need single sign-on. How can I realize it?

I have sites on different domains.

# Answer
If you want to do your authentication externally to Drupal, you could use the Secure Site module. You'd still need mod\_auth\_cookie to avoid double-password entry, but at least the username and password would be the same. I don't see mod\_auth\_cookie anywhere out on the internet any more, but I've got the code and could re-publish. As I mentioned in my comment above, it needs a little work.

Another way to avoid double password entry would be to put your sites at example.com/drupal and example.com/other, and protect all of example.com with Apache basic authentication.
> 1 votes

# Answer
When the non-Drupal site has a user created, use Drupal bootstrapping to create a new Drupal user. You can also use it to authenticate the user on the non-Drupal site.

It'd also be fairly trivial to write a script to generate Drupal users from the non-Drupal site, assuming you know their passwords. If not, send out a "forgot password" email to the users created in the Drupal site.

Check the documention for `drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL)`.

Last I did this I had some issues and found that this helped:

```
chdir($_SERVER['DOCUMENT_ROOT']);
define('DRUPAL_ROOT', getcwd());

```
> 0 votes

# Answer
In Drupal 7, setting up a Single-Sign On scenario involves the core user.module. There is an example on api.drupal.org that explains how to do this.
> 0 votes

---
Tags: authentication-authorization
---


title: Taxonomy: Too many tags?

text:
# Question
Title: Taxonomy: Too many tags?
I have a serious problem with the core's taxonomy module (Drupal 7): I have some vocabularies containing all together about 140,000 tags. I do not show these tags anywhere or use them for filtering or anything like it. At this point they are used only for a solr search index. It would be nice to show all nodes that have a certain tag as well, but I am not using this feature yet. Each node does not have more than 20 tags.

But nevertheless the taxonomy module eats all my memory so that the whole site is broken. I get the message

```
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to
allocate 75 bytes) in .../modules/taxonomy/taxonomy.module on line 1022

```

Does that mean, taxonomy module is not capable to deal with vocabularies that big? What am I supposed to use instead of taxonomy module to deal with big vocabularies?

# Answer
Nope, the taxonomy module can handle as many terms-per-vocab as your hardware will allow it to (within some reasonable theoretical bounds I'm sure, but certainly 140,000 terms would not be too much these days).

The 'problem' is in your server configuration. Quite simply you don't have enough available memory for the taxonomy module to process as many records as it needs to.

Try increasing the PHP memory\_limit setting gradually and hopefully you'll be able to come to an acceptable compromise between your available memory and the size of your vocabularies.

Just to preempt what I think your response will be - you're already allocating 256MB, which might be a large (even outrageous) amount of maximum memory to give to a single PHP script, but the fact that you're getting out of memory errors means it's simply not enough for your site and needs to be increased (unless you want to optimise the core taxonomy module which I don't think would be much fun).

If you're on shared hosting, the first thing to do would be to get the site on a dedicated server/VM. That should make a good bit of difference.
> 2 votes

---
Tags: taxonomy-terms
---


# Question
Title: Is there a way to hide images from the media library?
I'm using the media module, and I'd like to hide some images (in a certain subdirectory) from the files overview in the admin area.

Is this possible?

Thx in advance!

# Answer
> 2 votes
Yes, in version 2.x of the media module the media browser is implemented as a view. This is the key to doing any sort of customisation to the browser. You should be able to see it in admin/structure/views and override it as you would with any other view.

The media browser view uses files as it's base type. It has some existing filters for filename, type etc. You can add another one that filters by path. If you use the *starts with* operator and value *public://foo/*. That will end up doing a SQL LIKE query on the *uri* column of the file\_managed table, which should give you what you want.

It's worth noting that you can customise the media browser only for certain file fields. To do that, clone the view instead of overriding it, thereby giving you two media browsers. Then for each field that uses a media widget, you need to choose which browser(s) you want.

---
Tags: 7, files, media
---


# Question
Title: Progress bar in drupal admin area for long running scripts
I have a custom module that has visual representation in admin area of my Drupal 7 installation.

Script that runs via that module executes pretty long time (some syncing process), and i would like to implement some kind of Progress bar (like when you run some cron job etc in Drupal, you see progress bar and even messages of the script parts).

How i can implement this ? Basicially, i would like to track a foreach loop, and iteration through foreach loop would be visible as progress bar.

Script is being triggered via hook\_form\_submit.

Thanks!

# Answer
> 7 votes
Grab a copy of Examples and checkout the batch\_example module.

It's got several code examples for various scenarios using the batch API, which Drupal uses internally to produce pages with progress bars (like the upgrade check page for example). The module is very well commented, and it should give you everything you need to get started.

---
Tags: forms
---


title: Attach Galleries to Content Types

text:
# Question
Title: Attach Galleries to Content Types
I am working with drupal 7 and I need to attach a gallery to the content type. I looked at the current solutions where I can create a Image content type and create node references. I am looking for something where any user would be able to contribute images, multi-upload images at the same time, if possible can also add images from URL.

Also is it possible to do something where the user can just click on a "Add images" link and the user would be presented with a image upload screen ?

# Answer
> 2 votes
There are plenty of approaches to this, the main difference being whether you use the Media module or Drupal 7 core's built in image field. The image field route I think will be simpler as you have to create your own view mode to have custom image sizes with display suite and the 7.x-2.x version is still under heavy development. See the related Media modules for options. There are modules for multiple uploads and creating image galleries.

If you choose to use D7 core's image field you can add galleries to content types with the Views Galleriffic module.

Here are Step by step instructions for D7.

You can also switch between styles.

Default  Thumbnails above

For multiple uploads you can try Multiupload Imagefield Widget.

For a remote URL you can try Filefield Sources.

For an "Add image" button you can just create a link to the "/node/add/gallery" node or create a custom form.

# Answer
> 0 votes
On the content type, using your image field settings you can enable the number of values greater than one.

For the file source you can use FileField Sources module.

And for the gallery display you can use Gallery Formatter

# Answer
> 0 votes
Hope you have found the answer already since your question is from May. If not, and for all those who are still looking, this is a great tutorial.

http://www.dailymotion.com/video/xnqe4c\_creating-a-drupal-7-image-gallery-using-content-types-nodes\_tech?start=0#.UOS4IRwujTN

---
Tags: nodes, navigation, media
---


# Question
Title: Is there a way to get field associated with content type?
I have to do some functionality with fields associated with a content type, this i have to do before creating content for it.

In custom module tried using node\_type\_load('digital\_iq\_2012'), this function loads content type details alone and not the fields associated.

Do we have a way to get the fields as well?

Any help?

# Answer
> 2 votes
You can use field\_info\_instances('node', $content\_type).

With `field_info_instances('node', 'article')`, I get the following.

# Answer
> 1 votes
I guess **field\_read\_fields** will be nice : http://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field\_read\_fields/7

---
Tags: nodes
---


# Question
Title: How can I get rid of the paddings and margins that come with the webform?
What I did was use `position: absolute` to have them the way I want, but that is probably not a good idea. I tried to put padding and margin 0 everywhere, but Drupal seems to override my CSS or something.

# Answer
> 0 votes
Assuming D7,

You can use drupal\_add\_css() through a node or page template and add in your own styling that way. That should get loaded last. drupal\_static\_reset() can clear out css that may be conflicting if you encounter stubborness.

Also... clear the cache?

# Answer
> 1 votes
You can override Drupals styling rules. Just use your browsers (Chrome, Firefox) developer tools to inspect elements for whats styling rules they have. Then override them in your themes stylesheet(s).

---
Tags: webforms
---


# Question
Title: How to place the page title and local tasks tab in a Panels region?
Is it possible to move the displayed page title (h1) and the local task tabs below it (the 'view' and 'edit' node tabs) to a region? Panels displays these by default for node/% page overrides.

I can add the local task tabs to a region of my choice, but I can't see how to remove the default node local task tabs.

And while I can set the page variant to 'no title', that's not really what I need, I want to define the region where it should be shown. I can add the 'Page title' from the page elements Panels content in the region I want, but it is empty when I set the page variant to 'no title'. I could add the title field and wrap it in h1 tags myself so I can use the 'no title' setting, or hide the first occurrence of the h1 with css and use the extra 'Page title' element, but it seems there should be a better way.

# Answer
If you're just wanting to do that for a single variant, you may need a combination of panels configuration, e.g adding local tasks and page title to region as well as either `hook_preprocess_page` or perhaps `hook_ctools_render_alter` to remove the page title and tabs from default output based on path or other criteria.

For example:

template.php

```
/**
 * hook_preprocess_page
 * Alter variables for the page template
 */
function THEME_preprocess_page(&$vars){
  // If on a node page
  if ($node = menu_get_object('node')) {
    // Remove page title and menu tabs for this node type
    // as they're output in the panel variant instead
    if ($node->type == 'my_type') {
      $vars['title'] = FALSE;
      $vars['tabs'] = FALSE;
    }
  }

}

```
> 2 votes

# Answer
If you want to remove or otherwise affect the page-level elements, such as menus, that's out of scope for Panels, as it only deals with the content/entity being displayed.

Panels everywhere however does for the page template what panels does for the node template and can be applied selectively to pages with selection rules just like other variants.
> 2 votes

# Answer
Have you tried using the Title module? It transforms the Title property to a full Field API field with all the benefits coming with that. As a bonus it will also be fully translatable too.
> 0 votes

---
Tags: panels
---


# Question
Title: Is it possible to add menu tab in any menu group?
Any idea on how I can render the menu tab item into a menu group?

My goal is to add a user tab in navigation menu group. I tried hook\_menu but I cant manage to make it work.

Here's my approach:

```
function lms_core_menu() {
  global $user;

  $items = array();
  $items["user/$user->uid/myresults"] = array(
    'title' => 'My Results',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'navigation',
  );

  return $items;
}

```

Ideas will be greatly appreciated.

**EDIT:** See the image attached.

# Answer
Just change

```
'type' => MENU_NORMAL_ITEM

```

to

```
'type' => MENU_LOCAL_TASK

```

and clear the caches.

The MENU\_LOCAL\_TASK option will make the menu item render as a tab in the user/% group. If you want to control the tab order you can use the 'weight' key in `hook_menu()`.
> 1 votes

# Answer
I'm a little confused here so, first off a couple things in some comments below:

```
function lms_core_menu() {
  global $user;  // will be that of your admin when s/he rebuilds the menu...

  $items = array();
  $items["user/$user->uid/myresults"] = array( // so this will be hardcoded most probably as user/1/myresults
    'title' => 'My Results',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'navigation',
    // where is your page callback, eg, is it defined somewhere else and you are hoping to just piggyback on it in here?
  );

  return $items;
}

```

because I would imagine you could do something along the lines of:

```
function lms_core_menu() {

   $items=array();

   $items['lms_core/myresults'] = array(
      'title' => 'My Results',
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'navigation',
      'access callback' => 'user_is_logged_in',
      'page callback' => 'lms_core_myresults',
   );

   return $items;

}

function lms_core_myresults() {
   global $user;

   $account=user_load($user->uid);

   return FUNCTIONTHATCREATESMYRESULTSBASEDONTHEUSER($account);
}

```

where that big capitalized function above is the page callback defined wherever

```
$items['user/%user/myresults']

```

is defined.
> 0 votes

# Answer
You can, using code similar to the following one.

```
function lms_core_menu() {
  $items = array();

  $items['user/myresults'] = array(
    'title' => 'My Results',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'navigation',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'lms_core_myresults_page',
  );

  return $items;
}

function lms_core_myresults_page() {
  global $user;

  // Use $user for the user account information.
}

```

If you want to show the menu item as menu tab, and as menu link, you can use code similar to the following one.

```
function lms_core_menu() {
  $items = array();

  $items['user/myresults'] = array(
    'title' => 'My Results',
    'menu_name' => 'navigation',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'lms_core_myresults_page',
  );

  $items['user/%user/myresults'] = array(
    'title' => 'My Results',
    'type' => MENU_LOCAL_TASK,
    // The default access callback is user_access(), when the
    // access arguments are an array containing the permission users must have
    // to see the menu item.
    'access arguments' => array('the permission to see this tab'),
    'page callback' => 'lms_core_myresults_tab',
    'page arguments' => array(1),
  );

  return $items;
}

function lms_core_myresults_page() {
  global $user;

  // Use $user for the user account information.
}

function lms_core_myresults_tab($account) {
  // Use $account for the user account for which the tab is shown.
}

```

The difference is that the menu link will be visible only to the currently logged-in users for their own account, while the tab will be visible to every user with the right permission, for the user account %user. (This means users could see the tab for their own account, or for the accounts of other users, depending on the permission.)

Instead of the default access callback, you can use a custom one, as in the following code.

```
function lms_core_menu() {
  $items = array();

  $items['user/%user/myresults'] = array(
    'title' => 'My Results',
    'type' => MENU_LOCAL_TASK,
    // Instead of the default access callback, the code uses a custom one.
    // The argument passed to the access callback is the user object matching the
    // user ID passed in the URL.
    'access callback' => 'lms_core_user_access',
    'access arguments' => array(1),
    'page callback' => 'lms_core_myresults_tab',
    'page arguments' => array(1),
  );

  return $items;
}

function lms_core_myresults_tab($account) {
  // Use $account for the user account for which the tab is shown.
}

function lms_core_user_access($account) {
  if ($account->uid == $GLOBALS['user']->uid) {
    // The currently logged-in user is watching the tab for her/his own account.
    return user_access('permission for the users who watch their own account');
  }
  else {
    return user_access('permission for the users who are watching the account of another user');
  }
}

```

In this example, the access callback checks a different permission, if the user is watching the tab for another user account, or her/his own user account.
> 0 votes

---
Tags: 6, routes, navigation
---


# Question
Title: How to override file_public_path in install profile?
I want to create an install profile that creates the files folder in the document root, www.example.com/files, and not the sites/default folder.

I have tried two methods of doing this and both partially works, they create the folder in the correct place, but when the site is finished installing the admin/config/media/file-system is showing "sites/default/files".

**Method 1 used:**

Added "$conf\['file\_public\_path'\] = "files";" to settings.php

Note: This line was actually removed from settings.php after installation finished

**Method 2:**

added the below code to \[myprofile\].profile:

```
function sitebase_install_tasks_alter(&$tasks, &$install_state) {
  $GLOBALS['conf']['file_public_path'] = 'files';
}

```

In both cases the **Verify requirements** step was testing for "files".

How come Drupal all of a sudden seems to lose this setting and instead inserting the wrong value in the db? Do I need to also manually insert this in the db in \[myprofile\].install?

# Answer
> 2 votes
You probably want to look at this very recent blog post from PreviousNext: Collecting and writing configuration settings to setting.php from an install profile for answers to this question and your other about creating your own step in an install profile.

From that blog post regarding their install profiles form submit handler:

> Then we had to do the actual storing of these variables. Now at this stage the database connection is not setup so you cannot call variable\_set(), you have to use another of Drupal's lesser known api functions - drupal\_rewrite\_settings(). This is the function Drupal uses to write the $databases variable to your settings.php. But with some minor wrangling you can use it to also write $conf variables to settings.php, which are from that point forward available for use via variable\_get(). And therefore available for us to use to define our connection settings for the solr server. Because drupal\_rewrite\_settings should only be called once (to avoid having your settings overridden) we had to duplicate what the standard install does - ie writing the database settings - then we could write our own $conf settings.

---
Tags: distributions
---


# Question
Title: How can I add a class to #markup output?
I'm using this code to add a cancel button to my form. The link is generated through `#markup`:

```
  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );

```

I'd like to add a class, `cancel`, to the link. I tried adding this line:

```
'#attributes' => array('class' => array('cancel')),

```

but the class is not added. I'm guessing because `#attributes` cannot modify `#markup`? How can I add the class in this case?

# Answer
> 1 votes
You can do this...

```
$form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination, array('attributes' => array('class' => array('cancel')))),
    '#weight' => 20,
  );

```

The third argument on the 'link' function is for attributes and such...

```
l($text, $path, array $options = array())

```

Documentation: http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7

---
Tags: theming, hooks
---


title: Use views attachment as a block

text:
# Question
Title: Use views attachment as a block
Is there a way to use the views attachment as its own block? I would like to take the attachment from the "Glossary" view and output it elsewhere on my site.

# Answer
You could try creating a block in a custom module using hook\_block\_info and hook\_block\_view. Then use views\_embed\_view to load the view and display it in your block.

This may look a little like this:

```
function my_module_block_info() {
  $blocks['glossary_attachment'] = array(
    'info' => t('Glossary Attachment'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function my_module_block_view($delta = '') {
  $block = array();
  if ($delta == 'glossary_attachment') {
    $block['subject'] = t('Glossary Attachment');
    // Load the view.
    $view = views_embed_view('glossary', 'attachment');
    if ($view) {
      $block['content'] = $view;
    }
    else {
      $block['content'] = t('The view is empty');
    }
  }
  return $block;
}

```
> 3 votes

# Answer
Perhaps it's possible to add a "Block" display to the same view ( Via add new Display tab ) and then to add the block to a page from Admin \> Structure \> Blocks
> 0 votes

---
Tags: views
---


# Question
Title: How to upload static files to a remote server in Drupal 7 instead of local filesystem?
I've recently had to migrate from Django to Drupal 7 due to web server constraints. One of the aspects of my old Django setup that I would like to preserve is hosting static content like images and other media on a remote server as I have free access to a massive server for this purpose.

With Django, this was as simple as editing a line or two in the settings.py file. My search for how to do this in Drupal has so far been pretty fruitless. Can someone please suggest a relatively simple way of doing this automatically?

The website in question will have multiple contributors, most of whom will be non-technical, so this should be something that is handled automatically.

# Answer
> 1 votes
You should look into the CDN project. I am think of implementing it myself, but have no practical experience to impart.

# Answer
> 0 votes
I have never seen it done like you're asking for using Drupal's settings file. However I've seen people (including myself) add a rule to the Apache virtual host for your local site that automatically detects links to images and makes Apache serve the images from your web host instead of your local host. That avoids having to download the images every time.

# Answer
> 0 votes
CDN module does the trick. You can just give the address of remote host in CDN module configs. You can also specify which files or paths need to be serverd from your remote host (i.e CDN).

---
Tags: files
---


title: customize url of path of file entity

text:
# Question
Title: customize url of path of file entity
I'm using the media module to build an imagebank. Is there a way to customize the url of a file? Currently is looks like this: `file/20` and I would like t to look like this `imagebank/image/20`.

Any ideas?

thx in advance

# Answer
File entity doesn't currently integrate with Pathauto but integration is being worked on in Add support for Pathauto.

Please help test the latest patch and provide feedback including if it works correctly and any issues you might have found!
> 2 votes

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


# Question
Title: How to change the url alias after a username change?
I'm using pathauto to username paths (/member/\[username\]). After changing a username the url alias doesn't change and the user edit page doesn't have an option to change it manually.

Is it possible to change it with a rule?

# Answer
> 6 votes
Yes, you should be able to do this with a rule. Something like the following:

1. Event: 'After updating an existing user account'
2. Conditions: 'Data comparison'. Compare **account-unchanged:name** to **account:name** and make sure you negate, so the rule is fired when they don't match (i.e. when this field has been updated)
3. Actions: '**Create or delete any URL alias**'. THis should be under the 'Path' section. Select account:url and create a new value for it

Hope this helps!

Rules export:

```
{ "rules_change_user_url_alias" : {
    "LABEL" : "Change user URL alias",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "account-unchanged:name" ], "value" : [ "account:name" ] } }
    ],
    "DO" : [
      { "path_alias" : { "source" : "user\/[account:uid]", "alias" : "member\/[account:name]" } }
    ]
  }
}

```

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


title: Views: Get total results

text:
# Question
Title: Views: Get total results
I am trying to get a total count of the results using Views. Looking at this link, Count results in Views using aggregation, I use aggregation, but Views counts each row as 1. For example, this is what I get:

```
TITLE         Results
"A title"     1
"A title2"    1
"A title3"    1
etc...

```

I want it to be

```
Title
"A title"
"A title2"
"A title3"

Results: 3

```

Any way to do this in Views? If not, is there a way I can weak the current Views SQL or its output instead of having to write my own module and SQL query from scratch?

# Answer
> 13 votes
Add a *Global: Result summary* field to the footer. There is no need to turn on aggregation.

---
Tags: 7, views
---


# Question
Title: Display number of pending messages and friend request on the user menu
I'm using Privatemsg & User Relationships and the built-in user menu as a sidebar block. What I want is to display the unread messages count and the pending friends requests beside the links "My messages" & "My friends".

Any ideas of how can I do this? Thanks in advance.

Mock-up:

# Answer
> 0 votes
At the end @mohit\_rocks answer was useful but didn't work at all. Here's my workaround (based in what I learned from Drupal Commerce: Alter 'Checkout' link in user menu & You have x pending relationships block \- note that I posted this answer on the second too):

**YOURCUSTOMMOD.module**

```
<?php function YOURCUSTOMMOD_unread_messages(){
global $user;
$unread_messages = privatemsg_unread_count($user);
return $unread_messages;
}

function YOURCUSTOMMOD_count_pending_relationships($account = NULL){
global $user;
$pending_relationships = user_relationships_load(array('requestee_id' => $user->uid, 'approved' => 0));
$count = 0;
if (is_array($pending_relationships) && !empty($pending_relationships)) {
    foreach($pending_relationships as $requester_uid => $relationship) {
      if($user->uid != $requester_uid) {
        $count++;
       }
    }
}
return $count;
} ?>

```

**template.php**

```
<?php function YOURTHEME_menu_link(array $variables) {
    $element = $variables['element'];
$sub_menu = '';
$count = '';
$name_id = strtolower(strip_tags($element['#title']));

// add counters
if ($name_id == 'mis mensajes') {
    $count = sineditmod_unread_messages();
    $count = '('.l($count, $element['#href'], $element['#localized_options']).')';
}
if ($name_id == 'mis amigos') {
    $count = sineditmod_count_pending_relationships();
    $count = '('.l($count, 'relationships/received', $element['#localized_options']).')';
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . '<span class="count green">' . $count . '</span>' . "</li>\n";
}?>

```

*Note*: **Remember to clean the cache!**

# Answer
> 2 votes
This will return the unread private messages in Drupal 7.

```
<?php
global $user; privatemsg_unread_count($user);
?>

```

Refer this for more discussion

This will return pending relationship request for the loggedin user.

```
<?php
function _count_pending_relationships($account = NULL) {
  $counts = &drupal_static(__FUNCTION__, array());
  if (!$account || $account->uid == 0) {
    global $user;
    $account = $user;
  }

  if (!isset($counts[$account->uid])) {
    $count = 0;
    $pending_relationships = user_relationships_load(array('requestee_id' => $account->uid, 'approved' => 0), array('count' => TRUE));
    if (!empty($pending_relationships)) {
      foreach($pending_relationships as $requester_uid => $relationship) {
        if($account->uid != $requester_uid) {
          $count++;
        }
      }
    }
    $counts[$account->uid] = $count;
  }

  return $counts[$account->uid];
}
?>

```

Refer this for detail discussion.

You can create a block and create respective links with the functions shown above.

---
Tags: routes, blocks, privatemsg, users
---


# Question
Title: Attach user created content (in this case a gallery view) to a Profile 2, per user
I have created *Galleries* by following the tutorial here:

http://www.dailymotion.com/video/xnqe4c\_creating-a-drupal-7-image-gallery-using-content-types-nodes\_tech?start=0#.UOS4IRwujTN

I managed to do it fine and have the galleries working.

Now what I would like to do, is to be able to attach that view to the *Profile2* for each user.

I tried different ways, but I probably don't have the concept right and time is pressing. I would really appreciate if anyone could give me a pointer.

Just by changing the *EVA* parameters from *Content: Album* to *Profile: Name of Profile*. I assumed the view was going to get attached to *Profile*. Well it does!

But How do I filter the content in order to just get the attached images uploaded by the profile owner?

Also, I have the following issue, the profile author is always the administrator, since users cannot create profiles. They are able to edit them after the profile is created by the admin.

I thank anyone who can give me a tip on how to solve this issue.

Further info: Using Drupal7, Profile2, Views3, Eva

FOUND OUT YET ANOTHER ISSUE : The "*Add more images*" link as per the reference node is public. If you set this field as private, it only affects the display of the *Title(link)* in the image node, but the "*Add more images*" link shows and can be used by anyone. How can this be solved?

# Answer
> 1 votes
I am going to answer the first part of my own question:

If you need a gallery per user and you need to attach it to a profile2 type. Follow the tutorial linked to in above question, to create each gallery.

* Clone the gallery view (EVA Field), and change in Entity Content Settings.
* For *Entity* Type use *Profile*.
* For *Bundles*, the profile types you want the view to be attached to.
* For *Arguments*, choose token, and select `profile2:user:uid`.
* Go to *Advanced* and add a `Content: Author relationship` and `Contextual Filters: (author) User: Uid`. In the settings of the *Contextual filter* choose author for *Relationship* (that's what appear between brackets) and also for *WHEN THE FILTER IS NOT AVAILABLE* select *Provide Default Value -\> User ID from URL*. And below, *Specify Validation Criteria* \> Choose "*User*" as the *Validator* from the pull down, and "*Allow both numeric UID's and string username* (I don't know if that's strictly necessary but broadens the possibilities).
* You may want to (I did) restrict the selected roles to those that have that kind of *profile2* type. Done.

Now I need to figure out how to restrict the "*Add more images*" link. If anyone can answer that, I appreciate.

* I have created a URL alias pattern for the images content type that includes the *USER ID* in the *URL* when an image is uploaded.

---
Tags: users, nodes, views, media
---


# Question
Title: Filter view based on displayed part of an Open Layers map
I have a page that shows an OpenLayers map which is fed with data coming from an Open Layers data overlay view (user locations; the location is provided via a location cck field in the user account settings). Right underneath the map the overlay data is listed using a clone of the Open Layers data overlay.

Is there a way to filter the displayed entitites in the list based on what part of the map is currently looked at? That is, is there a way to hide entities from the list when I zoom into a different part of the map?

Example: Zoomed to full extend, showing the whole world -\> display all entities. Zoomed to the US, showing only California -\> display all entities with a Californian location.

# Answer
We had the same requirement in a recent project. It was solved with javascript, there is no out of the box way to do this.

Please see https://www.transpower.co.nz/projects

Here is some code to get you started:

```
(function ($, Drupal, window, document, undefined) {

  // ...

  $(function(){

    if($(".not-front .openlayers-map").length && !$('.node-type-project').length) { // only run when there is actually a map on the page, but not on the home page

      if ($('body').hasClass('page-community-initiatives')) {
        is_ci = true;
      }

      mapData = $(".openlayers-map").data('openlayers').openlayers;
      pointLayers = mapData.getLayersByClass("OpenLayers.Layer.Vector");

      // cycle through all layers and points on those layers, adding the points to an array
      for (var i in pointLayers) {
        for (var j in pointLayers[i].features) {
          pointData.push(pointLayers[i].features[j]);
        }
      }

      // if we've pulled out some points, go make a list
      if (pointData.length) {
        makeList(pointData, ".pane-openlayers-map");
      } else {
        $('.pane-openlayers-map').append('<div class="no-results"><p>Your search returned no results, please try again.</p></div>')
      }

      // add event listener to the map to be fired whenever the user interacts with it.
      // calls refreshList function above
      mapData.events.on({
        "moveend": refreshList
      });

      Drupal.openlayers.popup.popupSelect.events.on({
        "featurehighlighted": popupOpen,
        "featureunhighlighted": popupClose
      });

    }

  });

})(jQuery, Drupal, this, this.document);

```

The entire JS file can be download (unminified) from the theme. Please alter to suit your needs.
> 2 votes

---
Tags: views, location, javascript
---


# Question
Title: How is the height defined for a region in a Drupal theme?
I can see that regions are defined in the .info file for a theme but I can't see how these regions relate to CSS that would be used to style them.

For example, in the acq\_minimal / Minimal theme, the Header region has a fixed height but I have examined defaults.css and other css files and the .php template files but I can't see how its height is defined.

The Header region height is fixed rather than flexible to the content within it, because if I put text in it with a really large font, this spills over other regions - i.e. the Header region does not stretch to fit.

But preferably I simply want to know how to change the height of the Header region (and other headers). Knowing how to change the width and set the position would also be useful.

Please advise.

# Answer
Nothing magical is going on here; just look in the .info file for the stylesheets and then look at them. The CSS in there combined with the html in page.tpl.php and other template files build the pages drupal creates. Well, sometimes some javascript comes into play, but that covers the majority of page markup.

ADDITION:

I don't have the theme you are referencing in specific on my machine, and if you are using Drupal 7 it will be slightly different, but to use garland under Drupal 6 as an example, and to expound upon the above and comments below, if we open up its .info file, we will find a:

```
regions[header] = Header

```

This tells the theme engine that it has a region called header. So, if we look in its page.tpl.php file, we will find:

```
<div id="header-region" class="clear-block"><?php print $header; ?></div>

```

So, when the user puts blocks in the Header region via the Block Administration page, drupal puts all of the html etc into the $header variable for those blocks, which is then output here when it paints the page.

As you can see, $header is wrapped in a CSS id and class, so you can then look back at the .info file to find your CSS files:

```
stylesheets[all][] = style.css

```

Opening up style.css reveals:

```
#header-region {
  min-height: 1em;
  background: #d2e6f3 url(images/bg-navigation.png) repeat-x 50% 100%;
}

```

which gives the first of many cascading styles to apply to the theme's Header Region. Don't fret over the clear-block class, it's just a wizardly way of making sure nothing floats next to the header (and vice versa), and you aren't ready for that yet lol.

So if you do this with your theme, you should be able to discover how its header is styled.
> 8 votes

# Answer
Firebug is your friend. Load the page and inspect styles. If the css referred to doesn't look like a real file name then make sure css aggregation is turned off.
> 2 votes

# Answer
Try Sweaver it is awesome!

> Sweaver offers a visual interface for completely changing your Drupal theme without knowing any CSS. Through a bar that sits at the bottom of your screen, you can change the fonts, colours, dimensions etc. of all your design elements and see the changes real-time. If you are happy with the changes, you can easily save it as a revision to activate immediately or save for later. Advanced users will find a highly pluggable and configurable system that allows full manipulation off the interface and extendibility of the functionality.

I was sceptical when I read about what it can do But it turned out great, works like a charm! Awesome editor, Cuts hours of coding down to minutes!
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How do I customize a Superfish Menu for Drupal 7?
I have successfully installed Superfish by installing the Libraries module, downloading the Superfish library and putting it in /sites/all/libraries, and installing the Superfish module.

Now I would like to customize the look of it. The pre-built styles that show up in the drop-down in the Superfish Configuration could be a decent starting point, but I really would like to get into the details and get the measurements and colors just right.

How can I do this?

# Answer
You need to overwrite the styles in your own custom stylesheet. Use firebug to find which styles you would like to adjust.

Keeping it in your custom stylesheet will keep the styles from being lost when you update the module.
> 2 votes

---
Tags: routes, theming, navigation
---


# Question
Title: How can I install composer packages with drush make?
How does one include composer package in a drush make file?

The more general answer, the better. There's already a composer drush module allowing drush dl to handle composer packages, but that requires a shell command for every dependency.

Given our future use of Symfony, composer and other Symfony bundles is likely to become more important in the future.

# Answer
> 2 votes
You should use yoursite.make to download the Drupal module and composer.json for composer.

There is the Composer module that integrates Composer with Drush.

I hope that soon .make is going to disappear, replaced by composer.json; for that to come true, some issues need to be resolved, such as version number.

Composer packages are stored in the git repository; you can't use a composer package, but you can download the code. For example, for https://packagist.org/packages/symfony/symfony you can use the following.

```
libraries[symfony][download][type] = "git"
libraries[symfony][download][url] = " https://github.com/symfony/symfony.git"
libraries[symfony][destination] = "lib/symfony/"

```

Composer can build stuff recursively; of course, this will not work here.

See: http://cgit.drupalcode.org/drush/plain/docs/make.txt

Their is also https://github.com/composer/installers than can do the invert (install drupal module with composer).

---
Tags: drush, deployment, composer, 8
---


# Question
Title: when to use include (inc) files in module development
I think I understand the structural differences of a .inc file (compared to a .module), but could someone describe the design differences? I see drupal example modules calling an .inc file with hook\_menu, or I see call .inc file for function defintions.

* Under what circumstances does one put code in a .inc file? Any general design guidlines that some adhere to?
* Is there any advantage other than clarity as to why one would use an (or multiple) .inc file? performance? versioning?

thanks!

# Answer
> 12 votes
As general rule, I would put in the module file the code that is required more often (e.g. helper functions used from more than one function), and in .inc files the code that is not used so often, or that is used for specific pages.

Since Drupal 6, the code automatically loads the files containing the page callbacks, or the form builders used for the menu items. For that reason, page callbacks for administrative pages are normally put on .admin.inc files, while page callback for *normal* pages are put on .pages.inc files.

Since Drupal 7, files containing classes are automatically loaded when a class is instantiated. Drupal 7 allows modules to define in which files their hooks are defined (through hook\_hook\_info()). For example, system\_hook\_info() defines the .tokens.inc files as files where `hook_token_info()`, `hook_token_info_alter()`, `hook_tokens()`, and `hook_tokens_alter()` implementations can be found; in this way, those files are automatically loaded when one of those hooks are required.
This allows to further split the code in files that are loaded when necessary, and code that is always loaded from Drupal.

---
Tags: 7
---


# Question
Title: When programmatically adding file field, how to set allowed file extensions?
I'm trying to add a custom node type in hook\_install() for my custom module. I've been able to add the fields I want but can't seem to find a way to set the allowed file extensions for file fields. (it defaults to .txt)

The example below shows how I create my file field. I have tried setting both `allowed_file_extensions` and `file_extensions` in the settings array but that does not seem to work.

How would I set the allowed file extensions for a file field?

```
    field_create_field(array(
        'field_name' => 'xxx_video',
        'type' => 'file',
        'settings' => array('allowed_file_extensions' => array('mp4', 'avi', 'mov', 'wmv', '3gp', 'mpeg', 'mpeg2', 'mkv')),
        'entity_type' => array('node'),
    ));
    field_create_instance(array(
      'field_name' => 'xxx_video',
      'required' => true,
      'entity_type' => 'node',
      'bundle' => 'xxx',
      'label' => t('Video'),
      'description' => t('Video to play in smartbox.'),
    ));

```

# Answer
The allowed file extension settings are added to the field instance settings, rather than the global field settings.

The variable is called 'file\_extensions' and not 'allowed\_file\_extensions'

It is also a textfield string value, rather than an array.

You could try something like:

```
field_create_field(array(
    'field_name' => 'xxx_video',
    'type' => 'file',
    'entity_type' => array('node'),
));
field_create_instance(array(
  'field_name' => 'xxx_video',
  'required' => true,
  'entity_type' => 'node',
  'bundle' => 'xxx',
  'label' => t('Video'),
  'settings' => array('file_extensions' => 'mp4, avi'),
  'description' => t('Video to play in smartbox.'),
));

```
> 5 votes

---
Tags: entities, files
---


# Question
Title: Manage data: users able to sort the data fields to select course
I need to find the right module or set of modules to help visitors to my site review various course offerings. The categories would be presenter name, course name, interest area. Also want to list the course description as a pop up. The user should be able to sort the data (like you would sort from different airline options - price, flight duration, time, stops, etc.)

What do I use? Views? Fields? Data?

# Answer
> 1 votes
Although your question is quite general, you should be able to achieve that with a combination of

1. Content type for the course with relevant fields added.
2. Comments enabled on the course nodes for the visitor reviews
3. Views to list courses ( exposed filters for user filtering, table display provides column click sort options )
4. You may also want something like fivestar or rate for user voting.

---
Tags: views
---


# Question
Title: Different favicon for local version of site?
It's a small thing, but it would be nice if a site running locally could use a different version of a favicon, to make it easier to separate local and live sites visible in browser tabs.

I had in mind a really simple implementation, where a local favicon would just have "\_local" appended to the name of the current theme favicon, so:

```
favicon.ico
favicon_local.ico

```

Then, if the site is running locally, and if a local version of the favicon exists, use it instead.

My question - what's the best way to implement this? Also, what would be a good way to check if a site is running locally?

Thanks for any ideas, code, or pointers.

# Answer
If you want to try out a code solution, you can mess with the favicon in a `hook_html_head_alter()`.

Something like this would be a starting point, but you likely need to adjust the `$_SERVER` test:

```
function MYTHEME_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $value) {
    if (preg_match('/favicon\.ico$/', $key) === 1) {
      if (in_array($_SERVER['HTTP_HOST'], array('localhost', '127.0.0.1')) {
        // adjust $value as needed
        $head_elements[$key] = $value;
      }
    }
  }
}

```
> 1 votes

# Answer
Do you use any versioning like Git? If so, you can just upload the real favicon to your live site, then change the favicon locally and add it to your .gitignore afterwards.
> 2 votes

# Answer
Favicon module handles this for the multisite installations. You may get few pointers from the code in the module.
> 0 votes

# Answer
Based on MPDs answer above, this is the code I used to define a custom favicon on this site, when it is running locally using mamp pro. This is a function in template.php for the active theme. Seems to work well.

```
function sitename_html_head_alter(&$head_elements) {

  $path = 'http://sitename/sites/default/files/favicon_local.ico';

  if ($_SERVER['HTTP_HOST'] == 'sitename') {

    foreach ($head_elements as $key => $value) {
      if (preg_match('/favicon\.ico$/', $key) === 1) {
        $head_elements[$key]['#attributes']['href'] = $path;
      }
    }
  }
}

```
> 0 votes

# Answer
You may find the Environment Indicator module is better suited for that purpose.
> 0 votes

---
Tags: files
---


title: content type view into hidden region

text:
# Question
Title: content type view into hidden region
I would like to create and display content type in a hidden region. The only reason to hide the region is to prevent moving the location. It is for flash file header banner that will be changed by a user by adding or modifying the content type. If it must be a block, then I suppose it doesn't much matter if the region is visible or not. Any suggestions?

# Answer
> 0 votes
If I understand correctly what you want to achieve, you could also try the Boxes module or even Panels and Panels Everywhere.

# Answer
> 0 votes
If you're comfortable in code, you may find it easier to add the flash banner in hook\_preprocess\_page, that way it isn't exposed to blocks admin.

e.g, template.php

```
function THEMENAME_preprocess_page(&$vars){
  $flash_embed_code = ''; // TODO, get flash embed code.
  $vars['flash_banner'] = $flash_embed_code;
}

```

Then, in page.tpl.php

```
if (!empty($flash_banner)) { print $flash_banner; }

```

---
Tags: theming
---


# Question
Title: Australian payment gateway adapter for Pay API
Is anyone aware of a working code for the Pay (7.x) module that will process payments over eWay or NAB Transact?

I am considering writing adapters for these gateways, but though I would put out a call for any existing code to start from.

# Answer
There are a few modules floating around for commerce, CiviCRM and Ubercart that use eWay, they would be good basis.
> 9 votes

---
Tags: 7, payment-gateways
---


title: Feeds Xpath Parser

text:
# Question
Title: Feeds Xpath Parser
I'm using the Xpath parser module for my drupalsite, and now I want to pick a result from an XML that has a certain time. The XML parts looks like this

```
    <time from="2012-12-17T12:00:00" to="2012-12-17T18:00:00" period="2">
      <!-- Valid from 2012-12-17T12:00:00 to 2012-12-17T18:00:00 -->
      <symbol number="4" name="Cloudy" var="04"/>
      <precipitation value="0.6" minvalue="0.3" maxvalue="0.6"/>
      <!-- Valid at 2012-12-17T12:00:00 -->
      <windDirection deg="80.2" code="E" name="East"/>
      <windSpeed mps="3.2" name="Light breeze"/>
      <temperature unit="celsius" value="-2"/>
      <pressure unit="hPa" value="1014.3"/>
    </time>
    <time from="2012-12-17T12:00:00" to="2012-12-17T18:00:00" period="2">
      <!-- Valid from 2012-12-17T12:00:00 to 2012-12-17T18:00:00 -->
      <symbol number="4" name="Cloudy" var="04"/>
      <precipitation value="0.6" minvalue="0.3" maxvalue="0.6"/>
      <!-- Valid at 2012-12-17T12:00:00 -->
      <windDirection deg="80.2" code="E" name="East"/>
      <windSpeed mps="3.2" name="Light breeze"/>
      <temperature unit="celsius" value="-2"/>
      <pressure unit="hPa" value="1014.3"/>
    </time>

```

And now I want to pick the time with from=....12:00....

How can I accomplish this?

# Answer
> 1 votes
Try this:

```
/time/@from
/time/@to
/time/@period

```

---
Tags: feeds
---


title: simple news confirmation message

text:
# Question
Title: simple news confirmation message
i am using simplenews module in drupal7 . i mentioned simplenews block on home page. when i enter email id it shows message "You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription." on home page . now i need to show this message on new page(not on home page). also i want to change the text of that message

Any idea ?

Thanks in advance

# Answer
You could try setting the subscription confirmation pages at: /admin/config/services/simplenews/settings/subscription \> "Confirmation pages"

> SUBSCRIBE CONFIRMATION
>
> Drupal path or URL of the destination page where after the subscription is confirmed (e.g. node/123). Leave empty to go to the front page.

It may be that that page is only used when confirming from the email link, but might work for the subscribe block as well.

The message text could be overridden with the stringoverrides module
> 1 votes

---
Tags: 7, emails
---


# Question
Title: Rules module not enabling via Drush in drupal 7
this may be a simple one however while downloading Rules through drush
and getting the following error.

```
root@li:/var/www/drupal7/sites/default# drush en rules*

No release history was found for the requested project (i18n_string).[warning]
Module rules_i18n cannot be enabled because it depends on the        [error]
following modules which could not be found: i18n_string

```

I also tried doing drush dl il8n\_rules but to no use.

What is wrong here?

# Answer
You'll need the i18n module to install rules\_i18n

```
drush dl i18n
drush en i18n_string
drush en rules*

```

Alternatively, enable the rules submodules individually, excluding rules\_i18n
> 1 votes

---
Tags: 7, rules, drush
---


# Question
Title: TinyIMCE not working: looking for image files
TinyIMCE is not working: At Hostgator, I cannot access the images that I know are in there (at sites/default/files/field/image and at sites/default/files/pictures). In the text editor, I select the image-add icon (the tree). I select image url icon. The dialog box is limited to showing sites/default/files. It does not allow access to /field/image or /pictures/ The "insert image button at top right is missing (but it exists on my local server.)

I have uninstalled and reinstalled the wysiwyg and imce modules. I have checked permissions. I have made certain the files are in the places noted.

# Answer
I believe the image component of TinyMCE is a licensed product you have to buy, see http://www.tinymce.com/download/download.php at bottom. You might want to try IMCE module http://drupal.org/project/imce which is free and integrates nicely with the WYSIWIG interface. If you do decide to go that route, afteryou install IMCE make sure you turn on the check box for IMCE in the TinyMCE options inside the WYSIWIG Admin Tab in Admin -\> Configuration. Works like a charm for me.
> 1 votes

# Answer
Perhaps you'd prefer the Insert module. Demo here.

Simply upload an image and click the "Insert" button to insert into the textarea.

You can also select from available image styles on insert, e.g thumbnail, large etc..

After installing, you'll need to add an image field to the content type and configure Insert on that field settings page.

Added bonus is uploaded images use the Drupal files API and are therefore, among other things, available for display elsewhere on the site, e.g with Views, which isn't possible with IMCE.
> 0 votes

---
Tags: media, wysiwyg
---


# Question
Title: loading newer jquery with hook_js_alter() breaks file upload on node edit form
I'm using hook\_js\_alter() in my theme template.php to load jquery 1.7 to my frontend only, and I've noticed that doing this breaks filefield uploads.

More specifically, once you select a file and click upload, the file will upload but the spinner just keeps looping. If you click preview during this, then after the refresh you'll see the link to the file and the "remove" button. If you click remove here, you'll see the same issue with the spinner continuously looping. Hit preview again, and it'll refresh with the file removed.

I tested this method with jquery 1.5.2 as well and had the same problem, so its not a jquery problem.

This problem does not exist if using the dev branch of jquery\_update module to load jquery 1.7. But the issue with using this is it breaks field\_ui and views functionality, so is not an option.

My code (very simple) is as follows, any ideas?

```
function mytheme_js_alter(&$js) {
    if (isset($js['misc/jquery.js'])) {
        $jsPath = 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
        $js['misc/jquery.js']['data'] = $jsPath;
        $js['misc/jquery.js']['version'] = '1.5.2';
    }
}

```

# Answer
> 2 votes
Worth noting, Drupal is released with a particular version of jQuery. You generally can't add a newer version of jQuery without refactoring some core js files.

http://drupal.org/project/jquery\_update

provides those core patches and more recent jQuery versions.

# Answer
> 0 votes
Try this:

```
function jetaatokyo_js_alter(&$javascript) {
  // Replace with current version.
  $jQuery_version = '1.5.2';
  $jQuery_cdn = 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
  $javascript['misc/jquery.js']['data'] = drupal_js_defaults($jQuery_cdn);
  $javascript['misc/jquery.js']['version'] = $jQuery_version;
}

```

---
Tags: 7, hooks, javascript
---


# Question
Title: Print url to image from profile2 field with mutiple images
Hello guys i've been trying to figure this out the past 20 hours but i can't. I want to print som image url's to a link. I have this code

```
<div id="background-slideshow">
<?php
  $user_fields = user_load(24);
  $profile2 = profile2_load_by_user($user_fields->uid);
  $image = field_get_items('profile2', $profile2['side'], 'field_baggrundsbillede');
?>
<?php foreach($image as $key=>$value): ?>
 $output = field_view_value('profile2', $profile2['side'], 'field_baggrundsbillede', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail'
    'image_link' => 'content',
  ),
));
  <div class="test">
   <?php print render($output) ?>
  </div>
<?php endforeach; ?>
</div>

```

But the problem is that it prints the image file, when i want an url. How can i make that happen?

Thanks

**EDIT**

```
<div id="background-slideshow">
  <?php
    $uid = 24;
    $user_fields = user_load($uid);
    //$profile2 = profile2_load_by_user($user_fields->uid);
    $images = field_get_items('user', $user_fields, 'field_baggrundsbillede');
  ?>
  <?php foreach($images as $key => $image): ?>
    <?php $url = file_create_url($image['uri']); ?>
    <div class="background-image" style="background-image: url(<?php echo $url ?>);">
    </div>
  <?php endforeach; ?>
</div>

```

# Answer
> 0 votes
1. To get just the path of an image, use file\_create\_url
2. To get the path of an image using an image style, use image\_style\_url

e.g, in the context of your code:

```
<div id="background-slideshow">
<?php
  $uid = 24;
  $user_fields = user_load($uid);
  $profile2 = profile2_load_by_user($user_fields->uid);
  $images = field_get_items('profile2', $profile2['side'], 'field_baggrundsbillede');
?>
<?php foreach($images as $key => $image): ?>
  $url = file_create_url($image['uri']);
  // $url = image_style_url('medium', $image['uri']); // example image style url
  <div class="test">
   <?php print $url; ?>
  </div>
<?php endforeach; ?>
</div>

```

---
Tags: entities
---


title: Hide menu titles in Omega subtheme

text:
# Question
Title: Hide menu titles in Omega subtheme
Can anyone help me how to delete or hide the menu titles (eg MAIN MENU title)?

I know how it is done when I do it on a static template but I cannot find it in Omega.

# Answer
If you display menu in block. Select Configure block from the drop down that appears On the next screen enter `<none>` in the Block title and then click Save block at the bottom of the page. Or you can simply `display: none` via css.
> 4 votes

---
Tags: theming
---


# Question
Title: Check if form field contains particular value, if so, do not allow user save
I am having a lot of spam signups on a drupal site. I am even using captcha and mollum, but still getting a lot. I have a field that asks 'why are you signing up?' which, when a human user / non-signup signs up, is filled with proper information, however, it seems there are a lot of robots / fake sign ups that all fill the field with a value which is just the literal path to the node field value like why\_are\_you\_Signing\_up\[und\]\[0\]\[value\]. It is always the same. So I thought I could check for this value and cancel the sign up. I have looked at hook\_user\_presave and hook\_save. These look like good starting points.

# Answer
> 0 votes
hope I'm not stating the obvious but if your form resides in a template or module you can add server-side validation to the form values using a function like:

```
function your_form_validate($form, &$form_state) {
  if ($form_state['values']['your_form_field_name']) {
    // Perform PHP validation, and return FALSE if rejected.
  }
}

```

Also, see Form generation.

---
Tags: advertising
---


# Question
Title: theme function not available, not called?
I am extending a module, I want to create a new theme function for the output but it somehow is not recognized. I know of theme registry and rebuild it (manually and via devel module)

The issue is tracked down to

```
function cmis_browser_content_properties() {
    $output = theme('cmis_browser_content_properties', array('cmis_object' => $object));
    debug($output, 'output');
    return $output;
}

function theme_cmis_browser_content_properties($variables) {
  // do sth
  $output = 'sth';
  return $output;
}

```

When I create a new function by copying the existing to

```
function theme_cmis_browser_content_propertiesnewtest($variables)

```

and call it in above module code. There is no output anymore, debug says: ''

```
$output = theme('cmis_browser_content_propertiesnewtest', array('cmis_object' => $object));

```

Please enlighten me!

just fyi the cmis module is a connector to alfresco document repository via CMIS http://drupal.org/project/cmis

just seeing similar questions suggested. Will see if one fits, but send this anyaway.

# Answer
From the looks of it you've forgotten to register your theme function with the system using `hook_theme()`

```
function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'cmis_browser_content_propertiesnewtest' => array(
      'variables' => array('cmis_object' => NULL)
    )
  );
}

```

After you clear the caches your theme function should be registered with the system and start working as expected.
> 2 votes

---
Tags: theming
---


title: Optimal route on creating landing pages

text:
# Question
Title: Optimal route on creating landing pages
So, time and again I've come across the requirement to create a "custom" or "landing" page which pretty much narrows down to this:

The co-existance of manageable text/content along with predefined views and/or blocks

For example:

```
-----------
|[managed |
|    text]|
|- - - - -|
|[View    |
|    pane]|
|- - - - -|
|[HTML    |
|   block]|
|_________|

```

Page Manager seems to be the way to go, but apart from using a block to accomodate my Managed Text (in this example), and thus creating a block for "non-blocky" purposes, and using it as an HTML containing entity, I cannot think of a better way.

So, tl;dr version:

Which is the optimal/Drupal way of having predifined and managed content bundled up together in a single page?

# Answer
Yes, as you mentioned, you can do that reasonably easily with Panels / Page Manager

Enable the "Custom content panes" module to add arbitrary HTML content to Panels regions.

Note, when using Views in your Panels content try Views Content Pane type displays, which are designed for embedding into Panels and provide some useful settings in the View.
> 0 votes

---
Tags: 7, nodes, chaos-tool-suite
---


# Question
Title: New to Drupal and views, how do I change the order of my fields?
How do I change the order of these fields? See the image. I want to be able to change the output order of these fields.

# Answer
> 11 votes
In the View edit page, click the little cog icon in the top-right of the "Fields" pane, there's a rearrange option there.

---
Tags: views
---


# Question
Title: Search node by Image Field and return image as result rather than the node
I want to be able to search for a an item in a multiple value field of a node and return the data of that specific value as the result.

I have a content type called 'Gallery'. 'Gallery' contains an image field that allows for unlimited values. Each value has an alt value that is exposed to Search API. I have a view using the "Search Views" module to filter the results from Search API.

I can successfully search for any 'Gallery' based on any of the alt tags of any of the images. The necessary data is exposed as fields to my view, such as: Gallery Photos: The image file. (indexed) | Gallery Photos » The image file.: File ID (indexed) (File ID (indexed))

but these fields only return data for the first image of that field in the Gallery.

I've searched high and low for a module or hack solution. No one has seemed to solve this. This seems like an important feature, because the way things are looking now, I would have to store each image as a separate node to be able to search for it individually. And that doesn't make sense for a lot of reasons.

Any help or direction would be greatly appreciated.

# Answer
The problem you are facing is that Search API has a flat structure, so it cannot save multiple values for fields, as it would require a change in data structure which isn't done during indexing, since it will effect the already indexed results.

If you knew how many values you could get (fx max 3), then you could create entity properties that pointed to the values for image 2 and 3. Otherwise this is beyound the scope of what's possible right now with Search API module (at least to my knowledge.
> 1 votes

---
Tags: 7, media, search
---


title: User Management - with different levels

text:
# Question
Title: User Management - with different levels
We are working on a site building using drupal. We have 3 different user profiles / roles.

1. Site Administrator (manage client admin and content)
2. Client Administrator (manage department admins)
3. Department Administrator (manage his own content)

Project Flow: Site admin, will manage client administrator. Whereas client admin will manage department administrator.

Since we are at the beginner level in Drupal, I wanted to know which module will suit the above user management.

# Answer
> 0 votes
For each role you can grant access control with permissions, so each user with specific role can manage any content or users you want to.

1. Managing access control with permissions and user roles
2. User: access and management settings

---
Tags: 7, users
---


# Question
Title: How can I use my table for Views 3 sort criteria?
I am trying to create a special sort criterium.
I have a table with 2 cols: *nid*, and *count*.

How can I use this table to sort the view by count?

# Answer
> 1 votes
You can let Views know about your data using hook\_views\_data.

The function documentation itself contains all the information you need to use the data for sorting and other Views functions, so I'm not repeating them here.

# Answer
> -1 votes
You need to create a module and implement `hook_views_query_alter()`

Check this for details.

---
Tags: 7, views
---


title: Cloning content type edit link

text:
# Question
Title: Cloning content type edit link
When developing a site I often want to be able to access content type definition from the level of a viewed node representing it. So basically I'd say I'd need a new MENU\_LOCAL\_TAB with the path `/admin/structure/types/manage/%`.

What hook should be used so to not replace/override the already existing path? I would not like the corresponding item to disappear from Admin Menu. I just want to have a handy duplicate shortcut tab within a node.

# Answer
> 1 votes
You won't be able to get a tab with exactly that path in it, as it won't match the `node/%` path and the tab simply won't show.

The easiest way I can think of to do it would be to create a proxy page that does match that pattern. Something like:

```
function MYMODULE_menu() {
  $items['node/%node/manage-ct'] = array(
    'title' => 'Manage content type',
    'access arguments' => array('something appropriate to your install'),
    'page callback' => 'MYMODULE_node_manage_proxy',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

function MYMODULE_node_manage_proxy($node) {
  $type = str_replace('_', '-', $node->type);
  drupal_goto('admin/structure/types/manage/' . $type);
}

```

That way the tab will appear, but as soon as the user clicks through to the page it will redirect to the node type form.

---
Tags: routes
---


# Question
Title: How can I trace a HTTP 500 (Internal Server Error) at `admin/reports/status`?
I get a HTTP 500 (Internal Server Error) at **admin/reports/status**

I see no errors at **admin/reports/dblog**

How can I trace this?

# Answer
> 1 votes
Check the Apache/nginx/other server error log, 500 errors almost always appear in there.

As neok notes, checking the validity of your .htaccess file would also be a good thing to do. If required extensions are missing for .htaccess directives a 500 error is often the result

---
Tags: wsod, log-messages
---


title: View Paid Sorting

text:
# Question
Title: View Paid Sorting
I wanted to do something like following scenario.

So for example I have a view of content type 'mycontent'.

Bob wants to be on the top and he is paying me money for it. Is there any way I can show paid node first in the View Display ? Based on what they pay.

Any help would be appreciated.

P.S : I am using Drupal 7. And I already have 1000 nodes of the content type.

# Answer
You could create a field on the node to track how much has been paid. Use hook\_field\_access() or field\_permissions to make this field so that it can't be modified by the user. Use rules or custom code to set this field with the amount paid when the node is paid for. Then order your view by this field descending.
> 0 votes

---
Tags: views
---


# Question
Title: Make a specific content-type inaccessible
I have a content-types that only is linked from nodes of other content types and therefore should not be directly accessible. In other words, I don't want a visitor to be able to access these kind of nodes by going to `node/<nid>`. Is this possible?

# Answer
Yes, the Rabbit Hole module was built for exactly that:

> Rabbit Hole is a module that adds the ability to control what should happen when en entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

It's highly configurable and works seamlessly in my experience.
> 5 votes

# Answer
You need to change the access callback used for node/%node, for example using code similar to the following one. Create a module (if you don't have already a custom one), and add the following code to the .module file.

```
function mymodule_menu_alter(&$items) {
  if (isset($items['node/%node'])) {
    $items['node/%node']['access callback'] = 'mymodule_node_access_callback';
  }
}

function mymodule_node_access_callback($op, $node) {
  if (in_array($node->type, $content_types_that_should_not_be_directly_accessible_array)) {
    // Leave the node accessible to the users with the permission of administering nodes, or who can bypass the node access.
    return (user_access('administer nodes') || user_access('bypass node access'));
  }
  else {
    return node_access($op, $node);
  }
}

```

I would use a custom module, if you need this functionality only on few content types, if you don't need all the functionality provided by a third-party module, or you want to be able to customize the code to use.

In the other case, I would rather use a third-party module, such as the one suggested from Clive.
> 4 votes

# Answer
I suggest using the Page manager to deny access or redirect users that try to directly access a certain content type.

If you take a look at my answer in this question What's the difference between Page manager and Panels?, you'll see I take exactly your use case as an example for why one would want to use Page manger.
> 2 votes

---
Tags: 7, nodes
---


title: Alter the comment form

text:
# Question
Title: Alter the comment form
I have the following code to alter the way comment form is displayed. After the bellow code everything is displayed as i want to but it does not add the comments.

```
 global $user;
     if ($user->uid) {
       $form['author']['_author'] = array
     (
        '#tittle' => 'Name',
        '#attributes' => array('id'=>array('name')),
        '#prefix' =>'<ul> <li class="name_field_c"><label for="name">Name</label>'.$form['author']['_author']['#markup'],
        '#suffix' => '</li>'
     );
     }
     else {
     $form['author']['name'] = array
     (
        '#type' =>'textfield',
        '#attributes' => array('id'=>array('name')),
        '#prefix' =>'<ul> <li class="name_field_c"><label for="name">Name</label>',
        '#suffix' => '</li>'
     );
     }

     $form['author']['mail'] = array(
        '#type' =>'textfield',
        '#attributes' => array('id'=>array('email')),
        '#prefix' => '<li class="email_field_c"><label for="email">Email (optional)</label>',
        '#suffix' =>'</li>',
        '#required'=>TRUE,
        '#weight' => 2
     );

    $form['comment_body'] = array
     (
        '#type' => 'textarea',
        '#attributes' => array('id'=>array('comment')),
        '#prefix' => '<li class="comment_field_c"><label for="comment">Comment</label>',
        '#suffix' => '</li>',
        '#weight' => 4,
        '#resizable' => FALSE
     );

     $form['author']['homepage']['#access'] = FALSE;
     $form['subject']['#access'] = FALSE;

     $form['captcha']['#prefix'] = '<li><div class="captcha">';
     $form['captcha']['#suffix'] = '</div>';
     $form['actions']['submit'] = array (
        '#prefix' => '<button type="submit">',
        '#suffix' => '</button></li></ul>',
        '#markup' => '<span>' . t('Say your piece') . '</span>'
     );

    $form['#action'] = $_SERVER['REQUEST_URI'];

```

To submit the form i have to press twice on the submit button ( how can i solve it ? ) and after i submit the form again i get the following errors and i cannot figure it out how to solve them:

```
Warning: array_values() [function.array-values]: The argument should be an array in _field_filter_items() (line 513 of /home/mcristi/public_html/jhub/modules/field/field.module).
Warning: Invalid argument supplied for foreach() in text_field_validate() (line 119 of /home/mcristi/public_html/jhub/modules/field/modules/text/text.module).
Notice: Undefined index: homepage in comment_form_validate() (line 2155 of /home/mcristi/public_html/jhub/modules/comment/comment.module).

```

This thing causes the problem that the form is not submitted/saved :

```
 $form['actions']['submit'] = array (
        '#prefix' => '<button type="submit">',
        '#suffix' => '</button></li></ul>',
        '#markup' => '<span>' . t('Say your piece') . '</span>'
     );

    $form['#action'] = $_SERVER['REQUEST_URI'];

```

Is there any possibility to save the comment on the node page ? ( to not be redirected to /comment/reply/$nid)

# Answer
You're overwriting the form elements that are already there, some of which are fields and so need to have their array structured very specifically (Why is hook\_form\_alter so messy in d7? has some background for that).

You can alter existing elements in the form without overwriting the whole thing like so:

```
$form['comment_body']['#prefix'] = '<li class="comment_field_c"><label for="comment">Comment</label>';
$form['comment_body']['#suffix'] = '</li>',

```
> 2 votes

# Answer
I don't understand why you did `#prefix` and `#suffix` with `<button>` on `$form['actions']['submit']` which have already generated a submit button:

```
  <input type="submit" id="edit-submit" name="op" value="Save" class="form-submit">

```

You destroyed the default submit button and replaced with

```
  <button type="submit"><span>Say your piece</span></button>

```

This would cause the problem of the comment not saved. You could update `#value` of the submit button.

```
   $form['actions']['submit']['#value'] = 'Say your piece';

```

Redirecting to "comment/reply/$nid" is not a problem since the related node is displayed on that page.
> 2 votes

---
Tags: forms
---


# Question
Title: How do I allow users to just click a marker on an OpenLayers map to go directly to the node?
I am using the OpenLayers module and it appears that I can add a popup and a tooltip behaviour if a users clicks or hovers over a marker on a map, but I only need users to be able to click the marker to go to the node (no popups). Is there a config I am missing to do this?

# Answer
Usually jumping to new page just by clicking object is not what users want, as they need to be sure first that the clicked object is correct one, this is why there is no built-in function and you do not see this much in the wild.

OpenLayers module has *behaviours* for this kind of actions. It seems that the core module does not have what you expect, and nobody has done it yet, so no easy configuration option :( Here is the guide how to create new behaviours from scratch. I would use Popup behavior as sample.
> 4 votes

# Answer
Excellent use case, given popups are bad for mobile UI. A marker makes a great button, and jumping to the page from that button is expected behavior in some scenarios.

You should consider the Geolocation Views module, if you're using Google maps.
> 0 votes

---
Tags: javascript
---


title: Multi Upload Widget

text:
# Question
Title: Multi Upload Widget
Is there any widget that allows uploading zips or multiple files at once?

One possible module is Plupload integration; however, it seems to be unstable and is under heavy development.

Are there any well known stable multi upload widgets?

# Answer
AFAIK, Plupload is your best option at the moment, now and for the future. If you're worried about its stability, you are invited to help with testing and bug fixing.
> 2 votes

# Answer
Multiupload Filefield Widget
> 1 votes

# Answer
If you are uploading images and on Drupal 6 (your post doesn't say) I have hade good results with Image FUpload
> 1 votes

# Answer
I've been using Plupload on a Drupal 7 site for about a year with no stability issues I can recall.

I chose it after testing most of the other options I could find and it was the most stable and simplest to use. As I say, that was a year ago and a lot may have happened since then, so others may have surpassed it or they may fit your use case better (some others were good, they just didn't meet my needs as well).

The only "issue" I have is that the form when you have 50 images with alt, title, etc in your form and in those cases things really bog down when you edit the page and on slow connections I have had timeouts when I save the page. I'm not really sure how you would get around this though unless the image manage/edit/upload actions were distinct and separate from the page edit/manage/create functions and possibly separate from each other (manage/edit versus upload). Short of that, you're going to have pretty heavy forms no matter how you do it.
> 0 votes

---
Tags: 7, files
---


title: How to list all managed files?

text:
# Question
Title: How to list all managed files?
I need to get Drupal to list all its files and their management status for debugging purposes. It seems like there must be a simple way to print the list of managed files, right? How is this done?

# Answer
> 2 votes
There is at least 1 issue queue item looking to add "reporting" to the Media module, such as show me where this file is used on the site.

If you're using Drush. Look at `drush sql-cli` and a query such as `select fid, filename from file_managed where status = 1`

---
Tags: media, files
---


title: spam bot attacks

text:
# Question
Title: spam bot attacks
I have multiple spam bots that try a couple hundred times a day to access my website and post comments. I have reCaptcha installed and somehow they are able to register, and sometimes actually post spam. I also have the honeypot module installed. What is the best way to stop this?

# Answer
> 2 votes
The alternative I can suggest is the Mollom module, created from Dries Buytaert, and which uses a service provided by Mollom BVBA, an Acquia company, both co-founded by Dries Buytaert.

> Mollom may block a post outright if it is from a known spammer. If Mollom is unsure how to classify a post, it may require the completion of a CAPTCHA to accept the post. Posts that do not match a "spammy" text pattern and do not originate from known spammers are accepted without the need to complete a CAPTCHA. Essentially, Mollom acts as a proactive content moderator that is on the job 24 hours a day, 7 days a week.

If you want to read a negative opinion, you can see What's wrong with Mollom?

# Answer
> 0 votes
Before mentioning reactive solutions, I feel obliged to throw out there that locking things down as much as possible is one key. If it's not a community site, you can hold comments for moderation and prohibit new registrations without admin approval. Then anything that gets through is because you've fallen behind on some security update.

As for the anti-spam otpions in Drupal...

In brief, I like to see CAPTCHA solutions as a last-ditch effort. Automated CAPTCHA solvers are cheap and CAPTCHA solving services that hire employees to solve captchas will solve them in an avg of 20 secs and are under $10/10,000. Meanwhile, the captchas have gotten so damn hard to read, that I often take six tries. It's a losing battle - in another couple of years, I am convinced that automated captcha solvers will be superior to humans at this task and they will serve only to annoy real visitors.

Drupal has so many modules that let you stop spammers by requiring "proof of work", by comparing to a blacklist, by analyzing behavior or whatever that I rarely use captcha with Drupal.

I'm new at Stack Exchange and I don't know if it's allowed to link to our own blogs, but I did a pretty long, one might say overly verbose (but hey, it's for my reference, nobody is forcing you to read it), blog post on some of your options and my subjective, ill-considered and quite possibly wrong opinions on them. Here's my list:

http://raisedbyturtles.org/stopping-spam-comments-in-drupal-7/

I should add that since I made up that list, I've also started using Cloudflare which integrates nicely with Drupal with the optional Cloudflare module. This stops a lot of attacks before they even get to your sever. For those that don't know, it's a reverse proxy service and so before they even forward the request onto your server, if the IP is in their list of known spammers, they block it there. I have been using Cloudflare for a couple of Drupal sites and at least one Wordpress site and am very pleased. The one thing to be aware of is that if it's an e-commerce site, using Cloudflare (or any similar reverse proxy on a separate server) will require you to buy an additional SSL/TLS certificate. Other than that, it's the simplest plug and play thing and blocks a lot of spambots (now I have to remember to update my spam module page to include that!)

---
Tags: advertising, 7
---


# Question
Title: How to set form type as 'hierarchical_select' programatically?
I am using the following code to create a form in Drupal 6. This code displays a drop down filter with which I can select the terms, and apply the filters using the GET method.

```
function sample_create_form () {
  $vid=2;
  $options = taxonomy_form($vid, $value = 0, $help = NULL, $name = 'sample');
  $form['#method'] = 'get';

  $form['option'] = array(
    '#type' => 'select',
    '#title' => t('Terms for the Website'),
    '#options' => $options,
    '#description' => t('Website category'),
  );

  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Submit'),
  );

  return $form;
}

```

I want to display the form as a Hierarchical Select type. I tried to use 'hierarchical\_select' instead of 'select' in the above code but it didn't work.

Is there a way by which we can get the hierarchical select form?

I am using Drupal 6 and I have hierarchical select module enabled.

Any help highly appreciated.

# Answer
I think its better to use hierarchical\_select for element as it gives a FORM API that is really easy to use. Check the following snippet as reference

```
$form['hierarchical_select'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div id="hierarchical_select" class="hierarchical_select_wrapper">',
    '#suffix' => '</div>',
    '#attributes' => array(
        'class' => array('hierarchical-select'),
    ),
);
$form['hierarchical_select']['select_subject'] = array(
    '#type' => 'hierarchical_select',
    '#title' => t('Select the tag you wish to use.'),
    '#size' => 1,
    '#config' => array(
        'module' => 'hs_taxonomy',
        'params' => array(
            'vid' => 13 //The vocab id
        ),
        'save_lineage' => 1,
        'enforce_deepest' => 0,
        'entity_count' => 0,
        'require_entity' => 0,
        'resizable' => 1,
        'level_labels' => array(
            'status' => 1,
            'labels' => array(
                0 => t('Grade'),
                1 => t('Subject'),
                2 => t('Main Topic'),
                3 => t('Sub Topic'),
                4 => t('Standard'),
                5 => t('Sub-Standard'),
            ),
        ),
        'dropbox' => array(
            'status' => 0,
            'title' => t('All selections'),
            'limit' => 0,
            'reset_hs' => 1,
        ),
        'editability' => array(
            'status' => 0,
            'item_types' => array(),
        ),
        'animation_delay' => 400,
        'special_items' => array(),
       'render_flat_select' => 0,
       'path' => 'hierarchical_select_json',
    ),
    '#default_value' => 0,
);

```

I hope this helps.
> 3 votes

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


# Question
Title: How to COMPLETELY limit access to Views pages?
I've got a content type that has attached to each of its nodes a calendar (e.g., node/123/calendar); this is generated by fullcalendar via Views. I'm setting up node access rules on that page so that some users can see the calendar and some can't. The node access is handled through the "Access:" field in Page Settings for the view, in what I think is the usual way (I'll admit to being something of a Views newbie).

This works, but (to my eyes) only sort of. If a restricted user tries to get to the page, they get the same page structure, generated by a page--node--calendar.tpl file, that they'd get if they were allowed to see the page, except that the content is the "You are not authorized to access this page" message. Thus the user is able to get some information about this restricted item, like the fact that there is a node that has a calendar attached to it. I'd prefer to have a more empty 403 or 404 error page come back, without the node-related wrappings.

Is there any way to do this? I suppose my page template could check the content it's about to display and see if it matches the access denied message, but that's a little more hackish than I'd like to get...

# Answer
> 3 votes
That is because Drupal, when users access a page to which they don't have access, it draws the page using its template file, and replaces its content with the error message.

What you can do is setting a page to use for the access denied page, and use a different template file for that page. In Drupal 7, that is done in admin/config/system/site-information, under *Error pages*.

Keep in mind that, when an access denied error is returned, the URL of the page is not changed; this means the users would still know the node has a calendar attached, if they try to access the page using the URL directly. The Calendar tab is not shown to users who don't have the permission to access it, though; they can only try using the tab URL, and see if they get an access denied error.

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


# Question
Title: Having trouble with ckeditor toolbar buttons
I cant figure out how the full toolbar can be view. I tried to toggle collapsed toolbar of and on however I am unable to see the either advanced toolbar or full (only some buttons I haven't selected at all). Meanwhile I can create the basic toolbar.

Can anybody help me get the full toolbar?

# Answer
> 1 votes
You probably need to configure CKEditor for a specific input format.

You might have an easier time if you install WYSIWYG module AND the ckeditor editor. This setup will integrate better with the Media module for instance. If you install WYSIWYG editor, you then can easily setup the editor per input format.

---
Tags: wysiwyg, toolbar
---


# Question
Title: Programatically updating node immediately after creation causes PDOException
I'm working on a Drupal 7 site where nodes represent jobs in a queue. When a node is created, a custom module with hook\_node\_insert launches another program using exec. This program tells Drupal that the job has finished by requesting a page on the site at site.com/jobcomplete/NODE\_ID/IS\_ERROR. The callback for this page then does:

```
$node = node_load((int)$node_id);
$node->field_completed[LANGUAGE_NONE][0]['value'] = ($error == 1) ? -1 : time();
node_save($node);

```

The problem with this is that sometimes the program errors out almost as soon as it's started. When this happens the callback is called before the request that created the node in the first place is completely finished, resulting in 'PDOException: SQLSTATE\[HY000\]: General error: 1205 Lock wait timeout exceeded' when node\_save is called.

How can I get the callback to wait for the request that created the node to finish before trying to update it? sleep() doesn't seem to work.

Thanks.

# Answer
> 2 votes
Drupal provides a Lock API for this purpose - to handle when multiple processes are competing for a resource.

In your case, you need to acquire a lock and release it when finished, checking if that lock is available prior to processing from the other component.

i.e:

Although not directly related, you may also be interested in the Queue API for other queue based processing tasks.

---
Tags: 7
---


# Question
Title: what are some considerations to help me decide whether I should configure through the UI, when to configure programmatically
I restarted a site I was developing realizing that I didn't have a systematic approach to design, namely, I was implementing changes through both the UI/database and module code and hooks without thinking about why I was doing so.

My question is: what considerations should I take into account when deciding whether to make configuration changes through the UI or by coding a module?

Of course this only matters for things that you can do through both UI and module development like hook\_menu, views, etc. Here is my list so far:

Reason for UI:

* Ease of integration: (e.g creating a new content type through a module is a pain compared through the UI)
* Specific-config: if you don't plan on installing this configuration on multiple sites, UI should be sufficient.

Reason for module:

* Versioning: code can be versioned, when stored in the database it's not
* Portability: if you plan on installing this functionality on multiple sites, then a module is pretty much a must.

Unknown:

* Speed (database v.s. module code)?
* I also find that if you need to use an .install file for something you don't plan on being portable, it seems pointless to add this to module code if it can be done through the UI. Is this right?
* Other?

I'm very new to drupal development, but I'm just trying to make the right design choices. Any information you can provide would be helpful.

Thanks!

# Answer
You should make configuration changes in code as much as possible, in particular it helps with

1. Ease of deployment
2. Consistency across deployment environments
3. Consistency across developer team environments
4. Configuration changes are tracked in version control.
5. The required configuration for the application is in the code base.

If you haven't already, checkout the Features module for a good approach to exporting and synchronizing configuration between environments.

For example, you can build a Feature module for your

* Views
* Panels
* Content Types
* Fields etc..

and synchronize the changes in code by rebuilding the relevant feature module on dev, deploying it and reverting the feature module on the deployed environment.
> 1 votes

---
Tags: 7
---