title: hook_update_N is not running

text:
# Question
Title: hook_update_N is not running
I know there is a question hook\_update\_N not running but I checked its answers and it didn't help. I'm just learning developing modules for Drupal so maybe it's something really stupid but I have no idea...

My hook (in testModule4.install):

```
function testModule4_update_7001() {

$schema['testModule4_table'] = array(
    'description' => 'TODO: Description',
    'fields' => array(
        'main_id' => array(
            'description' => 'TODO: Description.',
            'type' => 'serial',
            'not null' => TRUE,
        ),
        'settings' => array(
            'description' => 'TODO: Description',
            'type' => 'text',
            'not null' => FALSE,
        ),
        'uid' => array(
            'description' => 'TODO: Description',
            'type' => 'int',
            'not null' => FALSE,
        ),
        'created' => array(
            'description' => 'TODO: Description',
            'type' => 'int',
            'not null' => FALSE,
        ),
        'changed' => array(
            'description' => 'TODO: Description',
            'type' => 'int',
            'not null' => FALSE,
        ),
    ),
    'primary key' => array('main_id'),
);

db_create_table('testModule4_table', $schema['testModule4_table']);

}

```

My module is working just fine. The schema\_version of module in database is 0 but update.php just cannot see it. What can be the cause of that? :/ I was trying clearing cache and reenabling a module but without success. I just don't know where to search for source of the problem. If you need more data, just comment :/ .

**Edit:**

I created simple module:

**testModule.module**:

```
<?php

function testModule_myform($delta = "") {

    $form['something'] = array(
        '#type' => 'markup',
        '#markup' => 'Something',
    );
    return $form;
}

/**
 * Implements hook_menu();
 */

function testModule_menu() {
    $items["test/test"] = array(
        'title' => 'testModule',
        'description' => 'TODO: Description',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('testModule_myform'),
        'access callback' => TRUE,

    );
    return $items;
}

```

**testModule.info**:

```
name = testModule
description = Test module for Drupal experiments.
package = CustomTest
core = 7.x

```

**testModule.install**:

```
function testModule_update_7001() {
    drupal_set_message('It works!');
    print 'Show something!';
}

```

And it still ignores this hook... Is it officially a Drupal bug and I need to reinstall the whole Drupal? \>\_\<

# Answer
The problem is upper/lowercase in your module name.

To be able to run update functions, your module must consist of lowercase characters *only*. Unlike all other hooks, those are detected through regexes and the way it's implemented isn't compatible with mixed case.
> 13 votes

# Answer
What reported by Berdir about the module name is correct, but there is something else to consider.

I created a module (testmodule.module) that defined an update function (`testmodule_update_7001()`) in its installation file. After I installed it, the {system} database table contained the following row about my test module.

Until I don't add a function using an update number higher than 7001, Drupal will consider my module as updated. In fact, this is what I get when I run update.php.

Drupal doesn't see any update.

Now I change the installation file. This is what it contains now.

```
/**
 * Check the update functions are invoked.
 */
function testmodule_update_7001() {
  drupal_set_message('testmodule_update_7001: It works!');
}

```

This is how I change it.

```
/**
 * Check the update functions are invoked.
 */
function testmodule_update_7002() {
  drupal_set_message('testmodule_update_7002: It works!');
}

```

I run update.php again, and this time I obtain the following.

This time Drupal noticed there are updates, simply for the fact I used an update number higher than the update number Drupal recorded in the {system} table.

Bear in mind that update hooks are not invoked when a module is installed; only `hook_install()` is invoked when a module is installed.
After a module is installed, the update hooks are invoked, when their update number is higher than the update number Drupal registered when the module was installed. If your module didn't have any update hooks, Drupal will record 0 as schema version, and any update hooks you add after will be invoked.

As side note, the description shown from update.php is taken from the comment for the update hook. The code for that is contained in update\_get\_update\_list().

```
  $updates = drupal_map_assoc($updates);
  foreach (array_keys($updates) as $update) {
    if ($update > $schema_version) {
      // The description for an update comes from its Doxygen.
      $func = new ReflectionFunction($module . '_update_' . $update);
      $description = str_replace(array("\n", '*', '/'), '', $func->getDocComment());
      $ret[$module]['pending'][$update] = "$update - $description";
      if (!isset($ret[$module]['start'])) {
        $ret[$module]['start'] = $update;
      }
    }
  }

```
> 5 votes

# Answer
`hook_update_N()` is only called when a module is being updated. If you're installing it for the first time, or you uninstalled and are reinstalling, the update functions will not be called at all.

So to test your update functions the correct procedure would be to:

1. Remove (or comment out) all instances of `hook_update_N()`
2. Install the module
3. Replace (or uncomment) all update functions
4. Run update.php

Remember that your `hook_schema()` and `hook_install()` should always be in sync with your latest numbered update function.

As a side note, please check the documentation for hook\_update\_N() for how the numbering scheme works. In your example, you would want to add a version in your `testModule.info` and use that to determine what number update function you should use.
> 4 votes

# Answer
Did you try to disable, uninstall, and enable again? This just helped me to have .install running.
> 0 votes

# Answer
Try this. It might help.

```
function testModule_update_7050() {
    drupal_set_message('It works!');
    print 'Show something!';
}

```

Note: changed the number in the function.
> 0 votes

---
Tags: 7, hooks
---


title: Interface translation of custom fields

text:
# Question
Title: Interface translation of custom fields
When I translate field labels via admin/config/regional/translate/translate then my changes are happening in the frontend - but this does not work for fields which I created myself. Those fields are available for translation in the same spot but changes to them have no effect - it always uses the original text.

In my case it's about some additional fields in the registration form. I have de/user/register and fr/user/register and the pre-existing fields are in the correct language and if I do changes to them, then they are applied. But if I provide translations for the fields which I added, then they just don't show up.

I am using Drupal 7.14. On the picture, you see the custom field "wohnort". The first one has been there right after the creation of the custom field; the second one only after the Field Translation module and the i18n pack.

# Answer
Here is **Internationalization** pack for building multilingual sites in Drupal: i18n.
To translate field labels you need *“Field translation”* module from this pack. After you enable it new tab “Translate” appears on field edit page.

## Update

That's strange that you can see your field labels on `admin/config/regional/translate/translate` page, so I started an issue #1672694. I think it's a bug.

## Update 2

Fixed since Drupal 7.22
> 3 votes

---
Tags: i18n-l10n
---


# Question
Title: What consequences does "references in call_user_func_array are deprectated" have on form api?
The documentation on call\_user\_func\_array has a note, part of it quoted below

> Before PHP 5.4, referenced variables in param\_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference does not emit a deprecation notice, but it is nonetheless deprecated, and has been removed in PHP 5.4.

The function drupal\_retrieve\_form uses call\_user\_func\_array in building the form, and has this comment shortly before the call:

> We need to pass $form\_state by reference in order for forms to modify it, since call\_user\_func\_array() requires that referenced variables are passed explicitly.

While I haven't hit any serious issues running PHP 5.4, it sounds to me like anything that builds a form and then relies on getting back a modified form\_state will break on 5.4. I may not entirely understand what's happening here however.

**What are the consequences for Form API of this PHP 5.4 change?**

# Answer
> 2 votes
No expert, but here's my punt:

> Before PHP 5.4, referenced variables in param\_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference ... has been removed in PHP 5.4

means

```
function myfunction($a, $b) {
  $a++;
  $b++;
  print "myfunction($a, $b)\n";
}

$apples = 10;
$bananas = 20;

// PHP < 5.4: $b is passed by reference, not honouring the function signature
call_user_func_array('myfunction', array($apples, &$bananas));
print("apples: $apples, bananas: $bananas\n");
// PHP < 5.4: $apples = 10, $bananas = 21
// PHP >= 5.4: $apples = 10, $bananas = 20

```

and

> Furthermore, this does not apply to internal functions, for which the function signature is honored.

presumably means (though it seems a bit unnecessary?):

```
$angle = 1.5;

// Despite passing by reference, there's no chance of $angle changing as the
// function signature's honored for internal functions.
$res = call_user_func('sin', array(&$angle));

```

Letharion wrote:

> it sounds to me like anything that builds a form and then relies on getting back a modified form\_state will break on 5.4

It seems to me like this should be fine, in this case at least: we're passing a reference exactly where it's expected by the function signature (I presume this is still the right way to pass by reference where that matches the signature). However if I *am* right, then any modules with typos in their form hooks like this `function MYMODULE_form_alter($form, $form_state, $form_id)` will work exactly as expected under PHP \< 5.4, but 'suddenly' mess up on 5.4.

@Letharion: in another answer you mention you have 5.4 running: I would've thought something would've exploded by now if it wasn't passing `$form_state` by reference? But IIUC if the following works as expected in 5.4, then the code you reference should be ok:

```
function myfunction(&$a) {
  $a++;
  print "myfunction($a)\n";
}

$a = 10;

call_user_func_array('myfunction', array(&$a));
print "a: $a\n";
// We expect a to be 11 the second time for all versions of PHP.

```

My 2 pennies

---
Tags: forms
---


# Question
Title: Cannot delete / re-install sharethis module
I upgraded my Drupal to the latest version. I also did this with the modules. When I was doing this I got an error for the "sharethis" module. I got a message that told me to upgrade that module myself, so I uploaded the new module files.

But the module isn't working anymore, and when I look at the module-list I cannot find "sharethis".

This is what I see: ShareThis Block 7.x-2.2 This module creates a custom block for the ShareThis widget. Vereist: Sharethis (**MISSING**)

When trying to reinstall the module I get this message: "Sharethis is aleady installed"

So I can't uninstall/install this module! Also when deleting the directory it gives the same error. (already installed) So I want to delete and re-install a module that's not visible in the module-list.

# Answer
I had the same problem previously, turns out I had copied the module inside itself. Duplicating modules inside modules directory might give this error.
> 0 votes

---
Tags: 7, social-network
---


