# Question
Title: How to inject postal address into user entity via custom registration form
I'm using the postal address module to obtain a user's postal address when they register on the site. The registration form is created by a custom module I made.

I'm able to get the form to display the postal address fields correctly (they modify based on your country, etc.), but when I go to process the form in HOOK\_submit(), I hit a problem.

The submit function adds the user entity and puts the correct information in for the user. It also creates a new line in the field\_data\_field\_postal\_address table in the db as it should. But the address fields are all empty.

I think it is very close to working, but I suspect that something is wrong with the structure of the array I'm passing in to the 'field\_postal\_address' custom entity field.

```
function user_registration_form_submit($form, &$form_state){
drupal_set_message("User registration submitted");
dsm($form_state);

$edit = array(
    'name' => $form_state['values']['name'],
    'pass' => $form_state['values']['password'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'field_postal_address' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['address']))),
    'status' => 1,
    'access' => REQUEST_TIME,
);
$newUser = user_save(drupal_anonymous_user(), $edit);
}

```

So, the question is, why is this function injecting an empty row of data into the field\_postal\_address field?

# Answer
> 1 votes
I managed to figure out the problem. Apparently you can't load the new user array with the position of the array where the address fields are located. Instead you have to load the address array into a new variable, and pass THAT into the "field\_postal\_address" entity field.

So, in my solution, I loaded the address array into the `$ary_address` array. Then I passed that into the postal address array.

```
$ary_address = $form_state['values']['address']['address'];

$edit = array(
    'name' => $form_state['values']['name'],
    'field_fname' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_fname']))),
'field_lname' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_lname']))),
    'pass' => $form_state['values']['password'],
    'mail' => $form_state['values']['mail'],
    'init' => $form_state['values']['mail'],
    'field_postal_address' => array(LANGUAGE_NONE => array($ary_address)),
    'status' => 1,
    'access' => REQUEST_TIME,
);
$newUser = user_save(drupal_anonymous_user(), $edit);

```

# Answer
> 0 votes
The first argument to user\_save() should be the user object for the newly created account not the anonymous user assuming your submit handler runs after the account has been created.

---
Tags: entities, users
---


title: Footer menu links

text:
# Question
Title: Footer menu links
I'm trying to find a sneaky and self-updating way to duplicate the main menu links and place them in a footer menu. The only difference would be that the menu items would have to be glued with a delimiter, perhaps a pipe character.

I tried `theme_links`, `theme('links', $primary_links)` but none of these worked. Of course I could paste them static, but I like scalable, self-updating solutions, that's why I'm asking. So, is there a drupal function that would get menu links and implode them easily?

# Answer
> 1 votes
You can override `theme('links__system_main_menu', $array)` at the theme level to add "pipes" to the list markup as necessary. I just copied the source of links\_system\_main\_menu and adjusted as necessary:

In page-front.php for example (note I added the #separator value so you could make it anything you want really. The rest of this theme() call is just plain old Zen theme code.

```
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu',
        'class' => array('links', 'inline', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
      '#separator' => '<span class="gold_tassle">|<span>',
    )); ?>

```

Then in my template.php file ...

```
function MYTHEME_links__system_main_menu($variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  $heading = $variables['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    $output = '';

    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading['level'];
      if (!empty($heading['class'])) {
        $output .= drupal_attributes(array('class' => $heading['class']));
      }
      $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
    }

    $output .= '<ul' . drupal_attributes($attributes) . '>';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class[] = 'first';
      }
      if ($i == $num_links) {
        $class[] = 'last';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
           && (empty($link['language']) || $link['language']->language == $language_url->language)) {
        $class[] = 'active';
      }
      $output .= '<li' . drupal_attributes(array('class' => $class)) . '>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.
        $link += array('html' => TRUE);
        $title = ($i != $num_links) ? $link['title'].$variables['#separator'] : $link['title'];
        $output .= l($title, $link['href'], $link);
      }
      elseif (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes.
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '<span' . $span_attributes . '>' . $link['title'] . '</span>';
      }

      $i++;
      $output .= "</li>\n";
    }

    $output .= '</ul>';
  }

  return $output;
}

```

# Answer
> 1 votes
Rather than pollute your page markup with extraneous pipe characters, why not just take a carbon copy of the header menu, and insert the pipes with jQuery? As it's a footer menu it'll be at the bottom of the page anyway, and 99% of the time users won't scroll down quickly enough to see the insertion happening.

I use this code in any site where I need to do the same:

```
(function($) {
    $(function() {
      var count = $('#header-menu li').length;
      $('#header-menu li').each(function(i, v) {
        if (i < (count-1)) {
          $(v).after($('<li class="menu-separator" />').html('|'));
        }
      });
    });
})(jQuery);

```

The above obviously applies to an element called `#header-menu` but you can change that for your own purposes. It works by inserting an extra `<li>` between each of the menu links and adding a specific class to it for easy styling.

# Answer
> 1 votes
Not sure if you want to use code but have you had a look at this module? http://drupal.org/project/menu\_block/.

"It provides configurable blocks of menu trees starting with any level of any menu. And more!"

# Answer
> 0 votes
The following should work fine...

```
print theme('links', array('links' => $primary_links));

```

Use an image for the pipe.

---
Tags: navigation
---


# Question
Title: How to adjust position of drop-down block in Nice-Menu?
I have inherited a site built in Drupal 6 that uses Nice-Menus for both the top and side nav bars. I've been tasked with modifying the current navigation and have run into issues adjusting both the position and width of various menu items.

You can see the issue by going to http://neoninc.org and hovering over "ABOUT" in the top nav bar, then "About NEON & Mission \>\>." You should see that the menu item for "Governance" doesn't align properly with its parent item.

The previous developer added the following items to the CSS page called by nice-menu to adjust their widths:

```
ul.nice-menu li.menu-563 li { width: 20em; !important}   /*  ABOUT */
ul.nice-menu li.menu-840 li { width: 20em; !important}   /* CONTACT US */
ul.nice-menu li.menu-236 li { width: 24em; !important }  /* SCIENCE */
ul.nice-menu li.menu-4191 li { width: 20em; !important } /* CITIZEN SCIENCE */

```

I tried adding the following:

```
ul.nice-menu li.menu-781 li { margin-left: 16px; !important} /*  ABOUT >> Governance */

```

and then:

```
ul.nice-menu li.menu-781 li { left: 16px; !important} /*  ABOUT >> Governance */

```

both of which seem to work when editing the CSS directly in FireBug. They don't work when inserted into the actual CSS file, and I'm stumped.

Yes, I've rebooted, cleared the local cache, cleared all caches in drupal, and double-checked that I actually uploaded the edited CSS file.

Any suggestions are greatly appreciated!

# Answer
> 0 votes
You need to be overriding this...

```
ul.nice-menu-down li ul li ul, #header-region ul.nice-menu-down li ul li ul

```

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


# Question
Title: Front class not included in body tag in my custom module
We are trying to make a Drupal mini bootstrap for our language selection module. We implemented `hook_boot()`, in this function, we included path.inc and common.inc from core.

The language selector always redirects to the frontpage of the according language. Now the problem is that, when loading the new page, the class of `<body>` is *not-front*. This means that front-specific styles, and template are not used; it just uses the default ones.

We are guessing that we missed something in the Drupal bootstrap process.

Do you have any idea?

# Answer
> 1 votes
If memory serves me correct the "front" class will only be set on the body, if the URL you are on matches what is set in the "Site Information" \> Front Page field.

My guess is that you'll need to override the string or array of body classes in the template.php file of your theme. To do this you'd want to use the template\_preprocess\_html function provided by Drupal core.

Here is a quick and dirty example of how to add the class to the body of your theme:

```
function THEMENAME_preprocess_html(&$variables) {

  if (theme_get_setting('my_variable') == 0) {
    $variables['classes_array'][] = 'front';
  }

}

```

From there you'd need to figure out what classifies the home page as the home page with some conditionals or custom functions.

# Answer
> 1 votes
The function that set those CSS classes is template\_preprocess\_html(), which uses the following code.

```
  // Add a class that tells us whether we're on the front page or not.
  $variables['classes_array'][] = $variables['is_front'] ? 'front' : 'not-front';
  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';

```

`$variables['is_front']` is set by \_template\_preprocess\_default\_variables(), which is called by template\_preprocess(), and contains the following code.

```
  // drupal_is_front_page() might throw an exception.
  try {
    $variables['is_front'] = drupal_is_front_page();
  }
  catch (Exception $e) {
    // If the database is not yet available, set default values for these
    // variables.
    $variables['is_front'] = FALSE;
    $variables['db_is_active'] = FALSE;
  }

```

`$variables['classes_array']` is then imploded in template\_process(), which uses the following code.

```
  // Flatten out classes.
  $variables['classes'] = implode(' ', $variables['classes_array']);

```

I tried the following text code, in my test site.

```
function code_testing_preprocess_html(&$variables) {
  $variables['classes_array'][] = 'front';
}

```

For a page that is not the front page, I got the following output.

```
<body class="html not-front logged-in one-sidebar sidebar-first page-tracker front toolbar" >

```

Your code should remove "not-front" as CSS class, before adding "front"; this could done in `hook_process()`, by altering `$variables['classes']`, or in `hook_preprocess_html()`, by altering `$variables['classes_array']`.

---
Tags: 7, nodes, bootstrapping
---


# Question
Title: Best practice: needs private and public contents of same type
The website need News, Image Gallery and Announcement. But all of the News, Image Gallery and Announcement has 2 types: public and private.

The private content is tend to be a "collaboration platform" for specific user role.

I've created two content types for News (news & private\_news), and so on for Image Gallery and Announcement.

So the website has 6 content types. I'm using content\_access to make the content type public or private.

The problem with this, I dont know the future of the website. It will fails if in the future it needs public and private forum (where forum cannot exist in 2 content types).

Choice 2: Make single content types. It needs single News content type. The field accessibility is done by using field\_permissions (not yet tested) and the node visibility is same as above; using content\_access

But the problem is the content types become more complex. It maybe become very heavy for the server.

Choice 3: Use different sobdomain: `www.site.com` for public contents, and `somename.site.com` for private contents (not sure what name I should choose as subdomain).

I'm not sure which one the the best if the website growing bigger (in terms of traffic and website features).

# Answer
Perhaps the deciding factor is to determine if the private users need to see the private content seamlessly integrated into the public content. If they do solutions 1 & 2 seem like they might work. If, on the other hand, private content can or should be viewed separately from the public materials, separating into two subdomains (or even subsites) with different access rules would be much easier.
> 1 votes

# Answer
Have you checked the Workflow module (http://drupal.org/project/workflow)? Even though the usecase for the module is not exactly what you are trying to achieve, it does allow putting nodes in different states (like private and public) which can be restricted per role.
> 1 votes

---
Tags: 7, nodes, users
---


title: Autocomplete URLs

text:
# Question
Title: Autocomplete URLs
After scouring the www for a solution, I thought I'd post my question here. I've got an autocomplete textfield that's actually retrieving custom URLs from the taxonomy\_term\_data and field\_data\_cip\_title (custom field for one of my taxonomy vocabularies) tables. Here's the script that I'm using to create the custom URLs:

```
SELECT CONCAT('<a href=\"/college/disciplines/check?eid=', ttd.tid, '\">', ttd.name, ': ', fdct.cip_title_value, '</a>') cip
  FROM {taxonomy_term_data} ttd,
       {field_data_cip_title} fdct
 WHERE ttd.tid = fdct.entity_id
   AND fdct.entity_type = 'taxonomy_term'
   AND fdct.bundle = 'cipcodes2010'
   AND fdct.deleted = 0
   AND LENGTH(ttd.name) = 7
   AND CONCAT(ttd.name,fdct.cip_title_value) LIKE :string
 LIMIT 0, 7", array(':string' => '%' . $string . '%')

```

The URLs appear just fine in the autocomplete textfield, and clicking on one of them will take you to the correct URL.

However, when clicking on a link, the HTML of the link appears in the textfield for a brief moment prior to being taken to the URL:

```
<a href="/college/disciplines/check?eid=5373">01.1202: Soil Chemistry and Physics.</a>

```

which is quite unattractive. Also, if the user uses the arrow keys to navigate to the desired choice, and then hits the enter key, nothing happens other than the selected HTML appearing in the textfield.

Is there a better way to return clickable - or selectable via arrow keys - autocomplete results that can be acted upon?

Please let me know if I need to elaborate a bit more, and I'd be more than happy to do so.

# Answer
> 1 votes
I suspect that what you are looking to do is identical to what the API module does on http://api.drupal.org/api/drupal . Based on a quick look, the module does not appear to construct the URL and return it along with the autocomplete values. Instead, it returns the best matches and when a match is clicked (or selected via the keyboard), it simply submits the form along with the selected value. The form redirects the user appropriately.

Check the block *hook* as well as the `api_search_form` functions in api.module to see how this is done. The module's repository might also prove useful, especially `api.js`.

---
Tags: 7, ajax
---


# Question
Title: Only load Views Slideshow JavaScript when needed
Does anyone know how to only load the Views Slideshow JavaScript on certain content-types, pages, or the front page?

# Answer
> 0 votes
If you want to only enable a Views Slideshow (or any other object) on certain pages, I recommend having Views output a block and then setting that block to display only on the necessary pages. It should only call the js (which should reside in sites/all/libraries) on pages that load the block. You can then set the block to display or hide by role, page, etc.

---
Tags: 7, views, javascript
---


# Question
Title: PHP setting of datetime field in CCK through Rules, How to stop continuous updates?
Drupal 6. Using Rules and CCK

So, I have a content type that gets automatically generated with Rules. Several CCK fields get populated at creation time, including a datetime field. I want this field to get populated with the current date/time.

For some reason, the Global Token fields don't work, the interface throws an error when I try to use a token instead of a standard formatted date/time stamp.

So, I use advanced PHP code box to set the date/time value.

return array( 0 =\> array('value' =\> date("m/d/Y - H:i")), );

This code works, but when I do it this way it seems that whenever I refresh the node page the date/time stamp in the field is updated to whatever the current time is. This is not the behavior I want. I want the date/time to get inserted at creation time, and have it remain unchanged for perpetuity.

Thoughts?

# Answer
> 1 votes
Thanks to Clive's help, I determined the problem was with the field type. There were several similar seeming Date/Time field types available to use, I was using one called "datetime". I switched to another one called "datestamp" and the datestamp field retained its original value after refreshing. I guess the "datetime" field is designed to always return the current datetime value of now(). Thanks for helping me work through this friend!

---
Tags: entities, rules, datetime
---


# Question
Title: Is table prefixing controlled by db_set_active()?
If I use `db_set_active()` to fetch data from another database, how will that affect table prefixing?

Is table prefixing dynamic in the sense that it adjusts to the currently active database?

# Answer
When you use `db_set_active` you change the config that Drupal uses, so in theory you could use `db_set_active` to use the same database but change the prefix used.

Drupal will use the configuration defined, and the changed they imply.

You should note, that db\_set\_active won't work if you use multiple db backends for older Drupal versions (Drupal 6 and earlier, several MySQL backends are fine, but you can't switch from PgSQL to MySQL)
> 3 votes

---
Tags: 7
---


# Question
Title: How to call pages by Ajax using javascript
I've a created an Ajax-callback page using my module available as `myModule/somepage/%/%` \- you can see that last two arguments in this page changes dynamically.

I want to make an AJAX call to this page, writing javascript. Say, when I click a button an ajax call will be made to this page (POST method preferably for the two arguments).

I know how to create hyper-links that handle Ajax calls automatically, but in that way links are static, and I can not send arguments to my Ajax-callback page. So how do I write JavaScript to make an Ajax call to my page?

# Answer
Here is the code to make POST req to a webpage.

```
$('#yourid').click(function(e) {
    e.preventDefault();
    var theUrl = base_url + 'myModule/somepage';
    $.ajax({
        url: theUrl,
        type: "POST",
        data: "name=John&location=Boston"
        success: function(msg){
        alert(msg);
        $('#displydiv').html(msg);
    }
    });
});

```
> 2 votes

# Answer
> Say, when I click a **button** an ajax call will be made to this page

If you want a form which has AJAX then you need to look at the FormAPI. This article also explain in quite good detail on how to build AJAX forms. If you want something other than forms then I suggest looking at jQuery API for jQuery.ajax. There's also a shorthand for jQuery.ajax which is jQuery.post.
> 0 votes

# Answer
There is good documentation about FAPI and AJAX:
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: How can I see the query that's being run?
I'm using hook\_views\_query\_alter(), and I'd really like to print somewhere (screen, error log, whatever) the query that's being run based on the alterations. I've tried dpm($query), but that gives me the whole krumo tree - all I want is the query - i.e. "select x, y from z where a = 2". Possible?

# Answer
The `views_plugin_query_default` class has a `query()` method that will take the parameters currently held in the object and provide you with a standard `SelectQuery` (un-executed of course).

Since the `SelectQuery` class implements the magic `__toString()` method you can then cast it directly to a string, which will be the SQL query itself:

```
$select_query = $query->query();
$query_string = (string)$select_query;
dpm($query_string);

```
> 13 votes

---
Tags: 7, hooks, views
---


# Question
Title: Rebuilding or regenerating the teaser after changing the trim length in Drupal 7?
I changed the teaser length from 600 characters to 300 characters for the Story and Book Page content types. How do I rebuild the teasers so that all teasers are updated to the new value?

Any help would be appreciated.

# Answer
> 1 votes
* If you are using the Views module to display your teasers, and you are using fields in the View, then you need to set the trim length for each field in the View itself.
* Are you using custom formatters? These might be buggy and/org disregard the trim length.
* When you edit the node(s), check that the summary field is blank. (I quote from the node edit page: "Leave blank to use trimmed value of full text as the summary.")
* For further troubleshooting, create a new node with a lot of dummy text. Does it get trimmed to 300 or 600 characters?
    + If the new node gets trimmed to the new value, but old nodes get trimmed to the old value, then there is a problem with your cache or with the old nodes.
    + If the new node also gets trimmed to the old value, then there is a problem with your fields or views.

---
Tags: nodes
---


# Question
Title: Custom CSS for title fields of Articles specified in content creation
Custom CSS for title fields of Articles specified in content creation

As an example, I have a view that displays my latest 10 articles but want the titles to be different colours. I want these colours to be determined based on what I input at the content creation form, whether it be in a separate field or by defining/attaching a specific class to each new Article.

Is there a way to do this or a better solution to my problem available? Thanks in advance :)

# Answer
> 0 votes
I had to do this as a hack solution for the interim until I find a better solution to implement. The following will apply a blue background to all articles in the front page feed view that have the title 'First Article'.

**HTML:**

```
<div>
    <span class="views-field-title">
        <a href="/articles/first-article">
            First Article
        </a>
    </span>
</div>

```

**jQuery:**

```
function ($) {
    Drupal.behaviors.ApplySpecificTitle = {
        attach: function(context, settings) {
            $('span.views-field-title a:contains("First Article")').parent().addClass('article-title-first');
        }
    };
})(jQuery);

```

**CSS:**

```
.views-field-title {
    background: #CCC; /* Default background */
}
.article-title-first {
    background: blue;
}

```

*Note: This is probably far from the most graceful solution but it works for my instance as I won't be adding new articles very often.*

# Answer
> 1 votes
For the simplest and quickest implementation I'd suggest you create a array in your THEME\_preprocess\_node(&$vars) in template.php:

```
<?php
$vars['color_cls'] = array(
    'red',
    'blue',
    'yellow'
);
?>

```

Then you could simply randomly address those in your node.tpl.php and print them as a class in your node, something like this:

```
<div class="node <?= $color_cls[array_rand($color_cls)]; ?>">

```

You could also make the color\_cls array associative and give them, for example, priorities:

```
<?php
$vars['color_cls'] = array(
    'critical' => 'red',
    'important' => 'blue',
    'normal' => 'yellow'
);
?>

```

And ofcourse, then you just style them with your CSS. I'm assuming you do know how to style the classes, so I'll leave out the CSS bit.

---
Tags: 7, theming, nodes
---