# Question
Title: How can i have a custom theme created by myself for multilingual site?
My website uses i8ln and it is configured to work with a large amount of languages. Using the page.tpl.php i managed to translate the website. But i had to create another custom theme for a specific path and the 404 page. So i created a page--node--23.tpl.php file and clear the cache. The file worked since the node i was trying to import the new theme was the node id defined when i created node/23. Now my problem is that i need to translate node/23 but when i click on translate and click save to save the translation another node is created and hence the page--node--23.tpl.php file is not used. How to set up drupal and able to adjust trasnaltion along with the custom themes???

# Answer
Theming pages based on node id is not the way to handle this because you will have to copy each template to the corresponding translated nids.
A better approach is to create content types based on differences (which can be different layouts as well).
You can create a content type "404\_page" for 404 pages in each language and create a template node--404\_page.tpl.php to style them. This is all node specific.

There are also page specific overrides like:

page--front.tpl.php
page--user.tpl.php
page--blog.tpl.php

Edit: Some extra information on Theme hook suggestions can be found on the Drupal 7 Theme Hook Suggestions documentation page.
> 1 votes

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


# Question
Title: User variables defined in hook_variable_info() in rules
I'm declaring the varialbes of a custom module in hook\_variable\_info(). Now I'd like to access some of them in rules. How can I do that?

The reason for this is that the Variable module gives me the chance to added fine grained access control for this values. Otherwise I would be forced to give users full access to administer rules.

Update: I found this issue: Make Drupal variables accessible with data browser in rules To be honest I don't fully understand what it is saying.

# Answer
As the Rules module uses tokens, and the Variable module implements hook\_tokens(), you should not do anything.

If the value returned from that implementation of `hook_tokens()` is not the value you would expect, in a module of yours you could implement hook\_tokens\_alter() to alter the token values returned by the Variable module.

Reading Entity property information, I get fago means code similar to the following one should be used.

```
function mymodule_entity_property_info() {
  $info = array();

  // Add meta-data about the variables exposed from the Variable module.
  $properties = &$info['site']['properties'];

  // ...

  return $info;
}

```

I didn't find any information about the parameters passed, for example, to the setter callback, even though entity\_property\_verbatim\_set() is defined as `entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info)`.

```
function entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info) {
  $name = isset($info['schema field']) ? $info['schema field'] : $name;
  if (is_array($data) || (is_object($data) && $data instanceof ArrayAccess)) {
    $data[$name] = $value;
  }
  elseif (is_object($data)) {
    $data->$name = $value;
  }
}

```

Vice versa, entity\_metadata\_user\_set\_properties() is defined as `entity_metadata_user_set_properties($account, $name, $value)`.

```
function entity_metadata_user_set_properties($account, $name, $value) {
  switch ($name) {
    case 'roles':
      $account->roles = array_intersect_key(user_roles(), array_flip($value));
      break;
  }
}

```

entity\_metadata\_user\_entity\_property\_info() uses that setter callback in the following definition.

```
  $properties['roles'] = array(
    'label' => t("User roles"),
    'description' => t("The roles of the user."),
    'type' => 'list<integer>',
    'getter callback' => 'entity_metadata_user_get_properties',
    'setter callback' => 'entity_metadata_user_set_properties',
    'setter permission' => 'administer users',
    'options list' => 'entity_metadata_user_roles',
    'access callback' => 'entity_metadata_user_properties_access',
  );

```
> 2 votes

---
Tags: rules, tokens
---


title: Equivalent of OnSessionStart for drupal

text:
# Question
Title: Equivalent of OnSessionStart for drupal
I am looking for the equivalent or at least a way to run a snippet of code only when the session starts and at now other time do i want this code run. Can anyone help me with this? Ive looked around and cant seem to find an answer and all i read about is how drupal is not good with sessions.

What im trying to do is: Retrieve a value from the URL when the session starts and set a couple variables and cookies according to that variable. I need to use those cookies throughout in order to retrieve correct results.

# Answer
> 0 votes
I guess you should use hook\_init as it's the first hook called right after Drupal setup sessions.

# Answer
> 0 votes
You could use hook\_init as @yvan suggested, but you would have to do a semaphore check as hook\_init will be called on each and every page load. Given that, it might be simpler to just use hook\_preprocess\_page which you might already be using and do something like this:

```
function YOURMODULE_preprocess_page(&$vars) {
  global $user;

  if ($user->uid) {
    if (empty($_SESSION['YOURMODULE_cookies_set'])) {
      // set your cookies here
      $_SESSION['YOURMODULE_cookies_set']='cookies have been set'; // or TRUE :)
    }
  }

  // do any other preprocess stuff here

}

```

I added in the $user-\>uid to do the check for only logged in users as sessions with anonymous users are a dark art :)

---
Tags: sessions, cookies
---


# Question
Title: How do I query for the next three dates using EntityFieldQuery or Views? (7)
This is my first question, so please don't be too harsh. I've been trying for the last couple days to solve this with no luck.

I have a content type called "Event" which contains a custom date field for the 'start date/time' of the event. What I need is to be able to list events for the next THREE days after the current timestamp.

Keep in mind that it doesn't count empty days, so if there are no events for tomorrow, for example, it won't count that as an empty day. Instead it would list the events out for the next day, and the following (assuming there are events for those days).

If I were able to access the custom date field through straight SQL, I would first get the 3 dates I need, and the query would look something like this:

```
SELECT DISTINCT(DATE(`date_field`))
FROM {node}
WHERE `type` = 'event'
AND `field_start_test_date` > NOW()
ORDER BY DATE(`date_field`) ASC
LIMIT 3;

```

I've been unable to accomplish this with Views or EntityFieldQuery. I'm also willing to create my own joins using SQL, but from what I've read, that's discouraged. I'm open to any suggestions. Please let me know if I need to be more specific.

Thanks!

# Answer
I'm just now getting back to this. I found what I believe to be the most elegant solution to my problem.

I had to break it down into two parts. The first thing I needed to do was get the next three days worth of events. I had to do it with this MySQL query:

```
$dates_query =
"
SELECT
    DISTINCT(DATE({field_start_date}.field_start_date_value)) AS start_date
FROM
    {node}
    INNER JOIN {field_body} ON ({field_body}.revision_id = {node}.vid)
    INNER JOIN {field_start_date} ON ({field_start_date}.revision_id = {node}.vid)
WHERE
    {node}.status = 1 AND
    {node}.type = 'event' AND
    {field_start_date}.field_start_date_value >= CURDATE()
ORDER BY {field_start_date}.field_start_date_value ASC
LIMIT 3;
;";

```

That query should retreive the next three dates (if any) that contain events. From there, I had to loop through the dates and pass them through this function which retreives their events using EntityFieldQuery:

```
function getEventsByDate($date)
{
    //Function to return a list of events for a specific date using EntityFieldQuery

    //start and end timestamps to query between (MySQL format)
    $start = date('Y-m-d', strtotime($date));
    $end = date('Y-m-d', strtotime($date . ' +1 day'));

    $events_query = new EntityFieldQuery;
    $events_query
        ->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'event') //get content types of event
        ->propertyCondition('status', 1) //published nodes only
        ->fieldCondition('field_start_test_date', 'value', array($start, $end), 'BETWEEN')
        ->fieldOrderBy('field_start_test_date', 'value', 'ASC');
    $events_results = $events_query->execute();

    return $events_results;
}

```

Thank you, clive for your help with this.
> 1 votes

# Answer
The query you've got in your question would be the equivalent of this `EntityFieldQuery`:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->fieldConditon('field_start_test_date', 'value', REQUEST_TIME, '>')
  ->fieldOrderBy('field_start_test_date')
  ->range(0, 3);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
}

```

I've assumed that `date_field` was supposed to be `field_start_test_date` and that the date column is a UNIX timestamp type. You'll need to make a couple of slight changes if those assumptions aren't right.
> 2 votes

---
Tags: 7, views, nodes, database
---


# Question
Title: What are Hooks, Actions and Triggers in basic terms
In basic terms what are hooks,actions and triggers.

My ideas are that hooks allow you to do something when an event takes place and that the "something" is the action.

I am having a bit of trouble figuring out where triggers fit into the equation.

# Answer
Hooks are one concept, and actions-and-triggers are a separate concept.

See What is the basic concept behind hooks? for the canonical explanation of hooks (there are some excellent answers to that question, there would be no point in trying to reproduce them here).

Actions and Triggers are best explained in Using the new Actions and Triggers functions in Drupal 6 (the concept is the same for Drupal 7).

From that page:

> What is a trigger?
>
> Triggers are Drupal events such as saving or updating a post, a user logging in or someone viewing a piece of content. Think of it like a trigger for an argument – when the trigger happens (ie. A disagreement), an Action happens (the argument). This allows you to heavily customize Drupal and paves the way to amazing new implementations of the software.
>
> What is an action?
>
> Actions are something that happens after the trigger. For example, you could redirect the user to a page, send an email notice to administrators or display a special message. This can allow you to integrate Drupal into other systems.

You might also be interested in the Rules module which is

> a replacement with more features for the trigger module in core

It's far more powerful than the trigger module and has a lot of extra features.
> 4 votes

# Answer
Triggers are events to which actions can be assigned. For example, if you look at admin/structure/trigger/node (once you have installed the Trigger module), you will notice the following page.

Actions are those available from admin/config/system/actions.

Triggers and actions are a convenient way to assign actions to system events. They are convenient because they can set through a user interface.

Drupal defines its own triggers, and actions, but third-party modules can implement new triggers, and actions through hook\_trigger\_info(), and hook\_action\_info().

As side note, the Trigger module has been removed from core, in Drupal 8. If you need a similar functionality, and you need compatibility with Drupal 8 since now, you should check a third-party module with equivalent functionality.
> 1 votes

---
Tags: hooks, actions, rules
---


title: Add user to OG based on roles?

text:
# Question
Title: Add user to OG based on roles?
I am using drupal 7, I want to add **users** having **role 'R'** to a **OG group 'G'.**

Is it possible to do that?

# Answer
Here's some code I've used, you can't add the role condition to EntityFieldQuery so the array needs to be filtered afterwards:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
      ->propertyCondition('uid', '1', '>'); // skip the anonymous and admin
  $entities = $query->execute();
  $uids = array_keys($entities['user']);
  $accounts = user_load_multiple($uids);

  // filter the users array by role
  $include_roles = array('my_role', 'my_other_role');
  $filter = function ($value) use ($include_roles) {
        $isect = array_intersect($include_roles, $value->roles);
        return !empty($isect);
      };
  $accounts = array_filter($accounts, $filter);

```