# Question
Title: Is it possible to customize site status messages?
There are various types, like "Error, status" and they show up after creating content, or when triggered by a rule.

I'm wondering if it is possible to create a new type, such as "Dev" and have it's visibility limited to certain roles, like administrator.

# Answer
> 4 votes
The status type can be customised so you're covered with that one.

Assuming you're setting messages using drupal\_set\_message, you could check if the message should be set based on the status of the user. To make it a bit cleaner, you might want to write a module so you can set a specific permission to show this message to certain roles.

# Answer
> 1 votes
There's a module for D6 that gives you a hook and a class for matching/editing messages displayed to the user - http://drupal.org/project/messages\_alter

---
Tags: status-messages
---


# Question
Title: How can I change the 'active' class in main menu to something else?
I'd like to change the class in the main menu from 'active' to say 'current'. How can this be accomplished?

# Answer
Assuming you are using Drupal 7.

You can overide theme\_links in your own theme.

find the line:

$class\[\] = 'active';

make it

$class\[\] = 'current';

check API:

http://api.drupal.org/api/drupal/includes!theme.inc/function/theme\_links/7

by the way, I would suggest you not to change 'active', instead you can just add additional class for it. As many contributed modules use the default 'active' class. Such as SuperFish, Menu Block
> 1 votes

---
Tags: theming
---


# Question
Title: On Rules Event Present Splash Screen To Flagged User
Hello i was wondering what would be the best path to take to achieve my goal. I am working on a website. I am using Rules and Flag modules. I was hoping to set up a rule that when a member has been flagged then an event would happen that would be like a big cartoon splash YOUVE BEEN FLAGGED (with an image and maybe possibly sound)

Im sure that this could be within the scope of drupal. Could anyone suggest a possible way of doing this?

Thanks

# Answer
One possible way is define your own Rules action against on that event.

Check the api: (assuming you are using D7)

http://drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook\_rules\_action\_info/7

Use jQuery to pop up an alert or whatever you like.
> 0 votes

---
Tags: rules, flags
---


title: Notice: Undefined offset: 1 error

text:
# Question
Title: Notice: Undefined offset: 1 error
I get this `Notice`:

> Notice: Undefined offset: 1 in custom\_context\_section\_condition-\>\_get\_url\_section() (line 110 of modules/custom/custom\_context/plugins/custom\_context\_section\_condition.inc).

```
  **
  * Get section by url
  */
  function _get_url_section() {
    // get the correct URL
    $path = $_GET['q'];
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $path = drupal_get_path_alias($_GET['q']);
    }
    $path = explode('/', $path);

    // Remove reserved part from path when defined as constant (see custom_context.module)
    if (in_array(arg(0), unserialize(URL_PATH_PART))) {
      array_shift($path);
    }
    // Remove reserved string from path when defined as constant (see custom_context.module)
    else if ($new_path = _custom_context_strpos_replace_arr($_GET['q'], unserialize(URL_PATH_STRING))) {
      $path = explode('/', $new_path);
    }

    // Get section by path
    $value = str_replace('-', ' ', $path[1]);
    $terms = taxonomy_get_term_by_name($value);

    // make sure we are getting the right section under the correct city
    // check if city context exist
    $city = NULL;
    $contexts = context_active_contexts();
    if ($contexts = context_active_contexts()) {
      foreach ($contexts as $key => $context) {
        if ($key == 'city') {
          $city = $context->conditions['custom_city']['city']['term'];
          break;
        }
      }
    }
    else {
      $city_context = new custom_context_city_condition(this, array());
      $cities = $city_context->_get_city($node);
      $city = array_shift($cities);
    }

    // check parent tid here
    foreach ($terms as $key => $term) {
      $parents = taxonomy_get_parents($term->tid);
      $parent = array_shift($parents);
      if ($city->tid != $parent->tid) {
        unset($terms[$key]);
      }
    }
    return $terms;
  }

```

This part:

```
if ($city->tid != $parent->tid) {
  unset($terms[$key]);
}

```

Also says: `Notice: Trying to get property of non-object`

Any idea whats wrong in my code?

# Answer
In the code above `$parent` is an array so `$parent->tid` is illegal. I am not sure what you are trying to find in the `$parent` but you should also note that the parent array has numeric indicies. So you probably have to do it this wat `$parent[45]` or `$parent[$city->tid]` depending on your requirement
> 3 votes

# Answer
For the second part, either $city or $parent isn't an object. They are NULL of an other type. Have a look with your debugger or dump the contens of the variables to see what they contain.
> 2 votes

---
Tags: 7
---


# Question
Title: Looking to make an opaque image/image caption in a teaser
I am interesting in making a teaser that just shows an image, which an opaque caption over it it saying blahblahblah READMORE and then a link to the page.

how would i do this? i'm not even sure where to start. i am using this with views kwick slider.

# Answer
I did this in CSS using the content title and the opacity feature of CSS. See below (modify for your purpose)

```
.view-id-programmes.view-display-id-block_1 .views-field-title {
margin-left: 10px;
position: absolute;
background-color:
white;
filter: alpha(opacity=68);
-khtml-opacity: 0.68;
-moz-opacity: 0.68;
opacity: 0.68;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
-khtml-border-radius: 15px;
border-radius: 15px;
padding: 8px;
}

```
> 2 votes

---
Tags: media
---


# Question
Title: Panels page - node template - comments won't appear
I'm using Drupal 7. I've got a Panel page set up that comprises a content type, followed by up to two page views based on taxonomy terms. The content type is set to allow comments, and when I use it alone (ie. not as part of the node template) the comments works fine. But when I have it as part of the panel page, no comments appear.

Can anyone think of what I'm doing wrong? I've asked this question on the Drupal forums but haven't received an answer.

Thanks

# Answer
Try checking if you are seeing the teaser view which may remove the comments, otherwise check to see if the panel settings allows the the comments to be shown
> 0 votes

---
Tags: panels, comments
---


# Question
Title: How to set fields value in Views PHP module?
How to define the fields value in Views PHP module?

# Answer
> 2 votes
First you need to load the node

```
$node = node_load($data->nid);

```

then you can either access

```
$value=$node->field_name['und'][0]['value'];

```

or assign

```
$node->field_time['und'][0]['value'] = $value

```

values to the node items. You may need to print out the content of the `$node` object to see the actual field\_name

```
$node_r = print_r($node, true);
watchdog('NODE PRINT OUT', "$node_r");

```

then view it in the recent log mesages

```
admin/reports/dblog

```

Ensure the DBlog (Database logging) core module is enabled

---
Tags: 7, views
---


# Question
Title: how to add a cck field for youtube embed code?
I have created a content type. I want to add a cck field to the content type where I can paste the youtube video embed code.

So that when I display the value of that field, a youtube video should display where I should be able to click on the play button and the video should play then.

Any module or any other idea for this problem?

# Answer
Use Drupal's Embedded Media Field. Here is a quote about it (from the module's project page):

> This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.
>
> The module is only an engine, and requires a supported module to function. These include 'Embedded Image Field', 'Embedded Video Field' and 'Embedded Audio Field'. These modules are included in the contrib folder of the module, so they can be easily activated from the module administration page.
> 0 votes

---
Tags: 7, files
---


title: How to hide certain links in forum?

text:
# Question
Title: How to hide certain links in forum?
I am wondering what is the best way to preserve viewing certain url patterns in forum posts only for authenticated users? So that guests can see something like "please log in to view the link", as per most stand-alone forums?

# Answer
Im not finding a module for that but what I would do is use jQuery to convert all links tags and their content in the "Content area" to \[Please login to view this link\] this is only loaded if the user is anonymous.

The function `.replaceWith()` http://api.jquery.com/replaceWith/ can be used
> 0 votes

---
Tags: nodes, users
---


# Question
Title: Is there a way sort View by results of "Options" Rate/Voting API widget?
I'm using the Rate module to allow voting on whether or not a given node is "Helpful" or "Unhelpful". I have a view with all nodes of this type, and the view includes a field for the Rate widget. I am having no problems displaying the widget itself, and the voting is working perfectly. However, I cannot for the life of me get any type of sorting functionality to work.

I've tried all of the sort types having to do with Vote, and all of them sort the nodes in no relevant order. It seems that the problem arises because I am using the value-type of "Options", and suggestions that I have found seem to require the value-type to be "Points". However, I'd much rather have user select between "Helpful" and "Unhelpful" than to use a thumbs up/down or +/- system of voting.

Does anybody know how I could sort by "most helpful" and "most unhelpful" and keep the value-type of "Options"?

# Answer
You have to add a relationship Content: Vote Results with proper data filters

* Value-type: Points
* Vote-tag: Your rate widget vote tag
* Aggregation-function: Number of vote

Then in views sort criteria add

* (Vote results) Vote results: Value (desc/asc)
> 5 votes

---
Tags: views, rating
---


title: Set title bar programmatically

text:
# Question
Title: Set title bar programmatically
I have to set, programmatically, the title value of pages, only for browser title bar (this value is stored in a metatags\_quick field) If I use "drupal\_set\_title" I change also the title displayed in page, I've only to change the window title.

# Answer
You can use `hook_preprocess_html()` to override this value:

```
function MYTHEME_preprocess_html(&$vars) {
  $vars['head_title'] = 'Some other title';
}

```

The title for the content won't be affected by that, just the `<title>` tag.
> 6 votes

---
Tags: meta-tags
---


# Question
Title: How to select every date before now in timestamp?
my database feild type is timestamp here is my code I used it but It also gave me today date I need every date before today

```
"SELECT * FROM {mytable} WHERE  date <".$now_timestamp."  "

```

please help me Thank you

# Answer
You could just use `strtotime()` to get yesterday's date instead of using a `DateTime` object:

```
$yesterday = strtotime('-1 day');

$sql = 'SELECT * FROM {mytable} WHERE date < :timestamp';

$result = db_query($sql, array(':timestamp' => $yesterday));

```
> 0 votes

# Answer
Timestamp is basically how many seconds have passed since 1st Jan 1970 UTC. To get the exact timestamp of Yesterday at 23:59 hour 59th second I can think of the following approach:

```
$yesterday = strtotime(((string) date('d-m-Y', strtotime('-1 day', time()))) . ' 23:59:59');

```

It's not really elegant, but if you really need exact time, then the above code should do the trick.

A breakdown of what's happening is:

```
$now = time();
$yesterday = strtotime('-1 day', $now);
$yesterday_date = date('d-m-Y', $yesterday);
$yesterday_date_string = (string) $yesterday_date . ' 23:59:59';
$yesterday_timestamp = strtotime($yesterday_date_string);

```
> -1 votes

---
Tags: datetime, forms
---


# Question
Title: How to find drupal 6 ubercart Persian translation?
Does anyone has drupal 6 ubercart persian translation or Anyone know how can I find it? Please help me Thank you

# Answer
You can find the direct link here:

http://ftp.drupal.org/files/translations/6.x/ubercart/ubercart-6.x-2.9.fa.po

In case you're interested (and for future reference) that comes from the Ubercart translation downloads page on Drupal.org.

You're pretty lucky, it was only generated 2 days ago!
> 1 votes

---
Tags: ubercart, i18n-l10n
---


# Question
Title: How to convert hook_filter and hook_filter_tips in Drupal 7?
I have trouble converting my custom modules in D7. Found a how-to here http://drupal.org/node/224333 but not so clear to me. This how my code in D6.

```
/**
 * Implementation of hook_filter().
 */
function custom_inline_filter($op, $delta = 0, $format = -1, $text = '') {

  switch ($op) {
    case 'list':
      return array(0 => t('Custom Inline Filter'));

    case 'description':
      return t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => '<!-- INLINE -->'));

    case 'settings':
      break;

    case 'no cache':
      return FALSE;

    case 'prepare':
      return $text;

    case 'process':
      return custom_inline_substitute($text);
      break;

    default:
      return $text;
  }
}

/**
 * Substitute inline image placeholder comments with inline image divs.
 * This function is usually called by hook_filter.process but also by template.php (used for RSS).
 *
 * @param $content
 * @param $node_id
 * @param $rss
 */
function custom_inline_substitute($content, $node_id = NULL, $rss = FALSE) {

  // Get nid from argument

  if ($node_id) {
    $nid = $node_id;
  }
  // Get nid when a node is displayed

  elseif (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
  }
  else {
    return $content;
  }

  // Instantiate inline image class

  $inlineImg = new CustomInlineImage($nid, $rss);
  return $inlineImg->substitute($content);
}

/**
 * Implementation of hook_filter_tips().
 */
function custom_inline_filter_tips($delta, $format, $long = FALSE) {

  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

```

# Answer
The code you should use in Drupal 7 is similar to the following one.

```
function custom_inline_filter_info() {
  $filters['custom_inline_filter'] = array(
    'title' => t('Custom Inline Filter'),
    'description' => t('Substitutes @inline tags with the uploaded inline images of the node.', array('@inline' => '<!-- INLINE -->')),
    'cache' => TRUE,
    'process callback' => 'custom_inline_substitute',
    'tips callback' => 'custom_inline_filter_tips',
  );

  return $filters;
}

function custom_inline_substitute($text, $filter, $format, $langcode, $cache, $cache_id) {
  // …
}

function custom_inline_filter_tips($filter, $format, $long) {
  if ($long) {
    return t('You may link to uploaded images within the current node using the wysiwyg editor toolbar icons.
      The Custom Inline Filter is to replace added image placeholders with uploaded inline images.'
    );
  }
  else {
    return t('Use the wysiwyg editor toolbar icons to display uploaded images inline.');
  }
}

```

The documentation for the input filter implementations is provided in more than one page:

For the parameters passed to the callbacks defined from an input filter module, see hook\_filter\_FILTER\_settings(), hook\_filter\_FILTER\_prepare(), hook\_filter\_FILTER\_process(), and hook\_filter\_FILTER\_tips().
In particular, it is relevant to know that:

* `$filter` is a filter object, not a string that identifies the input filter; it contains information about the input filter, but what an input filter implementation normally uses is `$filter->settings`, which is an array of settings defined from the input filter.
* `$format` is a format object, described in filter\_format\_save(); it doesn't contain information that an input filter normally uses.

To notice that only the first one is actually a hook; the others are callbacks. The documentation shows them as hooks because a limit of the module used to add documentation pages on Drupal.org API: A documentation page is added only if the function is contained in a module (a Drupal core module, or a third-party module), or it is a hook described in a .api.php file.
> 3 votes

# Answer
`hook_filter()` has been replaced with `hook_filter_info()`; the docs page has all the information you need on how to build a valid filter info array for Drupal 7.

`hook_filter_tips()` was removed in favour of the `tips callback` property of the array you return from `hook_filter_info()`. The basic example from the docs page should help it make sense, but there's a more advanced example on the same page if this is too simplistic:

```
$filters['filter_autop'] = array(
  'title' => t('Convert line breaks'),
  'description' => t('Converts line breaks into HTML (i.e. <br> and <p>) tags.'),
  'process callback' => '_filter_autop',
  'tips callback' => '_filter_autop_tips',
);

```
> 1 votes

# Answer
You can compare the D6 and D7 version of the node linke module. It's a filter module that has been ported from D6 to D7.
> 1 votes

---
Tags: 7, upgrading
---


# Question
Title: How to generate pdf file from a specific type of content?
I have a content type named "employees".

I want that when I add an employee(creating content of type employee) it should also generate a pdf file which will contain the data which I inserted during adding content.

And a link on that node appears stated that "Download the pdf".

# Answer
You can achieve this functionality with print module. For documentation click here. This module depends on the libraries you can install any of them.
1. dompdf
2. mPDF
3. TCPDF(Best in performance)
4. wkhtmltopdf
> 3 votes

---
Tags: 7, files
---


title: Year wise archive of blog using views

text:
# Question
Title: Year wise archive of blog using views
Is it possible to generate a year-wise archive of blogs using views?I need years listed like 2001,2002,...2012 and clicking on the year should display list of blogs for that particular year. I added a contextual Filter Content: Created year also , but it this query only

```
SELECT DISTINCT node.nid AS nid, EXTRACT(YEAR FROM((DATE_ADD('19700101', INTERVAL node.created SECOND) + INTERVAL 0 SECOND))) AS created_year, COUNT(node.nid) AS num_records
FROM
{node} node
WHERE (( (node.status = '1') AND (node.type IN  ('blog')) ))
GROUP BY created_year, nid
ORDER BY created_year ASC
```
.So this results in duplicate value for years

# Answer
> 2 votes
Check “Archive” view from standard Views install for start.
In your case you need to use contextual filter “Content: Created year” instead of “Content: Created year + month”.

# Answer
> 0 votes
I am trying to help you out.I am not sure whether it will work for you or not. (Drupal 7) Go to your views, then go to advanced and go to query settings and check "distinct".

---
Tags: views
---


# Question
Title: Failed to connect to your database server
I have uploaded my drupal commerce files. I get the message that my credential are wrong. I am just not sure whaht info they want for the

> In order for Drupal to work, and to continue with the installation process, you must resolve all issues reported below. For more help with configuring your database server, see the installation handbook. If you are unsure what any of this means you should probably contact your hosting provider.

> Failed to connect to your database server. The server reports the following message: SQLSTATE\[28000\] \[1045\] Access denied for user 'admin'@'localhost' (using password: YES).
>
> * Is the database server running?
> * Does the database exist, and have you entered the correct database name?
> * Have you entered the correct username and password?
> * Have you entered the correct database hostname?

I though I knew all of this information. I am running on my web host using admin as username. Any help would be greatly appreciated.

# Answer
Change the settings in your settings.php file. For remote server you should change this like below;

```
$databases = array (
  'default' => array(
    'default' => array (
      'database' => 'name of database uploaded on remote server',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```
* 'username' and 'password' are for the remote server
* 'host' is the hostname of the hosting server
> 3 votes

# Answer
You need to get the credentials for your database server form your webhost. This is usually a MYSQL database server, this tends to have a different username and password from the admin username and password
> 2 votes

---
Tags: database
---


# Question
Title: Search for content by title or add edit link to node
I have a Drupal 7 installation with a lot of content and it seems quite limiting that I cannot filter the content in the content administration screen by title. Is there a plugin that will add a filter to the title? I haven't found one so far after a lot of searching.

Alternatively the ability to add an edit link (near the nodequeue add/remove links) would be very useful. Is there a way to do that?

# Answer
> 2 votes
Yes, there's the Administration Views module, which replaces a bunch of the default admin pages with configurable views:

> Replaces administrative overview/listing pages with actual views for superior usability.

Features:

> * Filter all administrative views via AJAX.
> * Perform any kind of bulk/mass operations on items in administrative views.
> * **Filter content by title**, node type, author, published status, and/or vocabulary.
> * Filter comments by title, author, node title, or published status.
> * Filter users by name, ban/blocked status, or user roles.

You'll also need the Views module for this

---
Tags: nodes
---


# Question
Title: Change the site name programmatically for a specific page
I am trying to change the site name when a user enters specific pages on my website. I know the variable for the site name is `$site_name` and is being retrieved from the system.tpl.html file.

So I am trying to set different site names depending the URL; for example, when a user visits /about\_us, the site name should change.

In my template.php file, I have captured the path in a variable.

```
$path = drupal_get_path_alias();
if ($path == 'about_us') {
  $site_name = 'New title';
}

```

This won't work.

How can this be achieved?