Then, to add these to your group having id $gid

```
  foreach ($accounts as $account) {
    og_group($gid, array('entity' => $account, 'state' => OG_STATE_ACTIVE));
  }

```

Hope this helps. I think this should be doable in Rules, but I'm no expert in that.
> 1 votes

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


# Question
Title: How can I reduce the granularity of login time ago in Views (from minutes to days)?
I have a view of users which displays fields, one of which is `User: Last login`. I set the **Date format** to `Time ago (with "ago" appended)`. By default, this returns values like:

* 1 hour 5 minutes ago
* 7 hours 23 minutes ago
* 3 days 17 hours ago

I am sorting the view by `User: Last login` as well, and for this I have set the **Granularity** to `Day`. For a number of reasons, I would like to prevent users from seeing precisely how long ago another user logged in if that user logged in within the last 24 hours. So instead, I would like to return values like:

* 1 hour 5 minutes ago-\> **Today**
* 7 hours 23 minutes ago-\> **Today**
* 3 days 17 hours ago-\> **3 days ago**

Is it possible to do something like this as a custom **Date format** in Views?

# Answer
In the "dull ax" approach to things, you could do a combination of things here.

1. In the Views UI, under the Date Format, there is a `If "Custom", see the PHP docs for date formats. If "Time ago", enter the number of different time units to display, which defaults to 2.` **Set this to 1.**
2. Now, Views will only output `13 sec ago` `13 min ago` `1 hour ago` etc instead of `1 day 13 hours` etc.
3. This still doesn't get rid of your specificity of the time of the day if today, eg it is going to output `1 sec ago,` `12 min ago` or `3 hour ago,` etc.
4. To take care of that, you can create a views template for that field, eg, here in D6 World it would be something like `views-view-field--NAMEOFVIEW--login.tpl.php`.
5. In there, do something along the lines of:

```
if (strpos($output, 'sec') !== FALSE || strpos($output, 'min') !== FALSE || strpos($output, 'hour') !== FALSE) {
  print t('Today');
}
else {
  print $output;
}
```

which will print out `Today` if it sees a sec, min or hour, or the default if not, eg, it sees day, week, month etc.
> 6 votes

# Answer
I think the logic required for of "Today" vs "3 days ago" rules out using a regular Date format. If you stuck to "X days ago", it would work, but that's not as pretty.

I would implement a custom field formatter that did what you wanted, as it's an easy way to get high control over output.

There is a drawback in this case, since you don't actually have a proper field for "Last login", you need to add an extra "dummy" field. It's up to you if this is an acceptable work-around, but I've used this several times myself to no I'll effect. If you put it on a end-user editable entity, you will probably want to deny access to the field for users though, so it doesn't clutter the UI.

To keep topics separate, I posted that as a separate question. How do I make the output of field X look like Y?.
> 2 votes

---
Tags: views, datetime
---


# Question
Title: Is it possible to make Drupal administrator more comfortable
Is it possible to make Drupal administrator more comfortable? an GUI with icons instead of menu links?

# Answer
There's always the Root Candy theme which makes the admin interface look like this:

It also has a bunch of other features:

* Supports node/add /edit pages
* Re-colorable
* Icons
* Top navigation by role
* Simple dashboard
* 3 column fluid or fixed layouts
* Rootcandy dark sub-theme
* Icons in compact mode
* Sliding region
> 1 votes

---
Tags: theming
---


title: shadowy images question

text:
# Question
Title: shadowy images question
http://themeforest.net/item/converge-the-best-premium-drupal-theme/full\_screen\_preview/405072

I am trying to make a d7 version of this slider. I have enabled KWICKS VIEWS but I cannot seem to get a 3d effect, like it has here. Does anyone know what kind of css this uses? what i create and list class and enable it in VIEWS?

I used firebug to inspect but didnt see anything obvious. THANK YOU

--newbie

# Answer
It's using a transparent png to fade out the background and give that box shadow type effect on the right. Look at class fade-bg and you'll see how.
> 1 votes

---
Tags: javascript
---


# Question
Title: How to force a theme to use a sitewide custom menu
Ok so Im coming from wordpress where I could just hook a menu into the header of every page and create my own custom menu. I'm trying to do the same with drupal but it's so confusing! Im building my own custom theme so if I can start small with this question. How can I insert a sitewide menu with a custom template onto every page of the site. Something like this.

```
<div id="top-menu">
   <---hooked in functions from the template.php--->
</div>

```

# Answer
> 0 votes
**How can I insert a sitewide menu?**

You can use Context to insert menu blocks into regions. Contexts can be set to be site wide. Make sure that your theme supports the region into which you are inserting the menu block. The region should be defined both your theme's .info file and also it's relevant templates (generally the page template).

**Making a menu with a custom template**

You can use the devel\_themer module to sniff what templates you can implement to override the menu's default theming.

---
Tags: routes, theming
---


# Question
Title: Where is body field label stored in database
Due some caching problems I can't immediately change field label via /admin/structure/types/manage/page/fields. So I thought that I will able to do it from mysql but I can't find it. Any help?

Please note, that I have developement state here /admin/config/development/performance - no caching at all, no compressing

# Answer
> 6 votes
The field label, together with all other settings are stored as a serialized array in the field\_config\_instance table.

Manually changing a serialized array is usually a bad idea, it can destroy the data in there if you don't know what you are doing.

---
Tags: 7, caching, entities, database
---


title: Embedded nodes and views

text:
# Question
Title: Embedded nodes and views
Let's say I have a general content type called "Zoo". A Zoo may have several animals (animals will have a title, image, and description). Now at first, it may seem like I should just have an "Animal" content type and then somehow relate them, but all animals are unique to the zoo. (If two zoos contain a tiger, they will be completely distinct tigers, with their own images/titles/descriptions).

I have a view (already working), that lists the animals. I'd like for the animal titles to link to a page where the animal information (image/title/description) is available.

Because each image (animal) needs it's own respective title and description, and a Zoo may have several images (animals), I've tried to find a way to relate the information, since simply adding fields to the Zoo content type is fruitless.

The closest module I've found is Field Collections, and I'm technically able to reference the information correctly. The problem I'm having with it is, in the view list, I can't figure out how to show the titles of the animals and have them link to somewhere useful.

This "useful" place they link to is what I referred to previously, somewhere with the animal's information (image/title/description).

I know this example seems a little convoluted, and almost like I should use the node reference module. But the real use case requires not having to make separate nodes in separate areas and relating them, but rather making all of them at one time.

# Answer
> 2 votes
I would advise node References and Entity Views Attachment

1. Create 2 content types: 1) Zoo - 2) Animals
2. Animals has a "Node reference" to a Zoo
3. Create 2 views: 1) Zoo - 2) Animals - Attach entity contents by relating them and contextual filters on nid

This way you can create Zoo pages \[node\] with all the animals in the zoo On the animal pages \[node\], you can show which zoo(s) the animal belongs

You can also create pretty overview \[views\] pages

# Answer
> 0 votes
If I get you right, you don't need any properties for the zoo. If this is true you could handle the zoos just as a vocabulary with a term for every zoo. Or to get even a simpler structure just create a text field with a list of zoos to choose from.

But to be honest I think that it would give you a much bether data structure to create a content type for zoos and a content type for animals and relate them using node reference. Maybe you could tell us more why you don't want to do this.

# Answer
> 0 votes
If you want to be using Field collections, then I think it will be difficult to display each animal on a separate page (That could be possible if somehow you can configure the "Multiple Fields Setting" of Views dynamically). However, if you want to display only the titles of the "animals" in the "zoo" node and then link the titles to a page that displays all information about all the animals in the zoo, then that is possible.