# Answer
I think you mean page.tpl.php (not system.tpl.html, which isn't a standard Drupal file).

That said, you need to put your code in a `hook_preprocess_page()` function inside template.php, and actually alter the template variables that are passed in. At the moment you're just creating a variable called `$site_name` in the local scope, and Drupal has no way to pick that up.

Try this:

```
function MYTHEME_preprocess_page(&$vars) {
  $path = drupal_get_path_alias();
  if ($path == 'about_us') {
    $vars['site_name'] = 'New title';
  }
}

```

Have a look at Setting up variables for use in a template for a bit more info.
> 9 votes

# Answer
The site name is set in template\_preprocess\_page() using the following code.

```
  $variables['site_name'] = (theme_get_setting('toggle_name') ? filter_xss_admin(variable_get('site_name', 'Drupal')) : '');

```

In your theme, or module, you should use code similar to the following one. (Replace `mycode` with the short name of your module/theme.)

```
function mycode_preprocess_page(&$variables) {
  if (theme_get_setting('toggle_name') && drupal_get_path_alias() == 'about_us') {
    $variables['site_name'] = filter_xss_admin('The new site name');
  }
}

```

The call to filter\_xss\_admin() is not necessary, if you are not using the input obtained from a user.
You should always check the value returned by `theme_get_setting('toggle_name')`, as the site name could be toggled off for the theme currently used.
> 4 votes

---
Tags: theming
---


# Question
Title: Passing PHP objects and methods as strings to FormAPI
When working with objects, how do you pass a method to the FormAPI's \['#after\_build'\] feature?

For example, how can I pass $myObject-\>\_my\_after\_build\_function to \['#after\_build'\]?

---

**Non-OOP exampe of what I would like to accomplish:**

```
$form['#after_build'][] = '_my_after_build_function';

```

# Answer
`$form['#after_build']` is handled from the following code, contained in form\_builder().

```
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
    foreach ($element['#after_build'] as $function) {
      $element = $function($element, $form_state);
    }
    $element['#after_build_done'] = TRUE;
  }

```

Differently from other cases, Drupal doesn't use function\_exists() to check if the function exists. This means that using the following code works, since PHP 5.2.3.

```
$form['#after_build'][] = 'MyClass::_my_after_build_function';

```

As side note, it would work also with closures.

```
$build_function = function($element, $form_state) {
  // …
};

$form['#after_build'][] = $build_function;

```
> 1 votes

# Answer
I think your best bet is to call a function that will call

```
$myObject->_my_after_build_function();

```

One way that won't work most likely.

```
$method_name = _my_after_build_function;
"$myObject->{$method_name}"

```

Another shot in the dark that might work if using PHP 5.2.3+ http://php.net/manual/en/function.call-user-func.php.

```
"myObjectClassName::_my_after_build_function"

```

You can try the above 2 methods but with a `&` in front of it. http://www.php.net/manual/en/language.references.pass.php
> 3 votes

---
Tags: forms
---


# Question
Title: enable secure site only on certain pages
I am sending out user generation emails, but users can not access their one time login because of secure site from this link i see something about "Bypass Login Filter Page" and an option to set secure site login exceptions on certain pages but I can not find that anywhere.

http://drupal.org/node/98514

# Answer
> 2 votes
I have two options, but there could be more (quotes included are from their project pages):

1. Secure Pages:

> A small process which will redirect the required pages to a SSL version of the page.
2. Context SSL:

> Allow site administrators to make sure certain sections of their sites are always accessed through SSL.
>
> This module adds a reaction plugin to the Context module and thus benefits from all the flexibility that the Context module provides.

---
Tags: 6
---


# Question
Title: How to show parent terms in view for restricted nodes categorised with child term?
I have a number of nodes with individually restricted permissions. Logged-in users only see a selection of nodes depending upon their permission roles.

My view lists the taxonomy terms of the nodes, but only shows the terms containing nodes the user has permission to see by a relationship between the term and node (which is a good thing).

However, I have some instances where the following is the case:

```
Parent term (no nodes visible to user in this category)
    Child term 1 (10 nodes visible to user in this category)
    Child term 2 (no nodes visible to user in this category)

```

And the taxonomy view only lists "Child term 1", but I would also like to list "Parent term". How is this possible?

Thanks.

# Answer
In case anyone has the same issue, I gave up in the end and wrote a custom module since I find views a pain in the ass.

My module uses nested queries which is embarassing, but it's still fast to run (unless you have a massive list of taxononomy terms) so it doesn't matter too much for this purposes.

The module outputs a Drupal block, the content of which comes from this function:

```
function list_of_resource_tags(){

// Retrieve the logged in user
global $user;

// Select all "Metadata" terms for the nodes the logged in user
// has permission to see
$sql_terms = '
SELECT DISTINCT(term_data.tid) AS term_id, term_data.name, term_hierarchy.parent, term_data.weight
FROM node_access
INNER JOIN node ON node_access.nid = node.nid
INNER JOIN term_node ON node.nid = term_node.nid
INNER JOIN term_data ON term_node.tid = term_data.tid
INNER JOIN term_hierarchy ON term_data.tid = term_hierarchy.tid
WHERE node_access.grant_view = 1
AND node.status = 1 /* Published nodes */
AND term_data.vid = 9 /* Taxonomy terms of "Metadata" vocabulary only */
AND node_access.gid IN (SELECT rid AS roles FROM users_roles WHERE uid = %d) /* Logged-in user is granted permission to these nodes */
ORDER BY term_data.weight';

$result_terms = db_query($sql_terms, $user->uid);

$displayed_terms = array();
$output = '';
while ($row = db_fetch_object($result_terms)) {
    // If tag is top-level, just display and put in array
    if ($row->parent == 0 && in_array($row->term_id, $displayed_terms) == FALSE){
        $output .= '<div class="views-row"><a href="taxonomy/term/'.$row->term_id.'">'.$row->name.'</a></div>';
        $displayed_terms[] = $row->term_id;
    }
    // Test if we've already displayed the tags parent, if not, retrieve it
    else if (in_array($row->parent, $displayed_terms) == FALSE){
        $sql_parent = '
        SELECT *
        FROM term_data
        WHERE tid = %d';

        $result_parent = db_query($sql_parent, $row->parent);
        $row_parent = db_fetch_object($result_parent);

        $output .= '<div class="views-row"><a href="taxonomy/term/'.$row_parent->tid.'">'.$row_parent->name.'</div>';
        $displayed_terms[] = $row_parent->tid;
    }
}

return $output;
}

```
> 2 votes

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


# Question
Title: Are there plugins available for an "improved" Find Content admin interface?
One of our clients has a lot of content over a number of languages and has expressed that they don't really like the Filter/Sort options available on the Find Content page.

Are there any plugins available that present this information in a different manner...maybe something like Windows Explorer?

# Answer
> 2 votes
Have you tried VBO module? that, allows you create custom admin interface.

---
Tags: nodes, theming
---


# Question
Title: related news and articles block on content page based on tags
I have to create a block that contain five article based on the tags which is get displayed on the content page.Below is the view i created.

The output of this view is

here in the sidebar the article having the same tag in the content page is shown,but the content is getting repeated twice.can anyone tell me why the content in the block is getting repeated

# Answer
most probably you have more tags on the related content, so it is shown several times. try selecting "distinct values" in Query settings
> 0 votes

# Answer
You need to remove "Content: has term ...." in Filter Criteria

By the way, if you are interested in other modules to do this sort of task, you can check out, http://drupal.org/project/featured\_content

can

* List of content that has one of the same terms as the node being shown
> 0 votes

---
Tags: views
---


# Question
Title: How to display 'new' by unread forum posts (like drupal.org)?
If I go to my drupal tracking page while logged in I can see a red 'new' by forum posts that have changed since ive visited them. How can I add this functionally? I need to be able to do this without the advanced forum module.

This is the page but you wont see the red 'new' as your not logged in as me. See the attached image to see what I see. Thanks http://drupal.org/user/643368/track

# Answer
You can do this by a custom module.

Create a new table in database with 3 column \[ nid | uid | viewed\_time \] representing node view history.

And override hook\_node\_view(). The logic could be something like:

```
if (user is authenticated) {

  if (the node type is forum && nid with current uid is not in a row of view history table) {

    append 'new!' to node title

  } else {

    write [nid , uid, current time] to the view history table

  }

}

```
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How to consistently redirect after saving on Add/Edit node form?
When creating a new node doing a $form\['redirect'\] seems to work consistently, but doing the same redirect when editing an existing node doesn't. The problem only occurs when the admin overlay is shown.

Is there any way around this?

# Answer
> 0 votes
This does the trick ;)

The code below was added in hook\_form\_alter().

```
/* Set the desired redirect */
$form_state['redirect'] = 'node/add/lesson';

/* Then clear the "destination" value */
unset($_GET['destination']);
drupal_static_reset('drupal_get_destination');

```

---
Tags: redirection
---


# Question
Title: Is there a module for Drupal 7 similar to OG Membership Expiration?
OG Membership Expiration is for Drupal 6. Is there a similar module for Drupal 7?

# Answer
> 1 votes
What exactly do you want to achieve?

Assuming that you want to unsubscribe an user after certain time:

In Drupal 7, OG integrates really well with Rules module. It can fire many OG related action based on the condition / event you set.

You can use Rules Scheduler to schedule the action to be fired.

---

---

Furthermore, the OG Role Reference Field can:

* Grant a group role on a specific event
* Use rules\_scheduler to remove a group role after a certain amount of time

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


title: Setting text formats programatically

text:
# Question
Title: Setting text formats programatically
I have defined a new content type, that just has a body field, which I define in my install file:

```
$type = array(
        'type' => 'status_update',
        'name' => t('Status Update'),
        'module' => 'socmed',
        'base' => 'node_content',
        'description' => t('A Facebook-like status update.'),
        'has_title' => FALSE,
        'custom' => TRUE
        );

    // Turn off comments.
    variable_set('comment_status_update', 0);

    // Fill in remaining defaults, add a body field and save the node type.
    $type = node_type_set_defaults($type);
    node_add_body_field($type);
    node_type_save($type);

```

I would now like to

a) Create a new text format.

b) Assign that text format to be the default for this content type's body.

c) Set permissions on the text format for normal authenticated users, so that this text format is the only option.

I want to package this up as a module, so I would like to do so programatically, but I'm not sure how to go about it. Any pointers on any of these steps? Thanks!

# Answer
You're going to want to create your new input format separately (probably in a module), assign it to the fields in your content type, then export the fields again and bundle in your module.

Not knowing how complex your new input format is, best advice is to grab the examples module and check out the filter\_example module for a good test case of how to create a new input format.

Once you have the input format created, go back to your content type and under "Structure \> Content Types \> Manage Fields" set the default input format for these fields to your new input format and export your fields to your module.
> 0 votes

---
Tags: nodes, input-formats
---


# Question
Title: Best practices for implementing custom caching?
For every instance of every type of entity, I generate a number of caches, named something like: `[module_name]__[entity_type]__[entity_id]__[string_depending_on_where_the_cache_came_from]`