1. Install the "Entity view modes" module (http://drupal.org/project/entity\_view\_mode). This will allow you to add more view modes to your Field Collection. Add a custom view mode e.g. "Title only". Now in the display settings of your Field Collection, enable custom displays for the "Full content" and "Title only". "Full content" will have all the fields, "Title only" will have just the "Title" field.
2. Your main view that displays the title of the animals should be already having a Contextual Filter to the Content Id (Nid). In your main view, select the Field Collection field and select the Formatter as "Fields only" and the View mode as "Title only". Then under the "Rewrite results", check "Output as link" and put the path as "zoo-animals/!1". The path "zoo-animals" is described below.
3. Create another page view and put the path as "zoo-animals/%". Add a Contextual Filter to the Content Id. Select to display Fields and then add the Field Collection field, this time selecting the "Full content" view mode.

This way, you have one view, with the zoo content that lists the animal titles which are linked to the 2nd view that displays the full details of the animals.

# Answer
> 0 votes
A solution I used recently was references \+ nodereference\_url, you may set it up something like the following:

1. The INDIVIDUAL ANIMAL node type has a field ZOO which is a node reference to a specific zoo
2. The INDIVIDUAL ANIMAL type also has a field ANIMAL SPECIES which refers to a taxonomy term
3. When visiting the ZOO page as a content administrator you could click "ADD INDIVIDUAL ANIMAL" and you would need to select the species

This way you get to define generic properties and fields of an ANIMAL SPECIES while allowing you to define custom fields for a specific animal. The downfall of field collections module is that it does not give you fully fledged nodes to manipulate.

# Answer
> 0 votes
I recommend that you stick to the field collections approach and either:

1. Display each animal's collection in its entirety on the Zoo page and use JS to hide appropriate fields and display them upon click perhaps in a lightbox.
2. Write some code that mimics the node display to display specific field collections based on their own custom URL. I don't believe that this should be too difficult to write as there should be some simple API calls that you can leverage.

Good luck!

# Answer
> 0 votes
On a recent project I did exactly what cateye describes (node reference + entity views attach) but add in nodereference\_url like Duncanmoo mentions. It displays an "Add Animal" button on the Zoo page and automatically fills in the node reference to the parent Zoo on the Animal page. I think it's far easier than using Fields Collection. Animals really are a content type and not extra fields in a Zoo.

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


# Question
Title: How can I create two distinct sets of exposed filters for use in a single view?
I am wondering if there is a way to create two distinct sets of exposed filters to use on a single view. The reasoning is that I have a view for content of a given type. I have a set of views exposed filters placed in the header of the site that is used as a search form, which displays its results within this view. However, once the user submits a search, I would like them to be able to further filter their results based on aspects of the resulting nodes. This would somehow require a second set of exposed filters for the same view. As far as I can tell, as long as I have my exposed filters in a block, all filters that I add are placed within that block. Is there some way to get around this, and display two sets of filters, in different places, for a single view?

# Answer
> 1 votes
It looks like what you are describing is faceted search. In Drupal, a good solution for faceted search is using Apache Solr along with the Apache Solr module. Here's a video tutorial on how to install Solr for Drupal. Here you can see an example of faceted search working on a site I built for the company I currently work for.

---
Tags: views
---


# Question
Title: Views caching not working for Taxonomy listing pages
I was able to turn on Views caching (both time-based for a few, and content-based for others) successfully. However, for my "taxonomy/term/%" pages (and their respective "/feed? pages as well) if I turn on any kind of caching, I get an empty page. Not the WSOD, but just the title and no listings. Further, the pager is all screwy - the page numbers point to pages for OTHER taxonomy terms. I can't seem to find a pattern.

I did find this discussion on d.o but it's not much help: http://drupal.org/node/1430650

What's killing me is that these pages are seriously about 98% of my site's traffic - literally tens of thousands of page views per day. If I can get these cached it would give me a huge performance increase.

Any ideas?

# Answer
Have you tried doing a print\_r(), dpm(), etc. on the cache\_get() and cache\_set() functions to see what's going on? The output of this tends to be somewhat verbose, so I generally like to do an error\_log(), then go to the PHP error log and see all the calls to cache\_get and cache\_set to see if I detect a pattern. This would give you a concrete idea of what and what is not getting cached.
> 0 votes

---
Tags: views, caching
---


title: Connect Views and a second database

text:
# Question
Title: Connect Views and a second database
Lets say I have two (mysql) databases `drupal` and `book_data`.

The book\_data database has a table called `books` with three columns: `isbn`, `title`, `pages`.

My user entity has a field called `field_isbn` where every user may enter multiple isbn numbers of books he read.

The next step would be to tell views about the `books` data structure some how.

In the best case views would allow me to add a relationship between the `field_isbn` and `book_data`.`books`.`isbn` field so I am able to:

* sum up the `pages` to see how many book pages a user has read
* sort/filter for `books`.`title`
* expose theses filters

Is this possible at all?

# Answer
> 1 votes
I havent done this but I have seen code to make Views in D7 work with remote database tables. If you can get Views to see those tables and fields -- a bit more work should be able to allow you to filter/search through this stuff from Views:

Fields with Multiple Entries in Views w/ External Data Source

It looks like you just have to give drupal a `database` key for your remote database connection defined in `settings.php` per field description. The rest looks like a typical implementation of hook\_views\_data().

# Answer
> 0 votes
Establishing a relationship between your users' field and the book entities would definitely be possible, and rather easy with Views - if both the user and book entity where present in Drupal. If you have limitations in which you *must* store the book data in a separate database, that's O.K., just consider creating an import process in which you convert those books into Drupal nodes with custom fields. That way you will be able to harness all the power that Views relationships have to offer. You can also consider stealing some data import ideas from *The Economist's* migration to Drupal.

---
Tags: views
---


# Question
Title: Drupal 7 and Views 3: Page Display and Random Appended Arguments in URL
This is going to seem like an odd question. I am not sure if this is the way Views is meant to work but I want to see if I can turn it off.

Say I have a View with a Page Display with a defined URL like so: /testimonials

The Display takes not arguments what so ever. Here is the problem: I can now access this view using URLs like this:

* /testimonials/5898
* /testimonials/hello/what
* /testimonials/stupid/appended/data

I can't for the life of me figure out how to turn this off in Views. Any ideas?

# Answer
> 0 votes
5898 is just an extra URL argument in View's point of view. Views doesn't have the ability to throw 404 pages because there are "extra" arguments in the URL. Views ***does** throw 404s when there is **no** argument in the URL* (if configured that way). In any case, you can implement something like hook\_views\_pre\_view() and redirect the user to a separate 404 page if you see that extra arguments are found in the URL. This should take like 15 minutes for a Drupal developer to do.

---
Tags: views
---


# Question
Title: I get the following error message while updating a Drupal site
I keep getting this error when I try to update Drupal. I have no clue what it means; it seems I have a missing column.

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'base.access\_exposed' in 'field list':
> SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access\_exposed AS access\_exposed, base.data AS data FROM {rules\_config} base WHERE (base.status IN (:db\_condition\_placeholder\_0, :db\_condition\_placeholder\_1, :db\_condition\_placeholder\_2)) ; Array ( \[:db\_condition\_placeholder\_0\] =\> 3 \[:db\_condition\_placeholder\_1\] =\> 2 \[:db\_condition\_placeholder\_2\] =\> 6 ) in EntityAPIController-\>query() (line 152 of /opt/readyby21.org/public\_html/sites/all/modules/contrib/entity/includes/entity.controller.inc).

# Answer
> 1 votes
According to http://drupal.org/node/1489394 some users experienced this problem when updating their rules module. It looks like you'll need to update your rules, entity and internationalization modules all need to be updated to the latest versions (7.x-1.5 for internationalization and 7.x-1.0-rc2 for entities). If you already have, try only updating those modules, before attempting to update the rules module (you can disable the rules module. This should also solve the problem, but I assume you're using it for something or other).

As BetaRide points out above, checking into your web logs may shed some additional light on the problem, in case the above doesn't solve the problem.

---
Tags: updating
---


# Question
Title: Generate image styles on upload or in some other memory-conscious fashion?
I have a **D7** site that is hovering around 55mb on devel\_shutdown(); for most uncached pages and has a lot of migrated content that has images linked to various styles around the site, many of which are currently ungenerated.

If I bump PHP memory usage allowance to 130mb (I'm on Dreamhost shared hosting, so 150mb is the top end for any individual process), images generate fine. If I leave it at the unmodified 90mb, image generation starts to fail.

It seems there are two options:

a. Get more RAM, through a virtual private server or some other hosting-related fix.

b. At my coworker's suggestion, find some fiddly way of getting images to generate ahead of a user running into them.

In terms of option B, we're using, *gasp!*, WordPress for an inspiration, which seems to handle images more intelligently in low-memory situations (Heresy! Madness! Spartaaaaaa!).

To explain — after the page has loaded and PHP has released memory, thumbnails are generated **as they are uploaded**, noticeable when WordPress says "Crunching" during the upload process. This way, there isn't any delay when a user then views them, and there's no worry that the combined memory load of the CMS and the image library will cause one of them to fail.

Is this at all possible in Drupal? Would a module like Cache Warmer do this if set up in a cron job? Is there even any benefit to doing things this way?

# Answer
> 5 votes
I don't like the "lazy" image style generation either. After I imported 100,000 photos I batch created image styles for all of them. I just looped over each image and created the 5 or 6 styles for each image.

I noticed that there isn't a big penalty for looping over images that already have all image styles generated. So you could just run a cron, say every hour, that loops over all images created or updated within the last hour (or two to be save) and create the image styles.

I used something like this to generate the image styles, just select which ones should get generated:

```
    foreach(image_styles() as $style) {
        if ($style['name'] = 'thumbnail' || $style['name'] = 'medium'){
            $dest = image_style_path($style['name'], $uri);
            print ' '.$style['name']. ', ';
            if (!file_exists($dest)) {
                image_style_create_derivative($style, $uri, $dest);
            }
        }
}

```

You'll just need to $uri variable, in my case I get it directly from the file\_managed table since I ran a batch job.

# Answer
> 2 votes
http://drupal.org/project/imageinfo\_cache This module generates imagecache presets on file upload. So yes it is possible and yes we use this in production and have seen some massive speed improvements from it. Currently D6 only. Totally configurable so certain file fields only generate these presets.

Also for D6 imagecache are some drush commands to generate various presets. http://drupal.org/node/587086

---
Tags: 7, caching, performance, media
---


# Question
Title: Easist way to moderate an image via a php GET callback request?
I want to add some code that allows me to use an image moderation service called Webpurify http://www.webpurify.com/image-moderation/documentation/callback/. I can send the url request using a rule (or using a hook via a custom module) and they send a callback GET request to a URL I specify, with the imageid and the moderation status directly in the url like this - http://www.yoururl.com/imgcallback.php?imgid=43534dfdfg3453sffsd&status=1. What's the best way to setup a call back page or url in Drupal? It's very simple it just publishes the node if accepted and deletes it if not.

# Answer
> 1 votes
In a custom module, you would create a menu item and callback:

```
function YOURMODULE_menu() {

   $items=array();

   $items['imgcallback'] = array(
     'title' => 'Webpurify Response',
     'page callback' => 'YOURMODULE_imgcallback',
     'access callback' => TRUE,
     'type' => MENU_CALLBACK,
   );

   // create any other custom menu items here

   return $items;

}

function YOURMODULE_imgcallback() {

   $imgid=$_GET['imgid'];    // this is the ?imgid=....
   $status=$_GET['status'];  // this is the &status=...

   if ($status) {
     // this is where you would publish the node, but for now...
     return 'Webpurify liked image ' . $imgid;
   }
   else {
     // this is where you would delete the node, but for now...
     return 'Webpurify didn\'t like image ' . $imgid;
   }

}

```

Clear your caches and now you will have a url on your host:

```
www.YOURHOST.com/imgcallback?imgid=foobarbaz&status=1

```

that will return `Webpurify liked image foobarbaz` and

```
www.YOURHOST.com/imgcallback?imgid=baddabing&status=0

```

that will return `Webpurify didn't like your image baddabing`

It's up to you to change all of that to the publish/delete logic/functionality as I don't know how you are mapping imgid to node, etc. Just realize if your users can somehow figure that out, they can/could/would/might call this url directly with whatever status they desired.

# Answer
> 1 votes
You can specify a path with hook\_menu and let the call back point to this path. The call back method of the menu entry handles the call from the service, does any processing needed and finaly does a drupal\_goto to your node.

Have a look at the commerce adyen module. It provides two entries in hook\_menu which handle call backs from the adyen payment gateway.

---
Tags: 7, media, rules
---


title: Can I modify guestbook.module safely?

text:
# Question
Title: Can I modify guestbook.module safely?
I want to make a few changes in the HTML output by the guestbook module. For example, I want to enclose the submitters name in a `<div>` or a `<span>` (so I can style it better).

What's the best way to do this? The only option I can think of is to modify the guestbook.module, but that could cause issues down the track.

# Answer
> 4 votes
Changing module code is usually a bad idea because it makes it hard to impossible to update to a newer version of the module.

Without knowing the structure of that module, changing the HTML/output should always be possible by overriding theme functions, which you can do without changing the original code.

See: http://drupal.org/node/11811

# Answer
> 1 votes
Modifing core or contrib modules is something you should avoid. It will cause problems or at least tedious additional work when you want to update.

If the module does not offer any possibilities to theme the output to your needs I'd sugest to add a feature request in the modules issue queue (check whether it does not already exist). Then go and make the output themeable and add your changes as patch.

This involves getting familiar with drupal theming for module developers and the drupal contrib developement process which could take some hours. But you'll win in the long run. If you're patch is accepted the feature will be part of the module this free's you from maintaining and mergin in your changes for every update.

---
Tags: 7
---


# Question
Title: How to limit a user to one vote when using Fivestar?
In Drupal 7 I have enabled the fivestar module to allow users to vote in their comments. The results are tallied and give an average vote. Cool stuff.

Problem is a person can just keep voting over and over in each new comment or reply.

How do I limited a person to just one vote per node, via the comments. In other words, once they have voted, either the stars disappear, or the persons other vote is the default and cannot be edited?

Thanks

# Answer
You can easily do this using a custom module that contains code similar to the following one.

```
function YOURMODULENAME_print_rating($nid, $fivestar_widget) {
   $path = drupal_get_path('module', 'fivestar');
   drupal_add_js($path . '/js/fivestar.js');
   drupal_add_css($path . '/css/fivestar.css');
   $voting_message = '';
   $output = '';
   $is_login = user_is_logged_in();
   $rating = votingapi_select_single_result_value(array(
       'entity_id' => $nid,
       'entity_type' => 'node',
       'tag' => 'vote',
       'function' => 'average',
   ));
   if ($is_login) {
     if (isset($rating)) {
       $voting_message = "<div>You have already rated this.</div>";
       $output = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')) . $voting_message;
     }
     else {
       $output = render($fivestar_widget);
     }
   }
   else {
     $fivestar_links = l('Login', 'user/login') . ' or ' . l('Register', 'user/register');
     $voting_message = "<div>Only registered user can rate this content type.<br/>$fivestar_links to rate this content type.</div>";
     $output = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')) . $voting_message;
   }
   return $output;
 }

```

Use the below snippet in your node template file.

```
hide($content['field_fivestar_rating']);// This line will hide the stars which are coming from the fivestar module.
print YOURMODULENAME_print_rating($node->nid, $content['field_fivestar_rating']);// This will print the fivestar.

```
> 2 votes

---
Tags: 7, comments, rating
---


# Question
Title: Where do I set which template file to use for a block?
I know I can just override block.tpl.php using the normal template system. But is there a way to set the tpl file when I define a block in my module ?

I thinking of an equivalent to this:

```
function theming_example_theme() {
  return array(
    'theming_example_text_form'  => array(
      'render element' => 'form',
      // In this one the rendering will be done by a tpl.php file instead of
      // being rendered by a function, so we specify a template.
      'template' => 'theming_example_text_form',
    ),
  );
}

```

# Answer
> 3 votes
Most of the times I just do

```
$block['subject'] = t('My block title');
$block['content'] = theme('my_custom_theme', $block_content);

return $block;

```

from `hook_block_view()` function if you're making a module that creates a block. The theme function `my_custom_theme` can use a template file such as `my-custom-theme-block.tpl.php`. Also you can suggest theme hooks through `hook_preprocess_block`. Just check for the delta of your own block and set a theme hook there.

```
function HOOK_preprocess_block(&$vars) {
  if ($vars['block']->delta == 'my-block-delta') {
    $vars['template_suggestions'][] = 'my-custom-theme-block';
  }
}

```

---
Tags: theming, blocks
---


# Question
Title: How do I add venue location automatically when user selects a venue?
Does anyone know how I can allow a user to select a venue (such as a night club or restaurant) from a node reference autocomplete field and have the address of the venue also displayed. This assumes that the venue is already in the system along with the venue's address.

The problem I am trying to solve is as follows: my website allows users to post a comment about a venue which is already in the website's database. I want the user to be able to enter the comment and type the name of the venue from an autocomplete box. I don't want the user to have to enter the address of the venue rather have it auto populate.

Any help on this would be greatly appreciated.

Thanks,

Paul

# Answer
> 1 votes
EDIT: Just realized that this post is a few months old. Hopefully you already found a solution to your problem. If not, maybe this can be of use.

If I'm understanding correctly, you would like to have the address appear in the *published* comment, and comment is a content type. I emphasize published because this method only allows the information to appear in the published node and not within the content creation form (which is unfortunate, because I've been searching for this functionality for my own site). Assuming the above is the case, then I think the best way to do this would be with Rules. These instructions should get you close, I think, but I haven't used the functionality in quite this way before. Once installed:

* Add a field in your comment content type that matches the address/location field in your venue content type
* Go to admin/config/workflow/rules
* Add a new rule, and under "react on event" select "After saving new content"
* Add condition "content is of type", and select your comment content type
* Add action "fetch entity by id", and in the data selector input/select "node:your-reference-field:nid"
* Add action "set a data value", in the data selector drill down to "node:address-field-of-comment-content-type", click continue, click on "switch to data selection" in the new value area if it's not already selected, and then on that data selector field drill down to "entity-fetched:address-field-of-venue-content-type"
* Save changes

This should grab the address from the referenced node before the comment is saved, and populate the comment's address field with the referenced venue's address, after the user clicks the save content button but before it is saved. You're probably going to want to hide the address field in the comment content creation form so that users can't mess with it. It will more than likely just confuse them since they are not directly editing it. Hopefully this helps you out. Like I said before, I haven't used it in quite this way, but I have used it in a similar fashion.

You also might want to check out Entityreference Prepopulate. It allows you to fill an entity reference field automatically within the url. So, if you have a link on the venue page to create a "comment" for the venue, the you can use this module to automatically populate the entity reference field with the venue, making it so that users don't have to make the selection themselves.

# Answer
> 0 votes
If you want the address to show up on the published comment:

* in Content Type \> Comment Display
* use Format: Rendered Node (teaser)
* set up the Venue teaser to show the title & address

If you are already using the Venue teaser in another way, then use a Rendered View instead. First set up a view showing the Venue title and address.

---
Tags: comments
---


# Question
Title: What does test status postponed for a patch on d.o mean?
I've added a patch for the rules module. The patch detail page says the test status is *postponed*.

What does that exactly mean? Is there anything I should do to get the patch tested?

# Answer
The problem is that the current Rules branch is currently failing an already commited test. While this *should* obviously not be possible, as tests should be green before they are commited, rare circumstances will cause this to happen from time to time.

Since an already existing test *does* fail, we *know* that testing with your new patch will also fail, whether your patch is correct or not. Thus all tests are postponed until the existing and breaking test is fixed.
> 7 votes

# Answer
To add to what Letharion said, these are the Rules 7.x-2.x tests that fail.

The branch tests are the tests included in the module. To see the test ran for a module branch, you can check this page; the modules are ordered alphabetically, and by their version.

As the project tests are already failing, it doesn't make sense to test the patch; they would fail even when the patch would be correct.

The purpose of the project tests is exactly to verify that changes in the code don't introduce errors. They can be run after a commit, or before a patch is committed.
> 4 votes

---
Tags: community-official-site, version-control
---


title: Paging data from a web service

text:
# Question
Title: Paging data from a web service
I'm working on a module that uses soap to fetch data from a webservices. Data are ok, and I'll use theme functions to display them as a list. I should also to split results in pages, like views. Is there a way to add a pager?

# Answer
> 1 votes
Use something like

```

 foreach ($result as $node)
{
    $rows[] = array('data' => array("".  $node  ."..."));

    $html = theme('table',array('header' => $header,'rows'=>$rows,'caption' => '','sticky' => FALSE,'empty' => 'No details found...','attributes'=>array('class'=>'table-class'),));
    $html.= theme('pager',array('tags' => array(),'quantity'=> 10));
}

```

---
Tags: paging
---


# Question
Title: Article view with links to other articles
So I'm trying to create a view which displays the most recent article belonging to a specific taxonomy term and pulls out just the links to other articles which have the same term.

I want to display the article content and below that 4-5 links to other articles of the same taxonomy. I want to display this view as a block.

Is this possible? How can this be done?

# Answer
> 0 votes
Add a contextual filter: Content: Has taxonomy term ID (with depth), for displaying related articles

---
Tags: views, taxonomy-terms, blocks, navigation
---


title: Insert into table from Drupal 7

text:
# Question
Title: Insert into table from Drupal 7
I am very new to Drupal.

* I have a table called **`test`** with two fields: (int) id and (varchar) text
* When a new user signs up I want to store data on the table **`test`**

I'd like to know how can I do that. I really don't know how to start researching about this.

I think the most approximately that I have found is Overriding user login. I presume that it does what I want but in the pre-process functions I have to insert into the database. Question here how do I insert into the database from Drupal?

Could anyone clear my thoughts or point me to any good reference.

Thanks.

# Answer
> 5 votes
You don't need to actually override the login process to do this; The user module provides a hook (`hook_user_insert()`) which gets invoked any time a new user is created.

As far as inserting into the database goes, the best place to look first is the Database abstraction layer documentation which goes into detail about the various database methods available.

In this specific case it's the `db_insert()` function you're looking for. Your code might look something like this:

```
function MYMODULE_user_insert(&$edit, $account, $category) {
  db_insert('custom_table_name')
    ->fields(array(
      'id' => $account->uid,
      'text' => 'some text'
    ))
    ->execute();
}

```

This code would go inside a custom module; if you're not familiar with creating one of those check out the Module developer's guide which will tell you everything you need to know.

---
Tags: database, users
---


# Question
Title: Global site variables to be used in node fields and menu item
I'm looking for some way of having variable defined by admin which can be displayed in some fields or nodes.

Real use case: I have that specific date that changes periodically. And I want it to appear in some places, ie. within text of some node body (with possibility of fixing the variable ie. putting some text instead of date, but it's not a matter of my question).

My guess: create some hook to preg\_replace all occurences of some string, ie. ##VAR\_VARNAME1## with certain fields of nodes or within field texts. But actually I know that it will occur mainly in 2 or 3 places within my website (which is for sure body of one specific node and text of 1 menu item).

Any ideas to make this efficient and quick?

edit: I believe it's easy to do with defining new block.. but how about way I mentioned above..

# Answer
> 2 votes
Try the Custom Tokens extension to the token module. Here is a quote about it (from the module's project page):

> ... gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.
>
> Versions 7.x-1.x and previours relied on PHP evaluation to build custom tokens.
>
> The new 7.x-2.x relies on input filters. While still allowing for PHP tokens through the D7 core PHP filter module, administrators can permit only HTML or plain text custom tokens.

---
Tags: 7
---


# Question
Title: How to expose edit link on editable areas for all authorized users?
The ideas is that in Drupal 7, on mouse hover on a node (or block) a edit link appear at top corner of the node (or block), just like the cog that appears for admin when s/he hovers on editable areas.

By exposing the the edit link on hover, we can create a much better user experience, for users that are not necessarily familiar with Drupal backend. I appreciate your hints.

# Answer
> 4 votes
There are two ways to do this.

The "gears" feature is from the "Use contextual links" permission on admin/people/permissions. If you give that to the appropriate roles, your users should see that.

Personally, I don't like the **Contextual Links** feature, mainly because the markup it adds can mess with theme layout when you have other positioning going on. I typically add in my own edit links to pages, usually below the content somewhere. I will sometimes use a `display: none` on them, and then have a link in the footer menu that shows them all via jQuery.

---
Tags: blocks, nodes
---


title: Redirect to cck url on registration?

text:
# Question
Title: Redirect to cck url on registration?
I have a node that has a cck field that has a link, when the person clicks on it, I need them to sign up then redirect to that link.

Is that possible?

logintoboggan, rules and login destination cant achieve this, they only send to one defined page.

# Answer
When you redirect to the login or registration page you can add a `destination` GET parameter to the url, which Drupal will redirect to after form submission.
> 0 votes

# Answer
Create a custom module and implement hook\_menu

```

function YOURMODULENAME_menu() {
  $items = array();
    $items['checkuser'] = array(
      'title' => '',
      'page callback' => 'check_user',
      'access arguments' => array('access content'),
  );
  return $items;
}

fucntion check_user() {
  $destination = $_GET['destination'];
  $is_login = user_is_logged_in();
  if($is_login) {
    drupal_goto($destination);
  }
  else {
    $options = array('query' => $destination);
    drupal_goto('user/register', $options);
  }
}

```

Use below snippet in your node template

```

l('Title', 'checkuser', array('query' => array('destination' => 'destination_url')));

```
> 0 votes

---
Tags: entities
---


# Question
Title: How to insert a view in the body field of a node?
Is there any way to insert a view in the body field of a node?

Something similar to the insert module for inserting images in the body field.

# Answer
I've found this module Insert View

I haven't tried yet. Let me know if it fits your request.

I found this as well Views Reference I tested both and I think the second is more appropriated for you.
> 4 votes

# Answer
```
<?php
  $viewName = 'view_name_here';
  print views_embed_view($viewName);
?>

```
> 2 votes

# Answer
also you may create chainable tokens that will replace a token with view output
> 0 votes

---
Tags: views, entities
---


# Question
Title: new comment notification in teaser mode in links
Yesterday I saw "2 new comment" in teaser view in one of news in my Drupal-based website. when I click on news and read it and return to news list, the notification was gone. Now I want know where Drupal create this?

# Answer
There is `history` db table in Drupal: *"A record of which users have read which nodes."*
It contains last time when user viewed a node. This data allows to show new content and new comments to user.
Comment module uses it to determine how many new comments appeared while user was not on the node page in `comment_num_new()` function.
Link “2 new comments” was added by this code in `comment.module` file through `hook_node_view()` hook:

```
  // Show a link to the first new comment.
  if ($new = comment_num_new($node->nid)) {
    $links['comment-new-comments'] = array(
      'title' => format_plural($new, '1 new comment', '@count new comments'),
      'href' => "node/$node->nid",
      'query' => comment_new_page_count($node->comment_count, $new, $node),
      'attributes' => array('title' => t('Jump to the first new comment of this posting.')),
      'fragment' => 'new',
      'html' => TRUE,
    );
  }

```
> 1 votes

---
Tags: 7, comments
---


# Question
Title: How to allow a role to block other users?
Looks like there still isn't a great anti-spam solution for D7 ;-(

I already have flags for nodes and comments with automatic unpublish once enough users flag it.

I want to be able to give users of a certain role the permission to block other users and possibly unpublish any content of that user.

I don't see a permission for "block user". How can this be done?

# Answer
There isn't a specific "block user" perm. Out of the box there's only the *administer users* perm, which in turn grants the role the ability to add/edit/remove other users. If you want a *block user* permission, you could define your own *block user* permission, then grant your custom permission to whatever user/roles you want. Here's the basic recipe:

* Implement `hook_permission`, and add the *block\_user* permission there.
* Implement `hook_menu_alter`, and modify the `'access callback'` argument for the `user/%/cancel` and `user/%/cancel/confirm/%/%` menu items to point to your own custom access callback function. You might also need to change the `'page_arguments'` setting to point to your own form instead of the default, if the default user cancel form doesn't cut it for you. The default form called is user\_cancel\_confirm\_form().
* In your custom access callback, you can use user\_access() to verify that the current user/role has access to the block user permission.

Before you embark on this, you might be interested in checking out:

* The `user/%/cancel` and `user/%/cancel/confirm/%/%` entries in the `menu_router` database table. It tells you what are the access callbacks and all other important details of these paths.
* The `user_edit_cancel_submit()` function on the user.pages.inc include file. This is the Form API `#submit` function that gets called when you hit the *Cancel* button on any user user's account.
* The different account cancellation methods exposed in user\_cancel\_methods(), user.pages.inc. There's four cancellation methods. I think \*user\_cancel\_block\* and \*user\_cancel\_block\_unpublish\* are the safest methods.

Sample code:

```
/**
 * Implements hook_permission.
 */
function rallen_permission() {
  $perms = array();
  $perms['block_user'] = array(
    'title' => t('Block user'),
    'description' => t('Disables accounts and hides their contents.'),
  );
  return $perms;
}

/**
 * Implements hook_menu_alter.
 */
function rallen_menu_alter(&$items) {
  $target_paths = array(
    'user/%/cancel',
    'user/%/cancel/confirm/%/%',
  );
  foreach($target_paths as $menu_item) {
    $items[$menu_item]['access callback'] = 'rallen_block_user';
  }
}

/**
 * Custom access callback for blocking users.
 */
function rallen_block_user() {
  if(user_access('block_user')) {
    return TRUE;
  } else {
    return FALSE;
  }
}

```
> 1 votes

# Answer
Sounds like you must do it by custom module.

For blocking user, use db api and just change *status* column (users table) value to 0.

Similar things is for unpublish selected user content. All you need is in *node* table.

So you need two UPDATE statement for this job. That's all.

BTW. Do you try mollom for anti-spam? You can specify any form to work with mollom. Maybe you can configure this module to work with logged in users.

Mollom has nice permission, e.g.: Bypass Mollom protection on forms, so you can choose which role may bypass spam checking or not. Then just try to find any *hook* declared by *Mollom* module that allow you to block user when spam is detected.
> 2 votes

# Answer
Before writing code I'll probably add a user flag to the profile that is only visible to that special rule. When you flag a user it would fire a rule to block that user.
> 0 votes

---
Tags: 7, users, advertising
---


# Question
Title: Check if user can edit node with certain ID
I need to know a function or a way to find out if a user can edit a certain node.

For example I have the nid 200 and the user foo has logged in, I want to check if he is able to edit node/200.

Thanks

# Answer
> 12 votes
You can use `node_access` to do this:

```
$node = node_load(123);
$account = user_load(456);

if (node_access("update", $node, $account) === TRUE) {
  do_something_awesome();
}

```

If you look at the source for `node_access`, you will see that the `$node` argument can also be a `$nid`. This is how the path for the edit pages get checked (see the 'node/%node/edit' entry in `node_menu`).

---
Tags: 7, users
---


# Question
Title: Profile types with unique fields (Profile2?)
I'm trying to achieve the following with Drupal 7:

* Admin user will create all user accounts, users can not
* Admin has a choice of two profile types (Coach, Player)
* Coach and Player's user registration forms will have different required fields

I've been able to successfully setup the Profile2 module, and create two profile types. However, when I add fields to the Coach's profile those fields also show up in the Player profile when I go to /admin/people (add-user player-profile button)

Perhaps I'm going about this the wrong way, or perhaps I have something configured incorrectly with Profile2?

Thanks in advance for any advice!

# Answer
> 1 votes
The profile 2 page states:

> Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)

Did you set-up different roles for coach and player?

---
Tags: users
---


# Question
Title: Status updates in organic groups disappear after a period of time
After about 30 days or so, the activity streams under the Organic Group Home tab drop off or disappear. I have found a reference to this issue on Acquia Commons' community site.

I have checked the view `activity_log_stream` but do not see where we might adjust the length of time which content remains on the activity stream. Optimally, we'd like the content to disappear only after the Items per page attribute is met.

# Answer
In **/admin/settings/activity\_log** there is just the field to control this.

Note: Though each time we run a cron job, entries over 30 days still disappear. This is perhaps a bug? So our makeshift solution is to click the **Regenerate Activity** tag. This seems to behaves predictably.
> 0 votes

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


# Question
Title: Use taxonomy_get_tree() to extract term names?
I'm using the handy `taxonomy_get_tree()` function to, hopefully, just extract the list of term names within a vocabulary. Sounds simple enough, but I'm stumped. Running the following:

```
$tree = taxonomy_get_tree(2);
print_r($tree);

```

yields the following:

```
      Array
(
    [0] => stdClass Object
        (
            [tid] => 1
            [vid] => 2
            [name] => The First Term
            [description] =>
            [weight] => 0
            [guid] =>
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

    [1] => stdClass Object
        (
            [tid] => 2
            [vid] => 2
            [name] => The Second Term
            [description] =>
            [weight] => 1
            [guid] =>
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

)

```

Now all I want to do is pull out each of the `name` values. So I tried the following:

```
foreach($tree as $value){
    print($value['name']);
}

```

I'm returning a server error. I suspect it has something to do with that pesky `stdClass Object` thing.

So any ideas how I can extract just the `name`s?

# Answer
Nevermind... this works:

```
foreach($tree as $value){
    print($value->name);
}

```

Thankfully, it looks like I'm not the only idiot out there. Sigh...
> 1 votes

---
Tags: taxonomy-terms
---


title: How to import an iCal Feed

text:
# Question
Title: How to import an iCal Feed
I'd like to import an iCal feed. Every calendar entry on a given URL should be transformed into a node.

I read that this should be possible with with the feeds, date and calendar module. But I did not find any description about the topic.

I would be very happy if some one could shed some light on this topic.

# Answer
This online video got me a good bit of the way along:

http://mustardseedmedia.com/podcast/episode34

> On this podcast, Bob shows how to import any iCal feed of events into your Drupal site and displaying them in a Views-driven calendar on your site. (This means importing your Google or Yahoo! calendars or any other calendar system that puts out a feed in iCal format) This is tasty stuff! Want to have the Drupal calendar delete nodes once they're deleted from the feed? Check out this patch and give it a try. Episode Links Feed API, iCal Parser, Feed API Mapper

I am stuck on populating the Organic Group field of the newly created node.
> 1 votes

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


# Question
Title: Add custom fields to the Apache Solr search results
I'm trying to configure a search page from Apache Solr module, and add some custom fields to the items. Here is the code I'm using for this

Custom module:

```
function hook_apachesolr_query_alter($query) {
$query->addParam('fl', 'ts_field_up_short_description');}

```

Function in tamplate.php:

```
function tamplate_preprocess_search_result(&$variables) {
$variables['ts_field_up_short_description'] = $variables['result']['fields']['ts_field_up_short_description'];}

```

Display field in search-result.tpl.php:

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

```

I'v created 3 nodes with this field, but only one of them displays the short description field (if displaying the search results with views everything is fine). Please tell me am I missing something? Thanks

# Answer
I have forgotten to add the content type filters, everything is correct now. Another (better) way is to modify the snippet in module (like here) instead of the search results template.
> 1 votes

---
Tags: 7, search
---


# Question
Title: Getting the token tree to appear contextually
I'm writing my own file formatter which is supposed to be Token-compatible. As it will be also used on taxonomy term pages, it should accept taxonomy term token. What am I doing wrong in `hook_field_formatter_settings_form` by saying:

```
'#token_types' => array('node', 'taxonomy_term')

```

so that I don't get term-related tokens at all? Cleared cache many a time. Preferably, I would like the tokens to appear contextually: taxonomy term - when managing display of taxonomy term page, node - when managing display of a node page. Can this be done?

# Answer
> 0 votes
The surpising answer was: `'#token_types' => array('node', 'term')` Thanks to davereid!

---
Tags: hooks, tokens
---


title: Custom Modules Help

text:
# Question
Title: Custom Modules Help
First of all I am a Drupal beginner.

I need to implement a reward points functionality on a Drupal 7 website. A user is given points by performing certain actions such as user registration, when the user makes a booking through the system or when the user refers the website to other friends.

My question is when the administrator wants to know what are the users' reward points. How can I do this? Is it through a custom module and using a costume template (tpl.php)?

Thanks.

# Answer
> 3 votes
If you're saying that the points are awarded automatically when a user registers, creates a node, etc., rather than being assigned by an administrator, you might want to look at the UserPoints module. It assigns points based on certain actions. There's a helper module called UserPoints Contrib, which extends UserPoints to many more actions.

---
Tags: 7, hooks
---


# Question
Title: Which are the file_save_upload() validators?
In the `file_save_upload()` function, what keys can `$validators` take? I cannot find answers anywhere.

# Answer
> 2 votes
You can see the validators in core at the end of this listing:

http://api.drupal.org/api/drupal/includes%21file.inc/group/file/7

the ones starting with file\_validate\_

Also there's an example of the array structure here: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_validate\_picture/7

---
Tags: files, forms
---


title: Linking to My Blog on Menu

text:
# Question
Title: Linking to My Blog on Menu
I am creating a new Drupal website. I want to create a menu tab that links to the My Blog section. What URL link do I use for this?

# Answer
> 1 votes
Should be just (whatever your drupal directory)/blog, if it's installed in root directory, then it would look like http://www.example.com/blog, if the blog you created is different from the system default one, it would be http://www.example.com/your\_blog\_machine\_name

---
Tags: routes, nodes
---


# Question
Title: Feeds Importer won't import autocomplete field
I'm trying to use the Feeds Importer plugin. I have a field that's an auto complete and it maps to a NID. I have the NID in the csv file I'm trying to import but it doesn't ever populate that field. It does populate every other field correctly, though.

Any thoughts why this might not be working?

# Answer
Found the bug... http://drupal.org/node/1426762
> 1 votes

---
Tags: feeds, ajax
---


# Question
Title: How some hooks works, if doesn't return anything and doesn't have any references
In Drupal API documentation is an example:

```
function hook_user_view($account, $view_mode, $langcode) {
  if (user_access('create blog content', $account)) {
    $account->content['summary']['blog'] =  array(
      '#type' => 'user_profile_item',
      '#title' => t('Blog'),
      '#markup' => l(t('View recent blog entries'), "blog/$account->uid", array('attributes' => array('title' => t("Read !username's latest blog entries.", array('!username' => format_username($account)))))),
      '#attributes' => array('class' => array('blog')),
    );
  }
}

```

Noobie question is: how does it actually work? I mean, there is no reference being passed to the function, and it doesn't return anything. This is somewhat counter intuitive how function works. I guess $account data doesn't disappear with end of the function but how, if it's not a reference?

# Answer
The `$account` variable is a PHP Object.

In PHP, Objects are (for the most part) passed by reference, so any changes you make to the variable passed in will be persisted to the object in memory.

The only difference syntactically is that you don't need the ampersand before the variable name in the function signature - it's implied.
> 3 votes

---
Tags: hooks
---


# Question
Title: How can I set a certain cck value to selected nodes using View Bulk Operation (VBO)?
I have a text type cck filed (checkbox widget) allowing multiple values. I need to add one of the values of this field to selected nodes using VBO. I suppose `Modify node fields (views_bulk_operations_fields_action)` is the way to go but how can I exactly do it? I need to add just one value but keeping the existing values the nodes currently have.

# Answer
Create a view, and add Bulk Operation to the field. In the configuration field: Bulk Operations: Content Bulk Operations -\> Selected Operations, you can choose the operations you would like to perform in bulk. Once you done, save the view, and go to the view page.

1. Select the nodes you would like to edit
2. Choose an operation, click `Execute`
3. Select the field you like to edit
4. You got the rest.
> 0 votes

---
Tags: 6, entities, views
---


# Question
Title: How can I get $_POST data in a callback?
I've implemented hook\_menu roughly as follows:

```
function sample_menu() {
    return array(
        'path/to/things' => array(
            'page callback' => 'callback_function',
            'access arguments' => array('access content'),
            'page arguments' => array(),
            'type' => MENU_CALLBACK
        )
    );
}

```

I want to be able to post data to this url. So says $\_POST is the following array:

```
array(
    'data1' => 'value1',
    'data2' => 'value2',
)

```

How can I access $\_POST\['data1'\] and $\_POST\['data2'\] inside the callback? Directly accessing $\_POST seems to not work (it's var\_dumped as empty).

# Answer
They access `$_POST` in the same way other functions do.

Take file\_ajax\_upload() as example; it contains the following code.

```
  if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
    // Invalid request.
    drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
    $commands = array();
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
    return array('#type' => 'ajax', '#commands' => $commands);
  }

```

The function is a page callback defined in file\_menu().

```
  $items['file/ajax'] = array(
    'page callback' => 'file_ajax_upload',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );

```
> 14 votes

---
Tags: routes
---


# Question
Title: Get whole tree of a taxonomy term from node into seperate php variables
Can anyone of you brainy folk suggest the best way of retrieving the taxonomy term on a node and both of it's parents then storing as variables on a php snippet? For example: Country-\>City-\>District output to $country, $city and $district?

Thanks in advance for all your answers!...

nb, this is what I get from print\_r, \[0\] being the country, \[1\] being the area and \[2\] the district:

```
field_location_term] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [tid] => 26
                        [taxonomy_term] => stdClass Object
                            (
                                [tid] => 26
                                [vid] => 5
                                [name] => B----a
                                [description] =>
                                [format] => filtered_html
                                [weight] => 3
                                [vocabulary_machine_name] => geographical_location
                                [metatags] => Array
                                    (
                                    )

                            )

                    )

                [1] => Array
                    (
                        [tid] => 27
                        [taxonomy_term] => stdClass Object
                            (
                                [tid] => 27
                                [vid] => 5
                                [name] => B----o
                                [description] =>
                                [format] => filtered_html
                                [weight] => 0
                                [vocabulary_machine_name] => geographical_location
                                [metatags] => Array
                                    (
                                    )

                            )

                    )

                [2] => Array
                    (
                        [tid] => 28
                        [taxonomy_term] => stdClass Object
                            (
                                [tid] => 28
                                [vid] => 5
                                [name] => M----w
                                [description] =>
                                [format] => filtered_html
                                [weight] => 0
                                [vocabulary_machine_name] => geographical_location
                                [metatags] => Array
                                    (
                                    )

                            )

                    )

            )