Now whenever a entity is updated, I want to drop all caches starting with the relevant entity type and id.

How should I store/clear these caches?

Currently I just cache\_set(), but that presents a problem when I want to clear, as I don't know the names of all the relevant caches. Is it safe to drop cache entries with a db\_delete()?

# Answer
To delete entries from a cache, you should use cache\_clear\_all(). The reason is that the used cache implementation could not use a database table in the active database. That is what happens with the DrupalDatabaseCache class, but it should not be true for every classes.

If you look at \_cache\_get\_object() (the function called by cache\_get() and cache\_set()), you will notice it contains the following code.

```
  static $cache_objects;
  if (!isset($cache_objects[$bin])) {
    $class = variable_get('cache_class_' . $bin);
    if (!isset($class)) {
      $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
    }
    $cache_objects[$bin] = new $class($bin);
  }
  return $cache_objects[$bin];

```

The class for the cache implementation could be different for each cache bin store, and even the default one could be changed.

Private update status cache system explains exactly why the normal cache functions are not used in \_update\_cache\_clear(), \_update\_cache\_get(), and \_update\_cache\_set(). (Emphasis is mine.)

> We specifically do NOT use the core cache API for saving the fetched data about available updates. **It is vitally important that this cache is only cleared when we're populating it after successfully fetching new available update data. Usage of the core cache API results in all sorts of potential problems that would result in attempting to fetch available update data all the time, including if a site has a "minimum cache lifetime" (which is both a minimum and a maximum) defined, or if a site uses memcache or another pluggable cache system that assumes volatile caches.**
>
> The Update Manager module still uses the {cache\_update} table, but instead of using `cache_set()`, `cache_get()`, and `cache_clear_all()`, there are private helper functions that implement these same basic tasks but ensure that the cache is not prematurely cleared, and that the data is always stored in the database, even if memcache or another cache backend is in use.

The Update Manager has specific needs that are necessary because attempting to fetch update information too frequently would cause issues with Drupal.org servers, considering that the Update Manager can potentially fetch update information from any site running Drupal.

In your case, you could use `[module_name]__[entity_type]__[entity_id]__[string_depending_on_where_the_cache_came_from]` as cache ID for a single cache bin store. In the case you need to delete all the entries for a entity, you could use the following code.

```
cache_clear_all("{$module}__{$entity_type}__{$entity_id}__", $bin, TRUE);

```

If you cannot get the value to assign to `$module` when you are clearing the cache, or you want to delete the cache entry independently from the module for which the data has been cached, then you can use a different cache ID, such as `[entity_type]__[entity_id]__[string_depending_on_where_the_cache_came_from]`, or `[entity_type]__[entity_id]__[module_name]__[string_depending_on_where_the_cache_came_from]`. `cache_clear_all()` deletes all the cache entries with a cache ID starting with the string passed as argument, when `$wildcard` is `TRUE`, and the cache ID is not `'*'`. In this case, the cache would be cleared with the following code.

```
cache_clear_all("{$entity_type}__{$entity_id}__", $bin, TRUE);

```
> 6 votes

# Answer
I can't think of a good reason why dropping the entries manually would cause a problem. This assumes, of course, that you're using MySQL as the backend for your particular cache; although I think the same applies to any other type of cache backend, the method to clear just wouldn't necessarily be a database query.

If you take the core update module as an example, it bypasses the `cache_*` functions and clears its cache manually:

```
function _update_cache_clear($cid = NULL, $wildcard = FALSE) {
  if (empty($cid)) {
    db_delete('cache_update')
      // Clear everything except fetch task information because these are used
      // to ensure that the fetch task queue items are not added multiple times.
      ->condition('cid', 'fetch_task::%', 'NOT LIKE')
      ->execute();
  }
  else {
    $query = db_delete('cache_update');
    if ($wildcard) {
      $query->condition('cid', $cid . '%', 'LIKE');
    }
    else {
      $query->condition('cid', $cid);
    }
    $query->execute();
  }
}

```

I always think "if it's good enough for core, it's good enough for me" :)
> 8 votes

---
Tags: 7, caching
---


title: Relation module tutorial

text:
# Question
Title: Relation module tutorial
I could not find good quality of tutorials on Internet for learning Relation module . Could anyone suggest some links for good documentation/tutorial for relation module ? Thank you .

# Answer
> 3 votes
Well, there are a number of screencasts available on the module project page as well as the official module documentation. Assuming you've already tried these and still need help, there are two possibly less obvious places you can go for 'tutorials':

* Look through the source code of the module. Many of the more popular contrib modules have excellent documentation in the source on how to use the specific functions, methods, etc.
* Scan the issue queue for relations. Other users may have some of the same questions you have (especially issues filed under 'support request') that may be of use to you.

Finally, most modules won't have really useful tutorials on how to use them and rely on the user community to help each other define what is needed. One of the best things you can do to help is to ask questions as you explore the relations module, either here or on Drupal.org, as others may have the same questions. As you get more confident, you can help by adding some of your experience back as a tutorial for other beginners.

---
Tags: 7, entities
---


# Question
Title: View output that goes from list to three-column grid?
I'm working on a news site, which has a front page generated via Views.

Originally I was told it was just a straight list of stories, so I used the unformatted list display type, using on of the fields ("section") to group rows. Now, however, I'm being told it'd be nice to have the first ten stories display as an unformatted list, then have the next ten display in some sort of three-column configuration (similar to the "grid" display type).

Any idea how I'd do that? Thanks!

# Answer
> 1 votes
I am thinking to create two views. And add them one above the other in a panel. The first view has 10 items in an unformatted list then the next ten would have a grid display of the same content but with an offset of 10.

---
Tags: views, theming
---


# Question
Title: How to add an existing custom field to a new content type
In my new module I am writing, I am creating a new content type. In this new content type, I want to attach custom fields for a media player: the media player from MediaFront and a File field with a Media File Selector widget type.

As I understand it, these fields are already defined; I just need to create an instance of each field. How do I create an instance of each field, and then configure the extra parameters?

I haven't come across any good tutorials on how to do this.

# Answer
> 1 votes
This has been asked before, for a brief example see Clive's answer here. The easiest thing to do is:

1. create your field and attach it to an entity with the UI logged in at: Admin -\> Structure -\> Content Types -\> Manage Fields
2. use the code snippet in the below link, supplying your own `$entity_type`, `$field_name` and `$bundle_name` to get the `field_create_instance()` code outputted directly for you to copy/paste into your modules' `hook_install()`.
3. ...if you get good enough to know the Drupal Field API to build these `$settings` and `$config` arrays for fields without this code snippet -- more power to you .... I still use this code snippet myself, it saves time.

---
Tags: entities
---


# Question
Title: Is it possible to serve a theme from outside the web root?
We have a need to keep a proprietary theme in a directory that isn't readable or writable by a client.

At the same time, the client needs to be able to do standard Drupal updates (ie, they will have full control of the web root of the Drupal installation, but nothing above that).

What's the easiest/best way to accomplish this, assuming it's possible?

# Answer
If you have

```
Options +FollowSymLinks

```

set for the `DocumentRoot` for your Drupal site, you can put the proprietary theme anywhere you want as long as you create a symlink to it somewhere Drupal searches for themes (eg, sites/all/themes).

Just keep in mind that Apache needs to be able to read it. Whether the client can read it directly is a permission issue, but if Apache can read it a savy client can get it via custom PHP.
> 3 votes

---
Tags: 7, files
---


# Question
Title: How to structure a "many-to-many" relationship between nodes
I would like to have 2 node types, Sellers and Products. Each seller can have many products, and each product can have many sellers. Also, the relationship between Sellers and Products would need to contain a price.

What would be the best way to create that relationship, making it easy to list all the Products a seller sells on their page (with prices), as well as listing all of the Sellers selling a product on their page (with prices)?

# Answer
> 13 votes
You can achieve by these two modules: Field Collection and Entity Reference,

You can create Field Collection field (unlimited instances) to Product, the collection field (act like a wrapper) contains an Entity Reference field references to Seller, and a price field for that seller.

Some screenshot for you:

##

##

##

---
Tags: nodes
---


# Question
Title: Node access-control modules for members-only pages
I am building a straightforward Drupal 7 site that has public pages and members-only pages. There is just one kind of member. Right now access control does not need to be finer than that. It seems my choices are the modules Content Access, Nodeaccess, Simple Access, node privacy byrole, Taxonomy Access Control and Taxonomy Access Control Lite. To achieve what I need, I could control access either by role, or by using a taxonomy term like "members-only". Both would work.

All these modules are still under development for D7, and are in varying stages of (un)completion and bugginess. For some, development seems erratic or stalled. In addition, their UX's are of varying complexity for the non-sophisticated content editor.

(Another alternative to all of these modules is to create a separate content type for members-only pages, and just use the built-in content-type permissions. That seems inflexible and duplicative, but it is a way out.)

My question is a practical one, given the current reality: which one would you choose for use now or in the next few months, for this use case, and which one seems to have the brightest future?

**FOLLOWUP (7 months later):** After trying Content Access (CA) and Taxonomy Access Control (TAC), I settled on TAC. Content Access can do by-node access control, but the UX is not simple, and I wouldn't want to subject my editors to it. I find that using a taxonomy term to designate access can essentially be an abstraction mechanism: a single term can represent a complicated set of access choices. For one content type (calendar events), I vary the the access based on taxonomy. For another (members-only pages), I just use a one-term taxonomy vocabulary that is a required field (so its value can't change). So for me, TAC's functionality is a superset of CA. I also needed Field Permissions to selectively expose the fields in calendar events.

# Answer
Obviously there are a lot of factors that you should consider before deciding whether a module has a "bright" future or not. A very good blog post that describes all the factors that should be considered can be found here (it's based on the old theme of drupal.org but you can still get the point).

The final decision that you'll take is kind of a "feeling" that you'll get after you 've spent a lot of hours testing modules and banging your head against the wall, only to realize that the module that you picked is not the correct one. However, I will give you the results of a small script that I have and I run in such cases. It gives you the usage count of the modules that you provide as an input, and here they are:

* content\_access: 24939 users
* node\_access: 1295 users
* simple\_access: 1623 users
* node\_privacy\_byrole: 3399 users
* taxonomy\_access: 6037 users
* tac\_lite: 3397 users

Note that these results are just information pulled from the drupal.org website and you should not use them to compare the modules. They are just indications that tell you how other users "feel" about those modules that you are examining.

So, to answer your question, I would go for content access module since it supports the per-role access that you mentioned, there are tons of sites that are using it (meaning that it is highly unlikely to be discontinued), its author is someone that has done remarkable work for drupal and the D7 version was updated -relatively- recently.

P.S: if you want the script, lemme know. It's proven very handy in many cases.
> 4 votes

# Answer
You might be interested in the Premium Content module, http://drupal.org/project/premium\_content, which works in a way similar to what it seems you are after.
> 2 votes

# Answer
Providing access permission to a basic page seem's difficult in Drupal . It is however possible to grant permissions for view's created pages. Thus making it simple to just add a view instead of a basic page!! It even hides the menu item!!
> 1 votes

---
Tags: 7, users
---


# Question
Title: Sending system e-mails do not work in spite system says it sends e-mail
So, my Drupal 7 does not dispatch those messages (notify user on registration and such) in spite the system says it sended e-mail. Other scripts (like send the web page by email) work well, though!

I am on dedicated unmanaged (i manage it ;) ) Debian server with LAMP, and for e-mail I installed Postfix.

If someone got clues i would be grateful!

# Answer
> 1 votes
If the system log reports it is sent, mostly likely it was sent. Perhaps those mail went to SPAM box? If that is the case, check if you have Reverse DNS set up for your domain.

Besides, you can utilize 3rd party email service (such as Gmail) as your Drupal mail system. Check out SMTP module.

---
Tags: users, emails
---


# Question
Title: Use part of Date field for grouping / sorting in View
I'm creating a Schedule page. I created a Schedule Item content type with a Date field which tracks the date and the time. I want to create a View which lists Schedule Items grouped by Date alone.

My data looks like:

* 2012-07-01 08:00, Event 1
* 2012-07-01 11:00, Event 2
* 2012-07-01 11:30, Event 3
* 2012-07-02 09:00, Event 4
* 2012-07-02 10:30, Event 5

I would like this to be displayed grouped by the Date portion of that Date/time object so it looks like this:

* 2012-07-01
* + 08:00, Event 1
* + 11:00, Event 2
* + 11:30, Event 3
* 2012-07-02
* + 09:00, Event 4
* + 10:30, Event 5

I tried setting the Grouping on my View to use my Date field using a format that only displayed the Year-Month-Day. However, when doing the grouping, it is still grouping on the real value and not the displayed value. Meaning that since each Date/time value is actually different in the time portion, each value is being used as a separate group.

Is there a way I can generate a virtual field which only contains the Date portion of my Date/time field so that I can use it to properly group all items by Day?

# Answer
> 0 votes
I ended up solving it this way:

I added a Date field to my content type which only tracked the Year-Month-Day. Then I added a Time field to my content type which only tracked the Time.

In addition to making the grouping easier, it also represented my data is a much better fashion.

# Answer
> 1 votes
Go to your view and add an extra date field, but hide it from display. Use that as the grouping field. Then create a views template for that field. You can look at the template name suggestions, something like `views-view-field--field-date-1.tpl.php` would work

The default content of that file would be

```
<?php print $output; ?>

```

But you need to replace that with

```
<?php print date('F Y', strtotime($row->node_data_field_date_field_date_value)); ?>

```

Where 'F Y' is the PHP date string format http://php.net/manual/en/function.date.php

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


# Question
Title: Drupal 7 default Forum styling for custom content type?
Im using Drupal 7's forum module. Its working great but I need to also make a custom content type a forum.

I can allow comments on this custom content type, but can I make it have the same styling as the default forum content type?

UPDATE - The reason I need this is there are 2 user roles. Only registered users can see forums at all. Users with a special role can see private forums aswell.

# Answer
> 1 votes
By 'have the same styling', I'm assuming what you mean is have the same structure and functionality as the Drupal core forum (i.e. threaded discussions). You can always modify the content template to match the same layout and css styling of the core forum module but just enabling comments won't give you the same functionality as forums. The forums module uses comments but adds another layer of management on top which is where you get your threaded discussion. A comments-only content-type would also not integrate with forum add-ons like Advanced Forum.

You're best option is to create two distinct forums and then (as @frazras notes) use Forum Access module to control access based on your criteria.

---
Tags: 7, comments, nodes
---


# Question
Title: importing blogs from another database with different content type fields
I need to import blogs from a drupal database to another drupal database. Both the old and new drupal content types have different fields. I would like to get some hints about the sql queries or drupal api functions to be used and the process to be used to get data from old database.I have access only to the mysql database and not ftp/admin side.

# Answer
> 1 votes
Try using the feeds module and export to a CSV file then import the data under the new respective fields. You may need to add extra fields to the new content type to prevent data loss

---
Tags: migrations, database
---


title: Access published date via node_load()

text:
# Question
Title: Access published date via node_load()
The node `created` field is not the same time as when it was finally published (or I guess maybe promoted, instead of published).

I've loaded a node using node\_load() in my module code, how can I access when this node was actually published?

# Answer
> 4 votes
The node object does not store the "publication date", install this module to create that field http://drupal.org/project/publication\_date

Some details from the module's project page:

> The Publication Date module adds a "Published on" date for each node, containing the date when it was first published.
>
> Without this, the only dates available for nodes are their created date and changed date, but these are often insufficient to meet the needs of publishing workflows. Sorting nodes by their created date doesn't account for content which is held in draft form for a time while being readied for publication. Sorting nodes by their changed date fails to account for content needing minor corrections after being published.
>
> The "Published on" date can be used in any templates, or views. Publication date also incudes integration with the Display Suite module and has entity wrapper support, so it can integrate with modules like Rules that use the Entity API module.
>
> The "Published on" date can be edited through the node edit form, allowing a custom published date to be set. If a custom date is set prior to publication, it will be respected when the node is published. The publication date is also retained when a node is unpublished and then republished.

---
Tags: 7, nodes
---


title: Complex delayed unpublishing

text:
# Question
Title: Complex delayed unpublishing
I want a node that the user can edit the published setting on. (Via publish\_content)

It should be unpublished by default 4 months after being published, but paused not reset when unpublished.

Also, there should be a cck field allowing the user to alter the time published beforehand but this should not be editable if the content has already been published and is in delay (Or unpublished and paused).

I've been looking at rules since this seems to be a pretty complex task, but I'm not exactly sure how to go about it and I'm new to rules.

After the initial (4 month) delay is over the user should be allowed to start this whole thing again.

# Answer
> 0 votes
Have a look at the rules scheduler module (part of the rules module). You should be able to do most of the things with date calculation and rules scheduler.

If you're missing something in rules you might have to implement your own rules action. Have a look at hook\_rules\_action\_info().

---
Tags: rules, nodes
---


title: FB connect in Drupal6

text:
# Question
Title: FB connect in Drupal6
I am working in drupal-6 trying to do facebook connect button.

I installed fboauth module sucessfully. now i also got fb connect button and also able to connect successfully. now first time i allow application for this. it works successfully. Now When i logout from website as well as from Fb. then try to connect fb coonect it goes to app page after login. i want it directly goes to my website. when i logged in ..

Any body have idea?

# Answer
Got the Problem. FB changes their structure of application. Not a bug
> 0 votes

---
Tags: blocks, social-network
---


title: Submit form and redirect to same form

text:
# Question
Title: Submit form and redirect to same form
I have contact webforms in all pages on footer including the front page template. I want the user to be redirected to the same page they are in and but the message that the form have been submitted should be visible.

How can i do that? Is there a built in method.

# Answer
> 1 votes
A solution that comes in mind is:

* Install Rules and Webform Rules
* Go to your webform and at form settings set Redirection location: No redirect (reload current page)
* Add a rule, when a webform is submitted to fire action "Show a message on the site".

---
Tags: 7, webforms, status-messages
---


# Question
Title: how to have a another page.tpl.php file in drupal with different regions and blocks?
Well, here is the problem. In my site I want to create a plain template and add my own regions and my own blocks. So when the user visits for example www.example.com/register-now the blocks will be different from the main page. I dont like disabling the blocks because when you open Firebug the blocks can be still be seen.

So I have read in this article that you have to create a new `.tpl.php` file. So in my case I created the `page__register-now.tpl.php` file. and put that under `drupal/sites/all/themes/ninesixty/` directory.

Then I opened the `template.php` file and tried the below code:

```
function ninesixty_preprocess_page(&$vars, $hook) {
  $path=drupal_get_path_alias();

  if($path == 'register-now'){
    $variables['theme_hook_suggestion'] = 'node__register';
  }
}

```

# Answer
If your path to the register page is `www.example.com/register-now` then you only need to name the page template file appropriately and Drupal should do the rest, you shouldn't need to add anything to `template.php`.

From what you've written, the name of the page template file is wrong. It needs to be renamed to: `page--register-now.tpl.php` (notice the underscores turned to dashes).

After you rename the file (usually after adding any additional template files), make sure to clear all caches from `admin/config/development/performance`.

EDIT: If your page is a node, you can't use the Alias path in the template file, it actually has to be the internal path to the node, e.g. `page--node--123.tpl.php` where 123 is your node's ID.

> The rest are based on the internal path of the current page. **Do not confuse the internal path to path aliases which are not accounted for**.

See here
> 5 votes

---
Tags: 7, theming
---


title: Display block only on a specific page

text:
# Question
Title: Display block only on a specific page
I would like to display a block only on the `[root]/dashboard` page, and I would like to do this from my custom module defining the block, not from the Drupal admin interface. How can I do this? Thanks you!

Also, where would this condition be better to be written? In `hook_block_view()` within the module or in the block template file?

# Answer
> 2 votes
The code would go in `hook_block_info()`. You can use the `pages` property to define the list of pages the block should be shown on. e.g.

```
$blocks['recent'] = array(
  'info' => t('Recent content'),
  'pages' => 'dashboard',
  'visibility' => BLOCK_VISIBILITY_LISTED
);

```