```

I thought the best thing to do would be

```
$country = $node->field_location_term['und'][0]['taxonomy_term']['name'];

```

But I get no output.

# Answer
It appears from your printout that taxonomy\_term is an object, not an array. So your code would look like this:

```
$country = $node->field_location_term['und'][0]['taxonomy_term']->name;

```

You might not be able to do the object-\>\['array'\]-\>object-\>\['key'\] thing. It might need to be broken into:

```
$foo = $node->field_location_term['und'][0]['taxonomy_term'];
$country = $foo->name;

```
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Display a block only if another specified block isn't visible?
The issue is that I have a Menu Block with parent items that don't yet have child menu items, but eventually might. I want to display another block in place of the menu block if the menu block is not on a particular page. I have tried rules, rules bonus blocks, context, even conditions in my page templates but I am a PHP novice and so far it doesn't seem possible to create a condition based on a block's visibility. I hope that makes sense! Any help much appreciated! I am using D7.

# Answer
I was able to do this with panels, view blocks and a custom PHP visibility condition. I think Panels is trivia. You could do this with Drupal's built-in block administration.

I had a news block that would show up on the city page. It would display all the news of the city. If there was no news for that city, it would display \[another\] news block for that state. If there was no news for that state, it would display \[another\] news block for the country.

Each of these block was a view. In the PHP visibilty I would check for views results using the views\_get\_view\_result($name, $dispay\_id = NULL \[, $args\])

So the county block would check if the state and city block view returned any results, if FALSE (no results) then it would get displayed. State would check if city block view return any results, if FALSE (no results) then it would get display.

If you blocks are not views, then I don't know how to solve the problem easily (unless the last block is the only one that is not).
> 2 votes

# Answer
One of my blocks was not a view but a custom block generated via module, so create a view which would generate the similar content, at least could list the items or give the total count of items. Then I checked if there is any result returned by `views_get_view_result($name, $dispay_id = NULL [, $args])`, if yes then don't show this block else show the block.. and it worked for me. Hope this helps someone in need.
> 1 votes

# Answer
I had very similar problem with Menu Block module so I wrote simple Context module/plugin Context Active Menu Depth that sets appropriate context when specified condition (menu depth, menu name and has\_children) are met. Code is still experimental but you'll get the idea. In my case I needed to display replacement block if Menu Block with 2nd level of links is not present.
> 0 votes

---
Tags: 7, routes, blocks
---


# Question
Title: How do I disable fields for a user account?
The site I am developing has 2 type of profiles: the main account, and the alternative account associated with it. The alternative user gets blog posts, forum posts, under its own name. "He-man" and "Frodo" could be two examples.

The main accounts have signature, and image fields that never apply to them because the system always defaults to the alternative account for these things.

Since alternative accounts, and the main accounts both have different roles/permissions, how can I hide these fields using permissions?

I see that http://drupal.org/project/user\_picture\_field can be used to hide the picture field by setting permissions. How can I hide more than just the picture?

# Answer
With the Field Permissions module you can hide fields per role.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
>
> ### Features
>
> * Enable field permissions on any entity, not just nodes.
> * Role-based field permissions allowing different viewing patterned based on what access the user has.
> * Author-level permissions allow viewing and editing of fields based on who the entity owner is.
> * Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
> 0 votes

---
Tags: users
---


# Question
Title: Superfish Menu links disappear on iOS (only if they have dropdown menus)
I've got a superfish menu as the main menu on my site. Two of the links in the menu have sub-links and are presented as a drop-down, hover menu. This works great on desktop browsers. On iOS, however, the main link disappears if that menu item has a drop down. It's only gone in the default state though, if I tap on the spot where it should be, the link shows up again and the drop-down menu appears as it should. If I tap the other link which has a drop down menu, the first drop down will disappear and so will the main link. For example, if the normal menu looks like this..

`FOO` `BAR` `BAZ` `BAT`

and BAR has a drop down menu, then the menu will look like this on iOS:

`FOO` `<empty space>` `BAZ` `BAT`

but if I tap on that empty space, then `BAR` will show up and so will the drop-down menu.

I've checked the CSS and don't see any differences in the styles.

I'm sorry I can't give you a link to the site to see where this is happening. I'm under an NDA and the site isn't public yet.

**EDIT**: I discovered that the css sets `.sf-menu li` to have `position: relative`. When I disable this rule in the inspector, then `BAR` appears in the spot where it should be. However, when I do this, the drop-down menus no longer have the correct context for their positioning. So, I need this rule so the drop-downs work properly, but something about that rule is causing those elements to jump out of position.

So, two questions:

1) Do you know why this is happening and do you know of a fix?

2) or, do you know of a way to make them non-drop downs when iOS is detected? The dropdowns are not crucial to my site navigation.

# Answer
> 2 votes
Enough tinkering and I found a solution. I'm not sure WHY it works, but it does.

During my experiments, I wondered if the z-index was the problem and if it was getting covered by something, so I cranked the z-index up to 10000 but that still didn't solve it.

I eventually discovered the `position: relative` thing I mentioned above. So I opened up the Computed Style box and toggled the `position: relative` rule on and off, on and off, which would break it, fix it, break it, fix it. Then I looked in the Computed values to see if anything else changed. Sure enough, the z-index changed. When it was in the working state the computed z-index was `auto`, so I created a css rule to explicitly set z-index to auto for those elements and viola... it's working.

Hopefully this will be helpful to someone else.

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


# Question
Title: Can I override a theme function from a contributed module
Per this question, Can I modify guestbook.module safely? I have overridden `theme_guestbook_entry()` from the guestbook.module file. The problem is that my modifications are not taking effect. (Yes, I rebuilt the cache.)

I am following these instruction here, http://drupal.org/node/11811. I notice they don't mention contributed modules at all. Am I able to override these?

# Answer
> 5 votes
The page you are referring is for Drupal 5.

In Drupal 6, you alter a theme function defined in a module by defining the theme function, as in the following code. (Replace mytheme with the short name of your theme.)

```
// Drupal 6
function mytheme_guestbook_entry($uid, $entry, $comment_entry = NULL, $zebra, $confirm_delete = FALSE) {
  // Your own code.
}