# Answer
> 0 votes
In `hook_block` you can assign your block to any page.

```
 $block = array();
    if ($op == 'list') {
$block[1] = array(
            'info' => 'block info',
            'weight' => -1,
            'status' => 1,
            'region' => 'content_bottom',
            'visibility' => 1,
            'pages' => "test/*" . "\n" . "test2/*",
        );
    }

```

Where 1 is the delta of the block.

---
Tags: blocks
---


title: How to create a new Solr server URL

text:
# Question
Title: How to create a new Solr server URL
I am using Tomcat with Apache Solr to search the content on my site.

For testing purposes, I use http://localhost:8080/solr to connect to the Solr server, but I would like to change this to http://development.site:8080/solr.

How can I achieve this?

# Answer
> 0 votes
You can configure your Solr server from /admin/config/search/search\_api/server/apache\_solr/edit.

---
Tags: 7, search
---


title: Get a list of all enabled block deltas

text:
# Question
Title: Get a list of all enabled block deltas
I need an array of all enabled blocks' deltas.

For example, if I display the array, it should output the block deltas e.g. search\_form, user\_new, user\_login, *and not the block titles e.g Search, User* etc

I've found a few candidates: http://api.drupal.org/api/drupal/modules!block!block.module/function/block\_list/7

http://drupalcontrib.org/api/drupal/drupal%21modules%21block%21block.module/function/block\_get\_blocks\_by\_region/7

But they all crash my site. Really can't get it to work, please give some examples that works for you.

# Answer
> 2 votes
I can't imagine why your site is crashing using the two functions you link to (Drupal calls them both internally so it certainly shouldn't be), but you can use the following custom query to grab that data directly from the database:

```
$query = db_select('block', 'b')
  ->condition('theme', $your_theme_name)
  ->condition('status', 1)
  ->condition('region', -1, '<>');

$query->addExpression("CONCAT(module, '_', delta)", 'delta');

$deltas = $query->execute()->fetchCol();

// $deltas now contains a list of deltas for all enabled blocks in the provided theme

```

---
Tags: 7, blocks
---


# Question
Title: hook_taxonomy_term_view_alter is not being called
On my Drupal 7 site, I have a module which needs to determine the type of page being shown / being loaded.

I first implemented hook\_entity\_view\_alter. Doing this:

```
/**
 * Implements hook_entity_view_alter
 */
/*
function rsc_search_entity_view_alter(&$build, $type)
{
  echo "$type <br/>";
  echo $build['#entity_type'].'<br/>';
}

```

shows the info I need, so I know that the hook is being called. BUT, on taxonomy term pages, nothing shows up, although there should be an entity with type 'taxonomy\_term'. See the last few lines of code at: http://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy\_term\_view/7

So I tried the next thing, which is implementing hook\_taxonomy\_term\_view\_alter to catch those term pages:

```
/**
 * Implements hook_taxonomy_term_view_alter
 */
function rsc_search_taxonomy_term_view_alter(&$build)
{
  $var = $build;
  $build['extra'] = array('#markup'=>'nothing');
  echo 'tax_term';
  if ($build['#view_mode']=='full')
  {
    echo '<pre>';
    var_dump($build);
    echo '</pre>';
  }
}

```

This, however, NEVER DOES ANYTHING!

As far as I understand the documentation, I * used the correct function names * used the correct function parameters * remembered to clear the caches

Any ideas on what went wrong? Why can't I implement taxonomy alteration hooks?

**EDIT**

Clive asked whether I am using views taxonomy. But I am using a custom taxonomy page, which still calls taxonomy\_term\_view

```
function CSL_custom_admin_menu_alter(&$items)
{
  $items['taxonomy/term/%taxonomy_term'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'file' => 'taxonomy.pages.inc',
    'file path' => 'sites/all/modules/CSL_custom_admin'
  );
}

```

Here is an extract from my taxonomy.pages.inc:

```
/**
 * Menu callback; displays all nodes associated with a term.
 *
 * @param $term
 *   The taxonomy term.
 * @return
 *   The page content.
 */
function taxonomy_term_page($term)
{
  drupal_set_breadcrumb(CSL_taxonomy_breadcrumb($term));

  drupal_add_feed('taxonomy/term/' . $term->tid . '/feed', 'RSS - ' . $term->name);

  $subs = CSL_taxonomy_subs_count(taxonomy_get_tree($term->vid, $term->tid, 1));

  $nids = CSL_taxonomy_nids($term->tid, TRUE, variable_get('default_nodes_main', 10), ( isset($term->field_enable_sort['und'][0]['value'])&&$term->field_enable_sort['und'][0]['value'] ) || ( isset($term->field_toelaat_sorteer['und'][0]['value'])&&$term->field_toelaat_sorteer['und'][0]['value'] ) );

  $build = array();

  // Add term heading if the term has a description
  if (!empty($term->description))
  {
    $build['term_heading'] = array(
        '#prefix' => '<div class="term-listing-heading">',
        '#suffix' => '</div>',
        'term' => taxonomy_term_view($term, 'full'),
        '#weight' => 1
    );
  }

  if ($nids && $subs)
  {
    $build['subterms'] = array
    (
        '#prefix' => '<div class="taxonomy-subterms-wrapper">',
        '#suffix' => '</div>',
        'subterms' => array
        (
            '#theme' => 'CSL_custom_admin_taxsubstable',
            '#rows' => $subs,
            '#weight' => 2
        )
    );

    $build['nodes'] = array
    (
        '#prefix' => '<div class="taxonomy-nodes-wrapper">',
        '#suffix' => '</div>',
        'nodes' => node_view_multiple(node_load_multiple($nids)),
        '#weight' => 3
    );
  }
  else if ($nids) // no subs
  {
    $build['subterms'] = array
    (
        '#prefix' => '<div class="taxonomy-subterms-wrapper">',
        '#suffix' => '</div>',
        '#markup' => '<strong>'.t('This term has no subcategories.').'</strong>',
        '#weight' => 2
    );

    $build['nodes'] = array
    (
        '#prefix' => '<div class="taxonomy-nodes-wrapper">',
        '#suffix' => '</div>',
        'nodes' => node_view_multiple(node_load_multiple($nids)),
        '#weight' => 3
    );
  }
  else if ($subs) // no nids
  {
    $build['subterms'] = array
    (
        '#prefix' => '<div class="taxonomy-subterms-wrapper">',
        '#suffix' => '</div>',
        'subterms' => array
        (
            '#theme' => 'CSL_custom_admin_taxsubstable',
            '#rows' => $subs
        ),
        '#weight' => 2
    );

    $build['nodes'] = array
    (
        '#prefix' => '<div class="taxonomy-nodes-wrapper">',
        '#suffix' => '</div>',
        '#markup' => '<strong>'.t('Refer to one of the subcategories for articles.').'</strong>',
        '#weight' => 3
    );
  }
  else // nothing to see
  {
    $build['nodes'] = array
    (
        '#prefix' => '<div class="taxonomy-nodes-wrapper">',
        '#suffix' => '</div>',
        '#markup' => '<strong>'.t('There is currently no content in this category.').'</strong>',
        '#weight' => 3
    );
  }

  $build['pager_top'] = array(
      '#theme' => 'pager',
      '#weight' => -5
  );

  $build['pager_bottom'] = array(
      '#theme' => 'pager',
      '#weight' => 5
  );

  return $build;
}

```

I know my module names should not start with a capital letter (CSL\_), but that should not affect anything here.

# Answer
> 2 votes
It is a bug / missing feature in Drupal Core!

The taxonomy module does not exactly conform to standards... For example, where an $entity of type 'node' has the properties *bundle* and *content*, 'taxonomy\_term' doesn't. Also, in core taxonomy, **\_view hooks are never called** and \_alter hooks are only called when the taxonomy term has a non-blank description field. There are some patches available in this discussion, but I wrote my own, because I override taxonomy.pages.inc in any case.

I see a lot of modules struggle with this, and it is still an arguing point for Drupal 8. http://drupal.org/search/apachesolr\_search/hook\_taxonomy\_term\_view

Thanks for pointing me in the right direction, Clive. I would otherwise not have looked at my taxonomy.pages.inc

An excerpt from my new custom taxonomy.pages.inc follows. I hope this helps someone!

```
function taxonomy_term_page($term)
{
  // set breadcrumbs
  // add rss feeds
  // count subcategories and nodes

  $build = array();

  $view_mode = 'full';
  $langcode = $GLOBALS['language_content']->language;

  // NB Always call this, even if no description,
  // because other modules need hook_taxonomy_term_view_alter
  // and hook_entity_view_alter
  $term_renderarray = taxonomy_term_view($term, $view_mode, $langcode);

  // Add term heading if the term has a description
  if (!empty($term->description))
  {
    $build['term_heading'] = array(
        '#prefix' => '<div class="term-listing-heading">',
        '#suffix' => '</div>',
        'term' => $term_renderarray,
        '#weight' => 1
    );
  }

  // add stuff to $build['subterms'] and $build['nodes']

  $build['pager_top'] = array(
      '#theme' => 'pager',
      '#weight' => -5
  );

  $build['pager_bottom'] = array(
      '#theme' => 'pager',
      '#weight' => 5
  );

  // Keep modules that expect $entity->content to exist happy
  // otherwise this causes errors with implementations such as
  // field_conditional_state_entity_view()
  $term->content = $build;

  // Allow modules to make their own additions to the term.
  module_invoke_all('taxonomy_term_view', $term, $view_mode, $langcode);
  module_invoke_all('entity_view', $term, 'taxonomy_term', $view_mode, $langcode);

  return $build;
}

```

whew :)

---
Tags: taxonomy-terms, hooks
---


title: Meta tags not showing on front page

text:
# Question
Title: Meta tags not showing on front page
I'm using the module "metatag" to make my website SEO friendly. This works very well for all pages except the front page.

I go to modules -\> Meta tags -\> Settings -\> Global: Front page

There I set a description. But this description isn't shown if you search the site directly in google. All other pages are working great, with the correct description.

When I look at the source, I see no meta data included at the front page.

# Answer
> 1 votes
You need to assign a node to be 'front'. Otherwise the meta won't show.

---
Tags: 7, nodes, meta-tags
---