```

```
// Drupal 7
function mytheme_guestbook_entry($variables) {
  // …
}

```

In Drupal 7, if you just want to alter the variables passed to the theme function, you need to implement the preprocess function for that theme function.

```
function mymodule_preprocess_guestbook_entry(&$variables) {
  // Alter the values passed to the function, such as $variables['uid'], $variables['entry'],
  // $variables['comment_entry'], $variables['zebra'], or $variables['confirm_delete'].
}

```

The code I shown works whatever a theme function is implemented in Drupal, or a third-party module.

---
Tags: theming
---


# Question
Title: Drupal Views adding a view to node-customcontenttype.tpl.php
I've created a "homepage" content type, and I've created the node-homepage.tpl.php template file, but it doesn't seem it is used, even after I cleared the cache about 10 times.

I am also trying to display a view in this custom template file. How can I achieve this?

# Answer
> 0 votes
In Drupal 7 you should use two dashes : `node--content-type.tpl.php`.

Embeding view:

```
<?php print views_embed_view('articles','block', $node->nid); ?>

```

`articles` \- name of view, `block` \- type of view, `$node->nid` \- argument.

---
Tags: views, theming
---


title: How can I edit Custom Form API?

text:
# Question
Title: How can I edit Custom Form API?
I have created the Custom registration form module using the form API as per the requirements. I have also inserted the records in the database using form alter functions. Now I need to create an edit registration form for the logged users.

My suggestion on this is:

1. Create edit\_reg form module with form controls
2. Retrieve the records of logged users
3. Pass the values to defalut value of form controls

Is the above method good? May you suggest me any other method to edit the form API?

I am using Drupal 7.

# Answer
> 1 votes
Why not use the existing user edit form, and use `hook_form_alter()` to add your fields. That way, you get all the built in functionality, such as password changing etc.

It would also make sense to make the user registration alterations the same way, instead of creating your own flow, unless it for some other reason makes sense to do it that way.

---
Tags: forms
---