# Question
Title: Find out what time was last comment posted on a node
I want to put a new icon next to node listed in a block if it was created/updated or commented on in last 1 day. I'm able to fetch all the nodes which were created/updated or commented on sorted in descending order of their time of creation/update or comment.

This is my code in template.php:

```
 function analytic_preprocess_views_view_fields(&$vars) {
     $viewName = $vars['view']->name;
     $view1 = "view1";
     $view2 = "view2";
     $view3 = "view3";

    if (strcasecmp($viewName, $view1) == 0 ||
        strcasecmp($viewName, $view2) == 0 ||
        strcasecmp($viewName, $view3) == 0)
      {
           if (isset($vars['view']->name)) {
              $created = $vars['row']->node_created;
              $changed = $vars['row']->node_changed;

              $cexpire = $created + (1 * 24 * 60 * 60); //one day later
              $uexpire = $changed + (1 * 24 * 60 * 60); //one day later

              if (($cexpire > time()) || ($uexpire > time())) {
                    $vars['newicon'] = '<img src="'. path_to_theme().'/images/new_icon.gif">';
              }
       }
    }
}

```

Problem is that when I commented on an older article which I created few months back, it was accurately displayed at the top of my block but 'NEW' icon didn't appear next to it and I saw this error on the page:

`Notice: Undefined variable: newicon in include() (line 28 of /home/user/public_html/sites/all/themes/analytic/views-view-fields--viewname.tpl.php).`

where I'm displaying/rendering this image.

My understanding is that for the node which just has a new comment I don't have the time of update. How do I get that? Like I have `node_created` and `node_changed`.

# Answer
`node_created` and `node_changed` refers only to node itself.

In views you should be able to add relationship " Comment: Last Comment". Then, you'll have filter and field like "Comment: comment time". You can add this field as non-display one and then use it in templates for fields after it. Will be simpler and more reliable than preprocess functions.
> 1 votes

---
Tags: views, blocks, comments, nodes
---


title: Filter a field (with regex) in a view

text:
# Question
Title: Filter a field (with regex) in a view
I have a view with a field **Title** that needs to be filtered before being sent:

* Users fill a tracking number and press Enter
* This number is actually related to a node id
* If a user enter "123 123" or "#123123" it will not work because of the space and/or the # symbol

My first guess as a non-expert in Drupal (and coming from other CMS and PHP Framework) would be to add a filter to this input with a regex on it to get rid of all characters that are not 1-9. However, I tried to accomplish such a thing in creating a **Filter Critera** but it does not seem to be the solution.

Do you have any recommendation to do such a thing?

Thanks

# Answer
"Filters" have certain meaning in Views. They are this little things that give "go" or "no-go" to result rows. What you seems to want is to **rewrite** user's input, not **filter**.

hook\_form\_alter I see in your tags is actually a good call. You can use it to append AJAX to onblur and make it rewrite field. Or you can use validation function

```
function yourmodule_form_validate($form, &$form_state) {
  $form_state['input']['yourfield'] = _mymodule_sanitize( $form_state['input']['yourfield'] );
}

```

to rewrite it after user's submit, but before it is used by views. This function takes &$form\_state by reference. It means you are allowed not only to read it, but also write to it, and your changes will be visible for all submit functions attached to your form, and will be used in next rendering of your form in case of validation errors or multis-tep forms.
> 2 votes

---
Tags: forms, views
---


title: Rate module and rule integration

text:
# Question
Title: Rate module and rule integration
I don't fully understand how the rate module integrates with rules.

Here's my situation:

1) I created a widget of the type: **Number up / down widget** which allow users to vote in nodes of the **Answer** content type.

2) I created a rule which is fired in the event: **User votes on a Node** with the condition **"Check the value of the vote" is "1"**

3) A user "vote up" an **Answer** and the rule is fired.

So far so good...

**The problem:**

4) The same user "vote up" the same Answer and the vote is not added because the user only can give just one "vote up" per node, this is how the rate module works **and it is all right**. The problem is that the rule is fired even when the vote is not added, this is wrong, the rule should be fired only if the node get the vote.

Is this a bug? Do I have to add other condition to the rule?

# Answer
> 0 votes
It is not a bug. User voted up. His vote wasn't counted, but he voted all right. It might be used to update "last voted date" for example, or to give "forgetful" badge to an user who tries to vote many times on the same node. You either need to:

1. Look for an event that fires when vote is actually saved
2. Look for a condition that will let you filter out only new votes
3. Add `if` in the code that actually gets fired
4. If first two are not possible and third is to difficult, fill a feature request to add 1. or 2.

I'm deliberately not going to test these and find which one works, in hope future readers can benefit from algorithm for similar problems.

---
Tags: rules, rating
---


# Question
Title: get to previous page with destination d6
For example i have a button which has onclick event (redirecting to a user login page). When a user clicks on that button browser redirects him to page user/login, but when he's successfully logined in - how to redirect it back to the previous page? Tried module login\_destination, but didn't worked for me..

# Answer
In your onclick event, add a destination=previous\_path along with your redirection url.

ie: `yoursitename.com/user?destination=previous_path`
> 1 votes

# Answer
Server side example, using drupal\_get\_destination:

```
// Login link that redirects back to current path
$login = l(t('Login'), 'user/login', array('query' => drupal_get_destination()) ;
// debug
drupal_set_message($login);

```

and as an onclick attribute, example using an image:

```
$url = url('user/login', array('query' => drupal_get_destination());
$image_path = path_to_theme().'/images/login.png'; // or drupal_get_path
$login = theme('image', $img_path, t('Login'), t('Login'), array('onclick' => 'javascript:location.href='.$url)); // or jquery.onclick it
// debug
drupal_set_message($login);

```

Note, this is OTTOMH

Personally, I'd do it server side for reliability.
> 0 votes

---
Tags: 6
---


# Question
Title: Limit user (not role) publication of content to specific menu subtree
We have several roles. Each user is allocated to one role only.

Each user has a separate menu area - e.g.

```
user 1 - Profile
       - Product
       - Press Releases - release 1
                        - release 2

user 2 - Profile
       - Product
       - Press Releases - release 1
                        - release 2

```

**What this question is NOT about:**

It is not about restricting access to post by role (that is too blunt an instrument)

It is not about restricting access to view by role or individual user.

**What this question IS about:**

As the number of members increases, the "pick list" of menu items will become unmanageable. It also, of course, means that it is possible, for whatever reason, for users to post to someone else's area. We therefore need to lock each user's posting access to his own user account (in menu terms \[user1\] or \[user2\] and its subtree). Each user should not see, in the select box, menus that he cannot post to.

We need to allocate users to specific menu subtrees, presumably through either restrictions or permissions.

**What does not work:**

module: Menu subtree (applies to roles only)

module: Menu access (it crashed the site resulting in forced database maintenance)

module: User Permissions (it applies the standard permissions module for individual users, it does not add additional permissions.)

Node/content type: inserting a field - we can't see any way of importing the specific menu subtree that we want and, even if we could, we can't see a way of making the correct menu subtree appear for that specific user.

Any and all ideas are welcome!

# Answer
Drupal's menu module is pretty good thing, but written with simple cases in mind.

Solution without using menu system:

* Create a taxonomy tree representing the part of menu that gets repeated for each user
* On node creation, omit menu altogether, let user choose taxonomy term from a tree instead
* Use Views to render it all as one big tree, theming it so it would look like a menu

Added benefit is that you can easily move elements from user to user, allow users to change their names etc and it just works, no need to edit same thing in 2 places. And you can rename "menu element" once, in taxonomy, instead of "once per user".
> 0 votes

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


title: Drupal and Session Limit

text:
# Question
Title: Drupal and Session Limit
I am using Drupal 6 with the Open Atrium distribution. **Is there a problem if the same user connects from more than 100 different computers at the same time?** At the moment I am unable to do a test but I would like to know if I can encounter any problem. So far I did try with 10 PCs and no problem whatsoever. Also is there a limit that I have to remove or by default there is no limit? Thank you.

# Answer
There is no hardcoded limit, but sessions by default are kept in database, so user\<-\>session queries will get slow like a hell pretty soon. Move sessions to memcache or apc if possible, and consider giving each of those 100 guys his own account.
> 0 votes

---
Tags: sessions, distributions
---


title: Product feeds import

text:
# Question
Title: Product feeds import
I have a CSV of data which I am importing as Commerce-Products.

**The issue is the price data gets rounded up or down when loading the price field data from the CSV into the price field of commerce-product entities.**

For example, one CSV field has a price value of £71.89. I configure the price under **manage display** with the provided options and I get the following results:

* Raw Amount: £72
* Formatted Amount: £0.72
* Formatted Amount with components: £0.72

So, I need help in importing the price data exactly as it is in the CSV, please.

# Answer
> 0 votes
Try Convert Excel Data Types in the corresponding column.

Excel 2010

1. Click the File tab, Click Excel Options, Click Advanced.
2. In the Editing Options, verify that the AllowEditing directly in cells check box is selected. Click OK.
3. Double-click the cell you want to format, and then press ENTER.
4. Click the error button next to the cell, and then click Convert to Number on the shortcut menu

How to convert text to numbers in Excel

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


# Question
Title: Adding and reading a static HTML page with
The requirement is that the user can upload a folder, containing static HTML, CSS, JavaScript files, and a link is generated.

So, then I don't want to have any drupal styling whatsoever.

### My initial idea

* Set a specific content type, allow multiple file upload
* Upload all the files to a specific directory via some kind of rules
* Access the page at www.example.com/sites/default/files/MYFOLDER/index.html

Do you think this is feasible approach?

# Answer
> 1 votes
File (Field) Paths allows you to specify path using node fields. Using it, you can have node's files in directories like `sites/default/files/custom_pages/[nid]/[node_title]/` Just make sure to put `.htaccess` inside `custom_pages` folder, one that will allow direct html serving.

Then you can generate link using the very same tokens.

---
Tags: files
---


# Question
Title: Making custom fields available to views module
I have gone through tons of reading... I even went into drupal archivess looking for help :(

I have defined my own content types and fields as well as my own db tables. I want to be able to display these fields using views module in drupal 6.

This is the coding I have done so far:

```
function svm_mail_views_tables() {
  //Define the groups table
  $table['svm_mail_groups'] = array(
      'name' => 'svm_mail_groups',
      'join' => array(
          'left' => array(
              'table' => 'node',
              'field' => 'nid',
              ),
          'right' => array(
              'field' => 'nid',
              ),
          ),
      'fields' => array(
          'group_id' => array(
              'name' => t('SVM: Group ID'),
              'help' => t('The group id'),
              'sortable' => TRUE,
              ),
          ),
      'sorts' => array(
          'group_id' => array(
              'name' => t('Group ID'),
              'help' => t('The Group ID')
              ),
          ),
      );
  return $table;
}

```

I still don't have this available in my views module when building a view.

Can anyone help me out here and tell where I'm going wrong?

Thanks in advance.

# Answer
> 2 votes
If you want to add custom database tables in a view, you need to let views know about it by invoking hook\_views\_data() http://blog.menhir.be/2008/10/22/expose-database-fields-to-views-in-a-custom-drupal-module/

There is also documentation for this within the views module.

It looks like you are on the right track but your function name is \_tables() instead of \_data().

# Answer
> 0 votes
As acouch pointed out, you need to implement `hook_views_data()`. The Drupal API documentation has a good example, as well as the Drupal 6 views online help.

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


# Question
Title: Drupal sites extremely slow due to cache SELECT-queries
I have multiple drupal 7 sites running on my shared hosting. Suddenly almost all of my drupal sites began running very slow. After some searching I found that I had 132k slow queries of the 140M queries executes.

So I turned on de debug query option in the Devel module and got this:

```
Executed 230 queries in 18868.24 ms. Queries exceeding 5 ms are highlighted.
Page execution time was 21632.34 ms.
Memory used at: devel_boot()=2.61 MB, devel_shutdown()=47.54 MB, PHP peak=48 MB.

```

After looking at the SELECT-query list I noticed that there are a lot of cache-queries that run slowly:

```
SELECT cid, data, created, expire, serialized FROM cache_views WHERE cid IN (:cids_0)

```

Not only for 'cache\_views' but also other cache-tables:

* cache
* cache\_field
* cache\_filter
* cache\_menu
* cache\_bootstrap
* ...

In PHPMYADMIN I also notice that a lot of queries have been removed from the cache:

```
Qcache_lowmem_prunes: 35.2M (of 143M queries)

```

I already checked if there were modules enabled in the DB but deleted on the drupal site.

I hope this is enough info to get some help.

# Answer
The problem above went away after deleting MySQL DB's that I don't use anymore.
> 0 votes

# Answer
Sounds like MySQL needs to be tuned. I would start with the InnoDB Buffer Pool Size. This answer has info on innodb\_buffer\_pool\_size: Do Drupal websites have bad performance or are heavy?

If the innodb buffer pool is a reasonable size and If MySQL is in ball park of doing 3k+ queries per second and your running MySQL version 5.1 or lower you might be affected by the query cache bug. At work I ended up disabling the MySQL query cache after reading this bug and verifying that the version of MySQL we are running (5.1) does not have this fix http://bugs.mysql.com/bug.php?id=43758 (available in 5.5). The bug is that a lot of queries get stuck in the “freeing items” state http://dev.mysql.com/doc/refman/5.1/en/general-thread-states.html#id770305 (The thread has executed a command. Some freeing of items done during this state involves the query cache. This state is usually followed by cleaning up). I issued this command `SET GLOBAL query_cache_size = 0;` and saw an instant improvement in query times.
> 1 votes

---
Tags: caching, performance, database
---


# Question
Title: Adding the video field to a content type
We've been using an SWF player for a while. I added the Video module without adding a new content type, just to see if the HTML5 tag worked. It does. However, that obviously doesn't give us an SWF fallback.

I then tried to add a Video content type as per this video tutorial, but when I did it, I didn't see the Video field type or an option for 'video-widget'. Is that a feature present only in Drupal 7, or did I miss something in configuring the Video module?

How do I enable the Video widget so I can have HTML5 **and** the SWF fallback? Is there an alternative set of HTML to get this done?

# Answer
I was facing the same issue, then I realized that we were doing it the wrong way.

You have to select "file" drop down "Select a Field Type", then "Video" becomes available in the next drop down labelled "Form element to edit the data".
> 0 votes

---
Tags: 6, entities, files
---


# Question
Title: How do I chose recipient email address depending on textfield value?
I have created a webform which has a "Reference number" textfield.

When someone types *101* in that textedfield, the submitted form should be send to example@gmail.com; if someone types *777*, the submitted form should be send to example222@gmail.com.

Is there a way to achieve this?

# Answer
The first solution that comes to my mind will be using hook\_form\_alter. and take the value of the field. Based on the value, send the mail to appropriate address.

But most likely there will be a module for that. Meanwhile..

http://agileadam.com/webform-mail-alter can be of service

Regards

Oleg
> 3 votes

---
Tags: webforms, emails
---


# Question
Title: Webform submission edit - redirect after edit
I have a webform where I expect users to edit their submissions from time to time. I want to redirect users upon submission of the submission edit to another node - say node/2 - (back to another node which lists their previous submissions in a view). How can I acheive this redirect?

Note - this is not about redirecting after the initial submission of the webform. It is about redirecting after editing an already existing submission.

# Answer
> 0 votes
try using rules module, it has a full featured of triggering actions with conditions like content type, user roles, ... etc.

Take a look at the documentation if needed.

---
Tags: webforms, redirection
---


title: One user with multiple profiles

text:
# Question
Title: One user with multiple profiles
I'm setting up a webshop were clients can have multiple profiles. For example a customer and supplier profile.

Whenever the user logges in, he gets a choice which profile he wants to sign in. Depending on which profile the user has selected, he gets to see different views.
Above this, the user should be able to change from profile within the site... Much like the Masquerade-module, but in this case, it should be for all users.

I hope I make myself clear on this one...
Some advise on how to tackle this issue would be most welcome!

# Answer
Discussion about one user - multiple personas started and ended at drupal.org in 2007. I think your best bet is to use masquerade as a code example and implement it yourself.
> 2 votes

# Answer
You can achieve this with help of user roles

and profile module

> The module is aimed to provide a simple, but extensible solution providing a similar end user interface like the core profile module by default. Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those.

there is also a useful module which you can use

Profile2 Registration Path

> This module enables administrators to set unique registration paths per Profile2 profile type
> 0 votes

---
Tags: 7, commerce, users
---


# Question
Title: Block Node Access After A Certain Amount of Views
I've come across a client requirement in Drupal that is very new to me.

The website is subscriber based, so users pay to subscribe at which point they are granted a subscriber role. They then have access to particular content types that they did not previously have access to. This is all easy enough.

The challenge though is that they require each node to only be accessible 5 times by each user.

The website is running Drupal 7 and presently has both Content Access and NodeAccess modules installed along with Rules and Flag.

So far I've worked out how to block access to an entire content type using Rules and roles. I've also been experimenting with Rules and Flags to block a node. For example:

If a node is flagged 5 times by the same user, it should be blocked.

But it still seems to come back to requiring a role that is not able to access it. It's impractical to have a role for every piece of content that cannot be accessed though. Content Access and NodeAccess also revolve around roles.

It seems like every possibility I come across requires a role in order to prevent access, which just doesn't work for this situation as every user is going to potentially have a number of different nodes they cannot access and they are all going to be different. This severely limits the ability of roles to work as far as I can see.

Does anyone have any ideas that might be able to point me in the right direction to achieve this?

Thanks in advance for your help!

# Answer
> 3 votes
You can control it using hook\_node\_access($node, $operation, $account) for Drupal 7. For Drupal 6 one can use hook\_nodeapi() for similar result.

When $operation is view, first update usage index for that $account *(you need a database table with nid and uid as keys, and number of uses field)* and then test if he still can see it, or no. Return appropriate NODE\_ACCESS\_\* constant. Done.

Of course you will need to write your own module, but I guess it'll take less time to wrap simple function in a module than to hack 3 or 4 modules to work together in a way they was never designed to.

---
Tags: rules, flags, users
---


# Question
Title: Search taxonomy terms with node_search_execute()
I tried to use node\_search\_execute() to search nodes. So far, running the function is easy. I noticed that there was a `$conditions` parameter from the documentation of hook\_search\_execute().

Is there a way to extend the search function to also search for taxonomy terms? Simple friendly pointers to guide me to do fast and complete node search are also welcomed.

# Answer
> 1 votes
Actually, the only missing part is the form field that should allow the users to select the taxonomy terms used from the nodes they are looking for. The code used from Drupal 7 (and Drupal 8) is still looking for the corresponding values in `$form_state['values']`.

If you look at the code used by node\_search\_validate(), the form validation handler added by node\_form\_search\_form\_alter(), you will notice the following lines.

```
  if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
    $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
  }

```

If you then look at the code used by node\_search\_execute(), you will notice the following lines.

```
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }

```

Effectively, the functionality of searching those nodes that use specific taxonomy terms has not been removed; it has been hidden to the users who don't have anymore a way to tell the Node module to which taxonomy terms they are interested. This seems rather unintentional; probably the feature was supposed to be completely removed, but the submitted patch removed just the code for the user interface. I cannot find the related issue opened on Drupal.org, and I cannot say if my supposition is correct.

Until the code in `node_search_execute()` and `node_search_validate()` is not changed, all you need to do is adding the form fields in the search form, keeping in mind that the Node module is looking for `$form_state['values']['term']`. (In other words, the form field added for selecting the taxonomy terms should be in `$form['term']`.)

If, and when, that code is removed, adding that form field would not have anymore any effect.
Drupal doesn't allow a module to alter how a module integrates with the Search module. As a matter of fact, Drupal uses hook\_search\_info(), but no `hook_search_info_alter()`; if you would want to extend how searching a node is done (for example, by adding more options), you would need to alter the page callback assigned to search/node and search/node/%menu\_trail. See search\_menu().

>

>

---
Tags: taxonomy-terms, search
---


title: Customise taxonomy select options

text:
# Question
Title: Customise taxonomy select options
I have a vocabulary with a user reference field. In a content type I have a field that references one or more terms from this vocabulary with a select widget. I would like to restrict the options to only the terms that are referencing the logged in user.

Drupal 7, Entityreference module is used for the user reference in the term and the select widget that I want to customize in the node is a Term reference.

# Answer
EDIT: If you use Features and the field under that references the taxonomy term under question is in one of your features, there's is much easier way to do this. Add this to your my\_module.field\_base.inc:

```

// Exported field_base: 'field_user_blogs_ref'
$field_bases['field_user_blogs_ref'] = array(
    ...
    'settings' => array(
      ...
      'options_list_callback' => 'my_callback',
    ),

```

Neat. This has the additional benefit that it applies only to this field base as there might be more fields referencing this vocabulary. The same could probably be done with the code below as well but extra effort.

ORIGINAL ANSWER: still leaving this as this method might be useful for some cases.

I finally did this by altering the code that provides the options to the select widget. You can see how this is done in the content\_taxonomy module

1) Provide a hook\_field\_info\_alter to set the callback function

```

function content_taxonomy_field_info_alter(&$info) {
    $info['taxonomy_term_reference']['settings']['options_list_callback'] = 'content_taxonomy_allowed_values';
}

```
`2) Provide the callback that returns the options

```
function content_taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($tree['vocabulary'] == 'user_blogs') {
        return my_callback($vocabulary);
      }
      $max_depth = (isset($tree['depth']) && !empty($tree['depth'])) ? $tree['depth'] : NULL;
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'], $max_depth)) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('- ', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

````

Notice that the function provides the options for all taxonomy vocabularies, but if the vocabulary is of a certain type then it calls another function that returns the options the way required. If you don't use the content\_taxonomy module you can copy and use the taxonomy\_allowed\_values function from the taxonomy module.
> 3 votes

# Answer
Try Entity Reference View Widget module

> This module provides an advanced Entity Reference widget that uses a view for selecting items. The view can be paginated and have exposed filters. It degrades, so it can be used even if Javascript is disabled.

Video Tutorial
> 1 votes

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


# Question
Title: Hiding the previous instance in a Multi value field collection embedded widget
I have a multi valued nested field collection with many field in it like checkboxes ,image etc.

Now when adding/editing a node looks clumsy when multiple values added for that field collection.

So I decided to hide the previous instance when add another is clicked , which i achieved by hacking and preprocessing the theme\_field\_multiple\_value\_form in the core field.form.inc by not passing the item to drupal\_render(), but now what I get is empty draggable row that is not good.

So i managed that by just render a markup there which is not an issue now.

now the values entered to the field collection is not saved if it is hidden.

so what I'm technically asking is how to hide a field but still process it on saving the node.

OR may be is there any alternate ui for multi value nested field collection?

Note : I have tried hide(), #access & skipping from drupal\_render.

# Answer
I think the solution is within the theme layer. By extending the admin theme (i.e. creating a sub-theme) you could create the desired behaviour using CSS and JS.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: function theme_field__content_type() isn't working
I'm trying to modify all fields output for a specific content-type called Netrunner-Card.

After digging through Stack Exchange I ran across someone that suggested using:

```
function theme_field__content_type()

```

But it isn't working. My implementation is:

```
function blinks_responsive_field__netrunner_card($variables)
{
    $output = 'TEST';
    return $output;
}

```

Which if I understand correctly, this should remove all field data for a content type of 'Netrunner Card' but it doesn't.

I have multiple fields for each card. There are also card types which I want to output differently, (i.e. An Operation card should look like this, an Identity card should look like this, etc.). So I want to use a switch function (PHP) to check the card types and adjust fields as needed. First I have to get access to the fields and I'm trying to do this inside of ONE function versus a separate function for each field which would add a lot of duplication.

My theme is called blinks\_responsive. My content type is netrunner\_card. I am out of ideas.

**UPDATE:** I don't know if it matters but I discovered that I had a field.tpl.php file in my theme templates folder. Wondering if that caused me issues. Still not working tho.

# Answer
> 1 votes
The problem lies in having other functions that alter OTHER fields of the SAME content type.

Earlier in my development, I created two functions, one each, for two specific fields. Even though my adjustments for those fields were minor (added classes to one and added an img tag to another) it still caused the generic function to fail.

Because I had those other functions...

```
theme_field__field_name__content_type

```

It made the generic function for all fields...

```
theme_field__content_type

```

...not work.

Once I removed those other functions? Suddenly theme\_field\__content\_type started working instantly.

# Answer
> 0 votes
You can theme fields with both a template, and in a function. In 99.9% of cases, when a theming function 'does not work', it's because it has a wrong name. So is in your case. Your function has a theme name + the content type name. It lacks the actual field name. To pair up hierarchy of field (content type \> field name), you should use templates.

Take an existing field.tpl.php, rename it as per templating suggestions (http://drupal.org/node/1089656), and edit as required.

You can alternatively preprocess a field (http://api.drupal.org/api/drupal/modules!field!field.module/function/template\_preprocess\_field/7), depending on what you want to do.

---
Tags: theming
---


title: Render an item trough displaysuite?

text:
# Question
Title: Render an item trough displaysuite?
Admitted, I don't truly understand Displaysuite.

What I need, is, something of the following:

```
foreach (get_certain_nodes(), $nid) {
  $node = node_load($nid);
  $rendered_node = call_displaysuite_to_render_the_node($node, 'build_mode_foo');
  $output .= $rendered_node;
}

```

The missing link is how to render the node, using a predefined build mode. Or am I doing it wrong?

# Answer
> 1 votes
Rendering a Display Suite build mode is quite easy. If you know how. ;-)

```
foreach (get_certain_nodes(), $nid) {
  $node = node_load($nid);
  $node->build_mode = 'my_build_mode'; // Enter the name of your build mode here
  $rendered_node = node_view($node);
  $output .= $rendered_node;
}

```

By adding a 'build\_mode' variable to the node object Display Suite will recognize it as something it has to render in `node_view()`.

# Answer
> 1 votes
This is not a complete answer, but maybe it helps to have a look at the nd\_views\_node\_helper function. If I understand correctly, it's the helper function that allows Views rows to be rendered through Display Suite.

You can also make your custom code dependent on views: create a view which takes node IDs as argument and renders the nodes through Display Suite.

Hope that helps!

# Answer
> 1 votes
As per the API page for D7 node\_view() the second argument is the view\_mode which could be a display suite view mode if you like.

```
foreach (get_certain_nodes(), $nid) {
  $node = node_load($nid);
  $rendered_node = node_view($node, 'build_mode_foo');
  $output .= drupal_render($rendered_node);
}

```

# Answer
> 0 votes
You can activate the display "Full node" for a given content type. Go to /admin/structure/ds/layout and choose the Content Type you need to edit. In the section "Custom display settings" activate the view mode "Full content" and hit save. Now you can edit the "Full content" display to whatever you want to do with it ...

---
Tags: 6, theming, display-suite
---


# Question
Title: Using Fieldgroups with Entity Registration Module
I'm using the Entity Registration module to create event signup forms. I've got my first event registration form up and running and now want to group some of the fields into fieldsets.

I have the Field Group module installed, and have used it to group my fields into fieldsets (via Manage Display):

The effect I want to achieve is something like this:

However the fieldsets are not showing on the registration form or in the markup:

According to Field Group module, it should work with any entity:

> Fieldgroup will, as the name implies, group fields together. **All fieldable entities will have the possibility to add groups to wrap their fields together**.

I've searched the Entity Registration issue queue, but can't find anything relating to this. Has anyone managed to get fieldsets working with Entity Registration?

# Answer
Turned out I was missing a step, I didn't realise that you had to create your field groups in Manage Display AND Manage Fields. Seems a bit strange having to re-create the same field groups twice, but doing that fixed the problem.
> 0 votes

# Answer
You need to add corresponding group to add steps in it. See image.
> 2 votes

---
Tags: 7, entities
---


title: How to remove and add joins to a view?

text:
# Question
Title: How to remove and add joins to a view?
Because of some buggy handlers I need to write a hook that will:

* Get location\_instance table's alias from the original query
* Remove location\_instance table join
* Remove that alias join
* Remove a location table join
* Add 2 new joins

Apparently views does things a little differently so I can't just `$query->join()` my way to freedom. How exactly do I accomplish the above?

# Answer
> 0 votes
This is an issue I have been sturggling with myself. You may want to start by looking at hook\_views\_query\_alter() and read this related Drupal Answers question.

Then you can use these functions: views\_plugin\_query\_default to actually affect change on your query.

---
Tags: database, views
---


title: Bypass field validation

text:
# Question
Title: Bypass field validation
I have a content type form with some fields attached. I'm looking for an easy way of skipping core validation for one of those fields. I guess what I'm looking for is something like this:

```
$form['foo']['#check_valid'] = FALSE;

```

This could possibly be achieved using `#limit_validation_errors`, but this would require some work. Can this be achieved without too much of a hassle?

# Answer
> 1 votes
It should be possible to remove core validation from the field by adding the #form\_validate array element to the form element you want to edit, then pass a custom validation callback that passes the field by default. That should work.

---
Tags: 7, entities
---


# Question
Title: Display images instead of nodes titles in Drupal 7
Normaly in Drupal 7 we have (node.tpl.php):

```
  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

```

It is taking node\_url and putting it on a Title in every Node.

I do have 5 nodes (pages) displayed:

* First
* Second
* Third etc

I have created images First.gif, Second.gif and I want to load that images instead of Title.

I did check various implementation, but didn't find any resolution for me.

\[Update\] I did try to edit template.php file and to add functions for replacing title with image-if images exists. I need this in Drupal 7 - please see here - http://drupal.org/node/221854

Is there any help? Thanks

# Answer
Judging from your comment you actually want to change the title that gets output in page.tpl.php (and possibly other page templates). One way to achieve that is adding the following code into your template.php file:

```
function mytheme_process_page(&$variables) {
  if (isset($variables['node'])) {
    if ($variables['node']->nid == 1) $image = 'First.gif';
    elseif ($variables['node']->nid == 2) $image = 'Second.gif';
    elseif ($variables['node']->nid == 3) $image = 'Third.gif';
    elseif ($variables['node']->nid == 4) $image = 'Fourth.gif';
    elseif ($variables['node']->nid == 5) $image = 'Fifth.gif';
    if (isset($image)) {
      $url = url(path_to_theme() .'/images/'. $image);
      $variables['title'] = '<img src="'.$url.'" alt="'.$variables['title'].'" />';
    }
  }
}

```

You should switch out 'mytheme' with your actual theme name and change nid values, the path to images (if needed) to get yourself a working solution.
> 0 votes

# Answer
For non-coders: the views slideshow module (or something similar) could easily solve this problem without requiring custom code to maintain.

From http://drupal.org/project/views\_slideshow:

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
>
> Potential uses News item slideshow (such as the title, image and teaser of the last 5 news articles submitted) The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.). Rotate any image, based on any filters you can apply in views. Hottest new products for any ecommerce drupal site. Rotate contact links, share links, etc. Heck, you could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power. Its also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow. The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.
> 2 votes

# Answer
I believe that a simpler answer would be to manage your node fields better. If you created a new image field for each node, and only insert images for those nodes that need them then you could modify your template.php like in the example above and only replace the output for each one as needed, versus what amounts to a Drupal hack instead. When your output is generating data separate from the data I feel like this makes the whole thing harder to update. I mean, what if you upgrade your theme? You could lose all of those edits.

Just a thought.
> 1 votes

---
Tags: nodes, media
---


title: Problems with active-trails

text:
# Question
Title: Problems with active-trails
I have played with Menu Trail by Path and Menu Position, but none worked well with a Views-generated listing acting as a navigation menu.

Imagine the following scenario:

1. On the left side there is Views generated block of linked taxonomy terms.
2. When clicked, the link fills the main content area with a listing of nodes tagged with the given taxonomy term. The activated term link gets `active-trail` class - so far so good.
3. When you click a node link though, the node opens, but now - the `active-trail` is gone.

The complicating factor might be that my taxonomy is localized (each term has a translation within same vocabulary). But I believe there is a solution to that... Anyone?

# Answer
It's important to understand that taxonomy is not a menu system, the menu system is. There are ways to make the menu system mirror taxonomy, but they are separate systems. Taxonomy\_menu might be able to help.
> 1 votes

---
Tags: taxonomy-terms, blocks, routes
---


title: Linking image field to an external URL

text:
# Question
Title: Linking image field to an external URL
I have a list of images on my node that I want to output wrapped in an anchor tag for linking to external webpages. Images are coming from fields in my content type. I'm not using the Views or the Panels module, and I've edited my page.tpl.php and node.tpl.php files for a rather intricate "About Us" page.

So how do I do this? I'm using Drupal 7.

# Answer
> 1 votes
This is an updated answer to this question, not just for the original post as it was posted a year ago.

To perform this feature in Drupal 7, the module Image Link Formatter fits perfectly:

> This module is the result of the discussions around a requested feature to allow an image field to be displayed with a link to a custom URL

# Answer
> 1 votes
You can create a custom field formatter (theme function for fields) where you can define how the image field should be rendered. Here you can add the a tag or any other special markup.

There are a lot of guides on how to do this, both here on the site and on the web, so I won't go into details about how to create a field formatter here, but it's nothing more than a few hooks and a theme function.

# Answer
> 1 votes
If you want to have the option to add a url to each image, there's a module Link Image Field for that. The port to Drupal 7 is not yet finished however (but it looks like there's working code).

---
Tags: media, navigation
---


title: Formatting with Views

text:
# Question
Title: Formatting with Views
So I'm using the Views module to list inventory items that include:

* Name
* Photo
* Description
* Sales document

I noticed that each item in the view is formatted differently because of size of text, image, etc.

Can I force a specific width/height with CSS, or is there an option within views? Here is an example of the situation.

# Answer
If you're looking for uniformity across the view, I'd go with a teaser view mode on the nodes. It's under display settings. In view mode, you can control the length of the text that is trimmed, the size of the image,or whether or not you want field labels, or taxonomy terms showing, etc. In fact you can show a completely different set of fields that weren't visible on the default view mode. The upshot of this is the content will display exactly the same across the entire site without having to re-theme it in a block, in a different view, & so on.
> 0 votes

# Answer
My recommendation would be as follows:

In your view, do not use any content view mode (teaser or whatever) but fields instead. This provides more flexibility during theming.

In order to nicely and consistently format the image, you'd want to create a fixed-dimensions image style. For this purpose the best option is to use "scale and crop" effect, or use the Manual Crop module to individually crop each image.

Then, in the field formatting dialog, select this style from the dropdown list.

As for styling the fields, you could either provide classes and wrappers in Views UI, or use templatung/theming in the tpl file. To properly scope the and name the file, click on the Theming Information link in the Advanced column of the view editor.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Core blog module only shows two blog entries?
I've enabled the core blog module, but it only shows two entries on exampe.com/blog

If I "unpublish" one of them, it brings up the next published blog post, which shows me that it does recognize that there are additional blog posts.

There are about 137 in the database. How do I show them all with pagination? The core blog module doesn't seem to have any config settings.

EDIT: The site was recently migrated from D6 to D7, is there anything that may have caused this issue given this fact?

# Answer
> 0 votes
Can you reproduce this behavior using your module set, but with fresh install and blog posts entered manually / generated with devel generate? If not, it's migration failure and your best bet is to export content from old site (you have backup, don't you) and import it to the new one, without Drupal's built in migration tool.

If this happen with fresh setup too, try changing theme to one of the supplied core themes. If it works, then, it means you have a bug in your templates. If it's not, I need to get more info to further expand my answer.

---
Tags: 7, nodes, upgrading
---


# Question
Title: Display a block on some pages according to the fields content of that page
I created a content type called people, where I create personal pages using that type. One of the fields is 'area'.

Then, I created a view of block called 'software people', where I list all the people who work in software area. I want to show this block only on the pages where the person's area is Software. How can I achieve this?

Thanks

# Answer
> 1 votes
This goal can be achieved in views as well, but only with some PHP contextual filter code:

Just add contextual filter: **Content: area (field\_area)**

Under: "When the filter value is NOT available" select:

**Provide default value-\> PHP Code**

Enter PHP code:

```
$node = menu_get_object();
return isset($node->field_area['und'][0]['value']) ?
  ($node->field_area['und'][0]['value']) :'';

```

Under: "When the filter value IS available or a default is provided" select:

**Specify validation criteria-\>PHP Code**

```
$area = $handler->argument;   // content of field area
return ($area == 'Software'); // validation of the area content

```

**action to take if filter value does not validate -\> hide view**

**That's it!** Your block will show up only on the pages where the person's area is 'Software'

# Answer
> 1 votes
Simplest way is to conditionally output region in node.tpl.php But there is no $page in node.tpl.php. So you need to make it happen. In your template.php add function

```
mytheme_preprocess_node(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

```

Then in node.tpl.php use:

```
print render($region['region_name']);

```

to output your region. Of course wrap it in if, case or any other logic you fancy.

---
Tags: blocks, nodes, theming
---


title: user tabs customization

text:
# Question
Title: user tabs customization
I have a site built with Drupal 7, and I allowed the authenticated users to see the other profiles. Till now, every thing was OK; the problem is when they click on the name of a user. They see the tab **"account"** by default, and I wanted them to get the tab "video" or blog entries instead.

I have the view, edit, video, account tabs, and I used the tab tamer in order to reorganize the theme, but the "Account" tab is still the default one.

How can I make the "Video" tab the default one? Where can I change it?

Please check my site.

# Answer
> 0 votes
I am unaware of any module that does this for you. So, you'll need to use a little bit of code to tweak things. What you need to do is implement hook\_menu\_alter() in a module to alter the way the tabs are organised. In particular, you will need to swap the menu *type* of the default tab and your video tab. The types in question are MENU\_LOCAL\_TASK and MENU\_DEFAULT\_LOCAL\_TASK; i.e., change the default tab to MENU\_LOCAL\_TASK and your video tab to MENU\_DEFAULT\_LOCAL\_TASK which should set the latter as the default. More information on these constants are provided on the hook\_menu() page.

# Answer
> 0 votes
you can use the tab tamer module to rename the tabs and also specify which tabs to show and which not to..it is also fairly simple to use ... hope it solves your problem.

---
Tags: blocks
---


# Question
Title: How to add filter on node list in a custom module?
I am developing a module. In that module I have a page to list all the nodes of a specific type to user.

I need to:

1- show the nodes each on a row with ' Edit | Delete ' link in each row.

2- I also need to show a dropdown to give the user ability to filter the nodes by one of the node field.

I've created the first one but I don't know how to add a custom filter to the output.

Would you help me ?

I am working on Drupal 6.

Thank you.

# Answer
If you are using Views 3 and within CCK you have listed allowed values for the field in question, you can set it up like this.

1. Select the field in question with the allowed values option, eg, in Filters, select `'Content: Field Name (field_name) - ALLOWED VALUES'`
2. Click on EXPOSE.
3. Click in the values and select them all.
4. Click `Limit list to selected items`.
5. Save it.

You should now have an exposed filter with a drop down that limits the view to that field.
> 1 votes

# Answer
You can use views for listing nodes of specific types. Also, in views, you can use Contextual filters for other options. Please explore more options of views and you will find every option there. Thanks.
> -1 votes

---
Tags: 6, views
---


title: Set a view filter programmatically

text:
# Question
Title: Set a view filter programmatically
I have a view that includes a date field that only uses the year part. I want provide a default filter value for this field based on the current date. So far, I have this

```
function results_view_views_pre_view(&$view, &$display_id, &$args) {
  if($view->name == 'results_view') {
    $year = date("Y");
    $view->display['default']->handler->options['title'] = $year . ' Results';
    $view->display['page']->handler->options['filters']['field_season_value']['value']['value'] =  = $year;
  }
}

```

This doesn't throw any errors but the filter view isn't filtered

I'm not sure what I'm doing wrong here, or if I'm even going down the right path. The value I assigned above is based on the fact that when I hard code the year into my view, the view object looks like this

```
[field_season_value] => Array
(
        [id] => field_season_value
        [table] => field_data_field_season
        [field] => field_season_value
        [relationship] => none
        [group_type] => group
        [ui_name] =>
        [operator] => =
        [value] => Array
                (
                        [min] =>
                        [max] =>
                        [value] => 2013
                        [type] => date
                )

```

Just to clarify, the date field is based on a fiscal year that runs September through August. So if its May 2013, the date would need to be 2012. My example above is just a simplified version if what I'm going to need to do in the final version.

# Answer
> 2 votes
If you don't mind having "code in the database" you should be able to do all of this with an argument/contextual filter instead by providing a default value via PHP Code, eg, set one based upon your season field and then inside the GUI do something like this drupal 6 example...

...with obviously more logic than just returning 2013 :)

# Answer
> 2 votes
Set the default value to `now` using GUI. This should give you what you need without any code.

If you need to use fiscal years, either create own custom filter, one that will translate real date to fiscal year. Read manual and more detailed manual to see how to do it. Simply changing default value in date will not be enough, as user may inject date with more than a year set, making built-in filter not work the way you want it to. And then, well, then use `now` as default value.

You probably want to inherit from class views\_handler\_filter\_date and override it's extra\_options() method

---
Tags: views
---


# Question
Title: Search for duplicate or similar node titles when creating content?
Much in the same way that it is on this site (as you type your question, it shows similar questions) is there a module that will search for similar nodes as I type the node title in Drupal?

I know of the Unique Field module, however it only checks after the node has been submitted. I need some way of doing it as they type.

# Answer
There is module Uniqueness , it does exactly what you want. It allows you to enable for any content type, and you can configure checking on node add or edit or both.

> Uniqueness module provides a way to avoid duplicate content on your site by informing a user about similar or related content during creation of a new post. A UI widget is added to the node/add form that does asynchronous searches on inputted fields (like the node title or vocabularies) and returns the titles of similar content.
> 5 votes

# Answer
I'm not sure if there's a contributed module already. However you can create it yourself.

First you need to create/register autocomplete callback menu using `hook_menu` function.

```
/**
 * Implement hook_menu().
 */
function mymodule_menu() {

  $items['mymodule-autocomplete-title'] = array(
    'page callback' => 'mymodule_autocomplete_title',
    'access arguments' => array('view published content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

Then create a function to search and retrieve similar node titles.

```
function mymodule_autocomplete_title($title) {
  $results = array();
  $query = db_select('node', 'n')
    ->condition('n.title', '%' . db_like($title) . '%', 'LIKE')
    ->fields('n', array('title'));

  $nodes = $query->execute();

  foreach ($nodes as $row) {
    $results[$row->title] = check_plain($row->title);
  }

  drupal_json_output($results);
}

```

Then alter the desired node add form using `hook_form_alter` function to change normal node title field to autocomplete node title field.

```
/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  // node add form id
  if($form_id == 'page_node_form') {
    // make title field autocomplete field
    $form['title']['#autocomplete_path'] = 'mymodule-autocomplete-title';
  }
}

```
> 4 votes

---
Tags: search
---


title: Ubercart hook_order and delete

text:
# Question
Title: Ubercart hook_order and delete
So I am wanting to execute some code when an order is deleted in Ubercart. In order to test hooks, I have the following code:

```
function loaner_uc_order ($op, &$arg1, $arg2) {

  if ($op == 'delete') {
    $sql = "INSERT INTO {testing} (text) VALUES ('you deleted order number')";
    db_query($sql);
  }

}

```

The problem is it is just not firing. Am I doing this right? I know the query works because I copy/pasted it into a separate area, and it worked fine. I am honestly stumped.

# Answer
The syntax is ubercart hook order

```
hook_uc_order($op, $order, $arg2)

```

**Clear your site cache** from performance page, The hook is fired for me after clearing the cache.
> 1 votes

---
Tags: 7, ubercart
---


title: Are breadcrumbs not working properly?

text:
# Question
Title: Are breadcrumbs not working properly?
I am using the following PHP code in the view's header to set the breadcrumbs of the view.

```
global $base_url;
$path = $base_url . "/tag/" . arg(1) . "/" . arg(2);
$title = ucfirst(str_replace("-", " ", arg(2)));
drupal_set_title($title);
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l($title, $path);
drupal_set_breadcrumb($breadcrumb);
print views_embed_view('article_tag_name', 'default', array(arg(2)));

```

In my page, the breadcrumbs contain the term ID, not the term name. How do I get the term name?

# Answer
Seems like your breadcrumb is working properly but you get the real path instead of the path alias. You can use drupal\_get\_path\_alias.
`$breadcrumb[] = l($title, drupal_get_path_alias('taxonomy/term/'. arg(2)));`
Seems like you are setting title and breadcrumb in a .tpl file? Try to avoid that and put your logic in template.php.
Quick tip: views\_embed\_view can cause performance issues.
> 0 votes

---
Tags: breadcrumbs
---


# Question
Title: Set role expiry programmatically in uc_roles_expirations table?
I am moving a site to drupal. In that site role expire was manually set by admin.

In my drupal site I want this with the use of ubercart recurring subscription.

So how can I set a role expiration date programmatically which will work as we assign a role in features of any product purchase?

# Answer
> 2 votes
Solved Just by Database entry :

```
$expiredate = date('U', strtotime($expiry));
    db_insert('uc_roles_expirations')
    ->fields(array(
      'uid' => $uid,
      'rid' => 6,
      'expiration' => $expiredate,
    ))
    ->execute();

```

# Answer
> 0 votes
The way to do this with Rules is as follows. I've not done this with Ubercart per se but it should work.

* in Rules, create a component that will perform an action (i.e. remove a role)
    + a component of type 'action set' with a single 'node' variable
    + action: create a list of nodes (products or users?)
    + add a loop
    + add an action to this loop that will remove role
    + *** more actions may be required here depending on your setup ***
    + save the component
* now create a rule that will react 'after saving new content
* condition: you need to check for proper content type (Rules requires this)
* action: schedule component evaluation (select the component created above)
    + set date/time (the node published date; any date field will also work)
    + set offset (e.g. + 4 weeks, + 52 weeks, etc.)
    + save
* when a new (product) node is created, an action item will be added to the Schedule of items to be evaluated on cron.

Checkout Nodeone's screencast Using fields for setting evaluation time for more information.

Cheers!

---
Tags: 7
---


# Question
Title: Put footer/signature on every blog post?
I'd like to put a canned footer at the bottom of every blog post which has it's own content type. My blog posts can have comments so I'd like the footer boiler plate to be at the end of the post content but before the "Add new comment" header. I am NOT talking about a general footer for the entire site. What's the drupal way to achieve this?

# Answer
I see 3 pretty easy solutions :

1. (The easiest) You add a new field textarea to your blog content type. You configure its default value to the content you want (your blog footer content) which can be html (so you're free to type in whatever you want). Then configure the display of your blog post to have this field as the last one displayed. Done.
2. You can add a entity\_reference field (Entity reference module) to your blog content type. Then create a node which represent your footer, and use it as your default entity\_reference field value for your blog content type. (Then you'll have to configure your display modes however you want it ...)
3. You can probably do this with a hook\_form\_alter() and insert your footer directly in the form

Hope it helps
> 2 votes

# Answer
More tricky way is to add a region in a node.tpl.php used in your blog posts. To do this, in your custom theme add the following code to template.php file

```
function mytheme_preprocess_node(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

```

Then copy `node.tpl.php` to your custom theme and then place the following code between any HTML tag.

```
print render($region['region_name']);

```

That way, you can have region named blog\_footer, and put there whatever you want.

Taken from this answer.
> 2 votes

---
Tags: 7, nodes
---


title: Allow only single product in Cart

text:
# Question
Title: Allow only single product in Cart
Is there any way to allow user only one product in cart. I used uc\_restrict\_qty but After that i can add more than one products also.

# Answer
> 3 votes
If the module `uc_restrict_qty` not working file your issue there. Alternatively You can achieve this with help of hook hook\_uc\_add\_to\_cart

```
hook_uc_add_to_cart($nid, $qty, $data)

```

> Performs extra processing when an item is added to the shopping cart.

Inside hook you can check your conditions, and prevent your new item to add.

`uc_cart_get_contents()` can used to get existing contents of cart. If it is greater than 1 you can do your logic here, either remove previous one and add the current one or remove the new item

---
Tags: 7, ubercart
---


title: Edit Node Title in Template.php

text:
# Question
Title: Edit Node Title in Template.php
**UPDATE:** I know that I could accomplish this inside of a tpl.php file. But I would prefer to keep as much logic in the template.php file as possible, reserving tpl.php adjustments for markup. I have been informed that Drupal is NOT an MVC paradigm but an AOP, and I am trying to adapt to that as quickly as possible. But I feel that since I have already accomplished this IN the Template.php file that there is bound to be a 'Best Practices' way of doing this that I would like to adopt.

Currently, I have a node\_field called field\_unique\_card. This is a Boolean field. If field\_unique\_card == 1 then the title of the node needs to be something like this:

```
$title = '* ' . $title;

```

The way I am currently doing it is as follows:

**UPDATE:** I just remembered the better way of (expr1)?(expr2):(expr3); so I updated my preprocess function.

```
function theme_preprocess_node(&$variables)
{
    ...
    $variables['title'] =  $variables['field_unique_card'][0]['value'] ? '*' . $variables['title'] : '';
}

```

I am wondering if this is 'Drupal Best Practices' or if there is a smarter way? I ask because this only affects the nodes when they are displayed as a field. But on every node display there is an additional output of the Node title that happens at the top of the page. I can't figure out how to make it so that the title shows the * there as well.

Any help would be greatly appreciated.

# Answer
> 1 votes
It's a little confusing at first, but the main page title (usually the `<h1>` tag) is in page.tpl.php. If you look at the standard node.tpl.php file...

```
<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
<?php endif; ?>

```

the title variable that you're overriding in the node preprocess function, won't affect the title of the node if it's being displayed as a full page. This is completely by design so that the main page title can be consistently set in a single place (the page template file).

That makes it a slightly strangled route, and what seems like a simple task becomes a bit messy. You could implement a `hook_preprocess_page` function, check for a node in the current page, and adjust accordingly:

```
function MYTHEME_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    if (MYTHEME_node_is_unique_card($node)) {
      $vars['title'] = '*' . $vars['title'];
    }
  }
}

```

If you're using Drupal 6 you can also add

```
$vars['head_title'] = $vars['title'];

```

straight after setting the title, to alter the `<head>` title of the document (should you need to make it match). If you're using Drupal 7, that logic would move to `hook_preprocess_html()`.

Now as this is Drupal, there are other ways to do this too, with a custom module.

For Drupal 6, you can implement `hook_nodeapi()` to intercept the node view and alter the title:

```
function MYMODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($node->type == 'my_type' && some_other_condition($node)) {
    // If this ISN'T a teaser view.
    if (!$a3) {
      drupal_set_title('*' . $node->title);
    }
  }
}

```

Or the same thing for Drupal 7, using `hook_node_view()`

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_type' && $view_mode == 'full' && some_other_condition($node)) {
    drupal_set_title('*' . $node->title);
  }
}

```

There's usually more than one way to do something in Drupal so it can get pretty confusing; my best advice is to pick a process/workflow that works for you and stick with it. Your attempts to separate logic from presentation are spot on. The less logic in a template file, the better for so many reasons.

Regarding design patterns - You'll never get Drupal to respect a *true* MVC architecture in my opinion, but you can certainly apply some of the disciplines to Drupal development.

Some people have their own ideas on that though, and claim MVC in Drupal is possible. From a purists' point of view I can't agree with that thought, but there are some interesting articles out there (including that one) that might help explain how to shoehorn that thinking into a Drupal site.

# Answer
> 2 votes
The easiest (and less expensive) way I see to do this is as follows (did not try this, but should work):

1. Copy `node.tpl.php` from the core `node` module (/modules/node) to your theme's folder (/sites/all/themes/).
2. Modify the code to display the desired title. By default the code to display the title is:

```
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
</h2>

```

can be changed to:

```
<h2<?php print $title_attributes; ?>>
  <?php if($unique_card == 1) { ?>
    <a href="<?php print $node_url; ?>"><?php print "*" . $title; ?></a>
  <?php } else { ?>
    <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
  <?php } ?>
</h2>

```

Note: I used the variable `$unique_card` because the comments from `node.tpl.php` mentions:

> Field variables: for each field instance attached to the node a corresponding variable is defined; for example, $node-\>body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language; for example, $node-\>body\['en'\], thus overriding any language negotiation rule that was previously applied.

# Answer
> 0 votes
To address one of your sub-questions, namely

> I am wondering if this is 'Drupal Best Practices' or if there is a smarter way?

Drupal's common practice is to keep it in node.tpl.php

Drupal's practice is to split logic into files corresponding to parts of this logic, like node's logic to node.tpl.php, main html logic to html.tpl.php and so on. This way it's easier to find malfunctioning part and revert it from backup without reverting changes in totally unrelated parts.

Of course you can feel free to ignore it, especially if you aren't planning to share.

---
Tags: nodes, theming
---


# Question
Title: How could I select all the authenticated users and just only them?
I've a long running Drupal 7 site. Now my client needs a way to select (and act upon) the users who are not in the role "A" and "B", but just "Authenticated Users".

I know that the latter are not in the `users_roles` table which makes the standard admin/people form and the advanced users module useless (they both skip over the Authenticated Users).

Do you know of any module that could do something like that? Unfortunately it seems there is no way to alter the query in the `user.module` (which joins `users_roles`) so I feel like it's a dead end. Should I need to write a module with a form and duplicate most of the features of the admin/people?

# Answer
> 3 votes
Using the Views Bulk Operations (VBO) module it is possible, by creating a view to select all the people not in the desired roles.

---
Tags: 7, users
---


# Question
Title: Find out if a view returns any results and if it doesn't disable a link to that view
I have a panels page with two view panes on it. The first view pane lists taxonomy terms. When you click on one of the taxonomy terms the second view pane will display a list of content for that taxonomy term.

Is there any way that if there is no content for one or more of the taxonomy terms then those links can be disabled/hidden from the first view pane?

The second view pane uses the term ID from the links in the first view pane as an argument to filter the content for that term.

I'm not quite sure how to go about doing this. One way I had thought was to use jQuery and Ajax to somehow call a function in Drupal to find out if the view returned any result and then hide the link. But I haven't attempted this before in Drupal.

There is another slight complication in that the panels display are for organic groups and the second view pane only shows content for the taxonomy term clicked on and also content that is associated with that group. So that any function that finds if there are any results would need to pass in both the argument for the term ID and also the ID for the group, which the view was getting from the context.

Any help would be much appreciated, or even an outline of an approach I could take.

# Answer
> 0 votes
I managed to get the results I was looking for by using a different kind of view. I created a term view and added a relationship for "content with term", and a second relationship for "group membership" based on the first relationship. I then added in a filter for the content type, and a context filter for the group. I only added a field for the term and in the query settings made the query distinct. The view now only shows distinct terms which relate to content of a specific type and that \[the content\] belong to a specific group.

# Answer
> 1 votes
The one solution is hide empty terms. You can hide empty terms as shown here

Another solution is use php in your view or views template, use taxonomy\_select\_nodes function.

> Return nodes attached to a term across all field instances.

The tid can get from view. If the function return empty , dont provide link for that term.

Otherwise you can link term to your second view.

---
Tags: 7, panels, views
---


title: Login without password

text:
# Question
Title: Login without password
I'm in a project where the main login form must not have a password field. The user will login with a username and selecting a Country. This country field is configured within the user profile. So far, I can manage to log in users checking their username and the selected countries, but I can't find anything not to require a password for login.

This is my code.

```
function hdp_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    // Add country field to login form
    $form['pais'] = array(
      '#type' => 'select',
      '#title' => t('Pais'),
      '#options' => array(
        'Argentina' => t('Argentina'),
        'Chile' => t('Chile'),
        'Peru' => t('Peru'),
      ),
      '#required' => TRUE,
    );
    // Add validation to check country-username
    $form['#validate'][] = 'validacion';
  }
}

function validacion(&$form, &$form_state) {
  // Variables.
  $usuario_nombre = $form_state['values']['name'];
  $usuario_pais_seleccionado = $form_state['values']['pais'];

  // Search user countries by username. Username must not be duplicated.
  $uid = db_query("SELECT uid FROM {users} WHERE name IN ('$usuario_nombre')")->fetchField();
  if (!empty($uid)) {
    $paises = db_query("SELECT field_paises_value FROM {field_data_field_paises} WHERE entity_id IN ($uid)")->fetchAll();
    $paises_habilitados = NULL;
    foreach ($paises as $pais) {
    $paises_habilitados .= $pais->field_paises_value;
  }

  // Check if selected country is one of the user profile selected countries.
  $habilitado = strpos($paises_habilitados, $usuario_pais_seleccionado);
  if ($habilitado === false) {
    form_set_error('pais', 'Acceso denegado. Por favor revise su nombre de usuario y el país seleccionado.');
  }
}

```

# Answer
> 4 votes
If you don't require a password from your users, then you should:

* Make the password form field not visible to the users (it is enough to set #access to `FALSE`)
* Remove the form validation handlers that are not necessary

The form validation handlers that the user login block uses are the following:

What you need to do is removing `'user_login_authenticate_validate'` and `'user_login_final_validate'` from the array `$form['#validate']`.

Remember also that your form validation handler needs to set `$form_state['uid']`, since that is the value used from user\_login\_submit() to load the user object from the database.

As additional notes:

* Your code is making assumptions about where/how the field data are saved; in particular, it is assuming the field data are saved in the database currently used by the Drupal site, which is not necessary true, since field data could be saved in MongoDB. I would rather use the following code.

```
$uid = db_query("SELECT uid FROM {users} WHERE name = :account_name", array(':account_name' => $usuario_nombre))->fetchField();
if (!empty($uid)) {
  $account = user_load($uid);
  if ($countries = field_get_items('user', $account, 'field_paises')) {
    // I assume users can just select a single country.
    $country = array_shift($countries);
    if ($country != $usuario_pais_seleccionado) {
      // Show the error message.
    }
  }
}

```
* You cannot use user\_authenticate(), since that requires the account password, which is not saved in the database. The database contains the password hash.
* The string passed to `t()` should contain words in English, since the function is used to translate from English to the language currently set for the site. (*Pais* is not an English word; probably you meant *Country*.)
* Instead of `WHERE name IN ('$usuario_nombre')`, you should use `WHERE name = :username`. Input from users should not be used directly in SQL queries, as that is a security issue. (See SQL injection.)
* Functions implemented by a module should always have their names prefixed by the module name.

Talking of security issues, I hope you are using the authentication method you described in a very restricted, controlled environment. I would not use it in a public site where everybody can create an account, especially if the username and the country selected from users are visible to everybody. Even in the case the country is not visible, getting the right username/country combination is much easier than finding the right username/password combination that allows you to log in.

---
Tags: 7, users
---


title: Calendar add date programmatically

text:
# Question
Title: Calendar add date programmatically
I am having a bit of trouble figuring out a thing with Drupal Calendar.

I have created a custom content type , with a `date` field. I display the dates as events in a Calendar style view.

I want to add custom "event" on the day(s) after this event,based on some PHP logic. What would be a starting place to start modfitying it ?

For example: I insert 26th of May as a date (in a node of my custom content type). If the day is Saturday, I want the next day to be also marked in the calendar.

# Answer
> 1 votes
Since the event is a content type. You could use hook\_cron to find expired events and add new event node.

**Add node programmatically.**

```
  $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $path = 'content/my-lipsum-' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);

```

How to programmatically create node in drupal 7

---
Tags: views, datetime
---


title: Build StackExchange-style url's

text:
# Question
Title: Build StackExchange-style url's
I'm looking for a way to build what I call 'StackExchange style' url's with Drupal 7. In my definition, that means:

1. A node has a path alias containing both a unique identifier and the node title. For instance, if I'm writing a story and every chapter is a node, chapter 4 (titled "The day I became a lobster") would get www.example.com/chapter/4/the-day-i-became-a-lobster.
2. If a user knows the chapter, but not the title, he can just go to www.example.com/chapter/4, which will redirect to www.example.com/chapter/4/the-day-i-became-a-lobster.
3. If the title changes (www.example.com/chapter/4/the-day-i-became-a-lobster becomes www.example.com/chapter/4/the-day-i-became-a-penguin), or if the url is mistyped (www.example.com/chapter/4/the-day-i-become-a-lobster), the old or incorrect url redirects to the new / correct url.

I want this behavior because:

* In some cases, my users know a product number but not the title. This way they can easily figure out the url.
* Having the title in the url is good for SEO and user experience.

I guess the best approach would be to build the complete url using Pathauto and set up a redirecting mechanism that kicks in when the path start with 'chapter/\[id\]' but it's not a valid path alias.

Of course I can create a custom module, implementing hook\_menu for the 'chapter/%' path, lookup the correct chapter node and call drupal\_goto, but maybe there are better methods. How would you do it?

PS. I posted a similar question in the issue queue of Redirect, because that module looks related and very promising.

# Answer
I wrote a custom module to do this very thing. I use Pathauto to automatticly create aliases for my nodes, in the form of `questions/123/title-of-node-here`. The following code creates a `/custom404` page. I configure my "Default 404 (not found) page" (in Site information) to `custom404`. The module picks the node id out of the url, checks for its existence, and then redirects to `node/%nid`. Finally, the Global Redirect module will take over and redirect the user to the canonical url.

```
/**
 * Implements hook_menu().
 */
function custommodule_menu() {
  $items = array();

  $items['custom404'] = array(
    'title' => 'Page not found',
    'access callback' => TRUE,
    'page callback' => 'custommodule_page',
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

function custommodule_page() {
  $path = _custommodule_request_path();
  $parts = explode('/', $path);

  // The following lines matche a path alias to a content type
  // map /questions/%nid/%title to the 'question' content type
  _custommodule_match_nid($parts, 'questions', 'question');
  // map /websites/%nid/%title to the 'website' content type
  _custommodule_match_nid($parts, 'websites', 'website');

  drupal_set_title(t('Page not found'));
  return ' ';
}

/**
 * custommodule_request_path() is copied from globalredirect_request_path
 */
function _custommodule_request_path() {
  if (isset($_SERVER['REQUEST_URI'])) {
    if (isset($_REQUEST['q'])) {
      $path = $_REQUEST['q'];
    }
    else {
      // This is a request using a clean URL. Extract the path from REQUEST_URI.
      $request_path = strtok($_SERVER['REQUEST_URI'], '?');
      $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
      // Unescape and strip $base_path prefix, leaving q without a leading slash.
      $path = substr(urldecode($request_path), $base_path_len + 1);
    }
  }
  else {
    // This is the front page.
    $path = '';
  }

  // Under certain conditions Apache's RewriteRule directive prepends the value
  // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
  // slash in place, hence we need to normalize $_GET['q'].
  $path = ltrim($path, '/');

  return $path;
}

function _custommodule_match_nid($parts, $path_root, $node_type) {
  if (count($parts) >= 2 && $parts[0] == $path_root && ctype_digit($parts[1])) {
    $id = $parts[1];
    $args = array(
      ':nid' => $id,
      ':type' => $node_type,
    );
    if (db_query('SELECT count(nid) FROM {node} WHERE nid = :nid AND type = :type AND status = 1', $args)->fetchField()) {
      if ($alias = drupal_get_path_alias('node/'.$id)) {
        _custommodule_goto($alias);
      }
    }
  }
}

function _custommodule_goto($path) {
  $options = array(
    'fragment' => '',
    'query' => NULL,
    'absolute' => FALSE,
    'alias' => FALSE,
    'prefix' => '',
    'external' => FALSE,
  );
  unset($_GET['destination']);
  drupal_goto($path, $options, 301);
}

```
> 5 votes

# Answer
I've taken a simpler approach by writing a Drupal 7 module which inserts an additional, title-free alias on node insert. It basically forwards `/content/123` to `/content/123/title` (the canonical alias).

```
<?php
/**
 * Implements hook_node_insert().
 */

function custom_url_redirect_node_insert($node) {
  // Insert Content Type and Path Prefix here.
  // 'contentType' => 'pathPrefix'
  $entries = array(
    'recipe' => 'recipe',
    'blog' => 'blog',
  );
  foreach ($entries as $contentType => $pathPrefix) {
    if ($node->type == $contentType) {
      $alias = $pathPrefix . '/' . $node->nid;
      $isAlias = drupal_lookup_path('source', $alias);
      if ($isAlias == NULL) {
        $node->path['alias'] = $alias;
      };
    }
  }
}

```

**Update**: Further details.

Original poster asked to replicate the StackExchange URL pattern (`/question/{id}/title-name`) via Drupal. It's a great pattern, because it allows better SEO and allows title-names not overwrite each other.

To do this, you will need to:

* Install the Global Redirect module
* Enable "Create a new alias. Leave the existing alias functioning." in Path Settings (`/admin/config/search/path/settings`)
* Add pattern `question/[node:nid]/[node:title]` to your content type in Path Patterns (`/admin/config/search/path/patterns`)

It will output your content type as `/question/{nid}/title-name`.

The problem here, as the poster mentions, is that you cannot access your content by the unique identifier, such as `/question/{nid}`.

That's where this module comes in. It adds `/question/{nid}` as a URL alias, on every new node insert. In Drupal, it will look something like this:

```
Alias                   | System Path
------------------------+-------------
/question/123/new-title | node/123   //updated alias, canonical
/question/123/old-title | node/123   //old alias
/question/123           | node/123   //alias added via module

```

Global Redirect will redirect all aliases to System Path (`/node/123`) and from System Path it will look for the canonical alias (`/question/123/new-title`).
> 0 votes

---
Tags: uri, redirection, path-aliases
---


title: How to order input fields?

text:
# Question
Title: How to order input fields?
For displaying a content, I can modify the fields order using display and field weights.

However, in a node/add/content-type page the input fields doesn't obey the weight given to the display. How can I reorder the input fields in a node/add/content-type page?

# Answer
> 2 votes
Taking as example the Article content type, on admin/structure/types/manage/article/fields, you alter the field's order in the edit form; on admin/structure/types/manage/article/display, you alter the order the same fields are shown when rendering a node.

>

>

---
Tags: nodes, entities
---


title: job schedule skip a job

text:
# Question
Title: job schedule skip a job
In job schedule module, I have bunch of jobs that works, What I want to do is give the admin the ability to stop a certain job as he desires.

The only way I could do is that I could remove the job all together from the table with this:

> JobScheduler::get($job\['name'\])-\>remove($job);

and I would recreate it again.

But isnt there a way to skip the job instead of deleting and recreating it again? Rules maybe?

# Answer
> 0 votes
I ended up deleting the job and recreating it again.

here is how just incase.

```

// job_id = the job id in job_schedule table.
// $import_status = weather we want to delete or create a job.
// $importer_type = I had 2 types of importers to switch between.
// $original value = only recreating a job if it was deleted first.

function schedule_conrtol($job_id, $import_status, $importer_type, $original_value) {
  if ($import_status === 1) {
    // Deleting a job
    $job = array('name' => 'job_name',
                 'type' => $importer_type,
                 'id'   => $job_id
                );
    JobScheduler::get($job['name'])->remove($job);
  }

if ($import_status === 0 && $original_value === "1") {
    // Inserting a job
    $job = array(
    'name'     => 'job_name',
    'type'     => $importer_type,
    'id'       => $job_id,
    'period'   => 1800,
    'periodic' => TRUE,
    );
    JobScheduler::get($job['name'])->set($job);
  }

}

```

and you can control this using hook\_node\_presave

hope this helps.

---
Tags: 7
---


# Question
Title: Does a Context Condition Path need to exist?
I have a context that has a condition Path of FooBar/\* I added a block (Reaction) view for that context. When I go to /FooBar/Mens\_Bible\_Studies, the view shows, but I also get "Page not found"?

```
Page not found

    Mens Bible Studies

    Overview of Mens Bible Studies. Delete if you don't want an overview
        Curabitur tortor - Meets every Wednesday, 6:30 am.

The requested page "/FooBar/Mens_Bible_Studies" could not be found.

```

What am I missing?

Rich

Update based upon the first two responses.

Thanks Boriana and rooby for answering! Here is a little more about what I am doing. At this point I am really not sure why I didn't use a page view. I am leaning to using contexts instead of panels. I want a responsive site and the theme handles that for me so I don't want to force a layout with panels. I want to select my block view based upon the "FooBar" root path. I have a fairly large number of content types tagged with different taxonomy terms. I have a compound view that does all the work. It just looks at the last leaf of the URL (/FooBar/bla1/bla2/blanN... there is a variable depth) and uses that as the taxonomy term and builds a recursive output that descends the taxonomy tree in a way that I can CSS style each level differently. Content tagged as sub-category heading displays differently than content tagged with terminal terms (the lowest level in the branch of the taxonomy hierarchy they are in). I have heading content and then child content under that in the term hierarchy. I thought I could just have the reaction point to the view and have it output. I will try both approaches you both suggested to see what works best. I believe I have to go with rooby's suggestion since I don't think I can have menu entries point to non-existent content. After I posted, I was thinking of just creating a panel page with empty variants that reacted to all the URLs I needed to create. Each of these would point to the same block view.

So Ideally, the new module I would need create (I never created a module before) would take a list of my hierarchical URLs, create phantom pages for them and create menu entries for them. My context would provide the content.

Or, perhaps I should just commandeer the taxonomy term views with what I want since the URLs that I want match the taxonomy term hierarchy.

# Answer
> 1 votes
Yes, the context module does not create pages, it allows you to position blocks on existing pages.

If you want a page that is not a node or a view you can use the empty page module or the panels module.

If you want a bunch of pages that are dynamic like FooBar/\* where there are lots of sub pages, you could also create a custom module to create the pages, by using hook\_menu() and returning an empty string for you page content.

---
Tags: 7
---


title: Theming translation links

text:
# Question
Title: Theming translation links
I need to change translation links attributes, which have been defined in translation\_node\_view function in these lines:

```
$node->content['links']['translation'] = array(
  '#theme' => 'links__node__translation',
  '#links' => $links,
  '#attributes' => array('class' => array('links', 'inline')),
);

```

I'd like to override these attributes in my custom module.

Any help would be appreciated.

# Answer
I found a solution by myself. May be useful for others I think:

```
/**
 * Implements hook_node_view_alter()
 */
function MYMODULE_node_view_alter(&$build) {
    if (isset($build['links']['translation'])){
        $build['links'] = array(
            'translation' => array(
                '#theme' => 'links__node__translation',
                '#links' => $build['links']['translation']['#links'],
                '#attributes' => array('id' => 'translation_links')
            )
        );
    }
}

```

** Now my links have their own ID, so I can customize them as I need with css<br>* If you need to custom only these links, I suggest to use MYTHEME\_node\_view\_alter()*
> 0 votes

---
Tags: theming, navigation, i18n-l10n
---


# Question
Title: Add theme_hook_suggestions only for nodes in content
I am developing a blog with different categories (taxonomy terms) and I wanted to have custom node templates for the nodes displayed on the blog page and category pages. Because my blog page has a view, I am able to use this template for nodes on that view: node--view--blog.tpl.php. But there is no template I can use for the nodes loaded in www.example.com/category/cat\_name (alias for www.example.com/taxonomy/term/3).

I tried suggesting a node template in template\_preprocess\_node() like this:

```
if(arg(0) == 'taxonomy') {
  array_push($vars['theme_hook_suggestions'], 'node__view__blog');
}

```

The problem with this is that now all the nodes inside that page are rendered with that template, including the ones in my sidebar.

Is there a way to filter inside template\_preprocess\_node the only ones that are part of the "main content" of the page?

# Answer
> 1 votes
I would recommend you override the default term page with a view, and then theme it like you are doing for your other view. All you have to do is create a view with that same path (taxonomy/term/%) and it will override the default page.

There is even a view already configured for this purpose, you just have to enable it.

On the views listing admin page it is called "Taxonomy term". Just enable and configure this view and then you can override it's themeing.

# Answer
> 0 votes
The preprocess/process function invoked for the node.tpl.php file don't get any information about which region contains the node going to be rendered in the page. If that information is not given from a CSS class present in `$variables['classes_array']`, the preprocess/process functions don't have any way to get that information.

What you can do is doing as suggested by @rooby, or suggest a template file to use instead of page.tpl.php. See also the information give in hook\_page\_alter() about how a page rendering array is structured.

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


title: How to make a "title" a link

text:
# Question
Title: How to make a "title" a link
Building a content type "news headlines." I want the title to be the headline and I want that headline to link to a outside URL that has the full story. This node-summary could then appear on the home page and in a view and not link to the node but to the outside story. I can make a link that does that but cannot figure out how to make the title do this.

# Answer
What you can do is implementing a preprocess function for the node.tpl.php file, and alter the content of `$variables['node_url']`, which is the variable the template file uses when rendering the title.

```
  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

```

You should first verify `$variables['page']` is not `TRUE`, since that means the node is being shown in its own page, which is not what happens, for example, when the node is shown as teaser in the front page or in a view.
> 2 votes

# Answer
In your view, in the **Fields** section, click on the **Content: Title** field. In the **Rewrite Results** field-set, check **Rewrite the output of this field**. There you can override the output of the field with custom text, replacement tokens, etc. You can also Output the field as a link and set the required link path.
> 0 votes

---
Tags: 7
---


# Question
Title: What is the advantage of the APC module?
I had the APC PHP extension enabled it it seems to work well. I had 0.0% misses and not much fragmentation. Then I installed the APC module with:

```
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';

```

in settings.php. After that the fragmentation becomes enormous and I can't see any performance loss when I disable the module again, but with it is actually enabled I get annoying messages when I use drush. So what exactly is the advantage of using that module?

# Answer
Using APC with PHP and the APC module are two totally different things.

APC for PHP caches the opcode for files. Essentially, when PHP executes a page, it compiles all of the code into opcode. APC caches this, so the next time a file gets used, it can skip the compilation step. This can cause tremendous speed increases in a complex PHP application like Drupal. Running Drupal without APC enabled is a bad idea.

The APC Module is an alternative cache backend for Drupal. Out of the box, Drupal caches data in the database. The APC Module lets Drupal cache the data in the APC user cache. As with everything, tuning APC is essential to getting this to work well.
> 10 votes

---
Tags: caching
---


# Question
Title: Why is my custom module not being recognised?
I am trying to create a simple module by following the instructions in http://websmiths.co/blog/very-introduction-drupals-hookformalter.

I've created the following two files along with the content in them as below:

### mysite\_simplenews.info

```
name = Custom Example
description = Just a simple example module
version = 0.1
core = 7.x
package = Alpha Custom Modules

```

### mysite\_simplenews.module

```
<?php

```

I've uploaded the module to the server, but it is not being picked up in the list of modules.

Is this because I am running Drupal 7 and the tutorial is for drupal 6? Is it because of the `<?php` line in my .module file?

# Answer
Take a look at Creating Drupal 7.x modules

Writing module .info files (Drupal 7.x)

Example The following is a sample .info file:

```
name = Really Neat Widget
description = Provides a really neat widget for your site's sidebar.
core = 7.x
package = Views
dependencies[] = views
dependencies[] = panels
files[] = example.test
configure = admin/config/content/example

```
> 3 votes

# Answer
Contributed modules should be installed under \[siteroot\]/sites/all/modules, under your custom module folder.

Before your module will show up in the Modules listing, make sure you have both a .info file and a .module file (it can be empty for the moment). Call it exactly like your .info file (e.g. mysite\_simplenews.module)

Your .info file looks OK, look here for a more detailed description of what should go inside a .info file: http://drupal.org/node/1075072
> 0 votes

# Answer
For the info of others - I had this issue and the problem turned out to have been caused by the character encoding of the text editor I'd used to create the custom module. For some reason, my editor (notepad++) was using Macintosh EOL format - something not obvious at all - but this was preventing Drupal from discovering the module.

So my advice to others in this situation, in addition to the responses above, is: check your module's character encoding and EOL format by comparison to another module that works fine.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I structure node data that records time and quantity?
I have a node that will have one field that will be updated often by adding a field with a time and quantity of an item. I would like to output the data as a table.

Some fields the node will have are:

```
Title
Description
Type
Year

```

Then it will have data that is updated attached to it:

```
Monday | 4
Tuesday | 7
Friday | 3
Sunday | 9
Monday | 3
Friday | 7
.
.
.

```

I need a field to contain both the data/time and the quantity. Do make a new entity to contain this information and have a mutli value entity reference field? Do I create a field collection? Do I instead make a two value field with the field API? What is the simplest way to store this data? The field will be updated programmatically.

# Answer
These are just my opinion...

* A custom entity would probably be overkill, unless you plan to extend the functionality at some point. If your end game is just to store those key/values pairs, the extra code and DB complexity doesn't feel worth it.
* To extend on that, Field Collection already implements that entity for you, plus all of the entity/field/views niceness. Add the Field Collection Table module as a table formatter, and you'll be probably be ready to go in about 10 minutes.
* A custom field (and formatter for the table) would be reasonably straight forward to implement, but is tricky to extend if you decide, for example, you need another data column. It does have less DB overhead than the Field Collection method (as there isn't another entity involved), though, in case performance is a major issue.

If you're looking for simple, I'd say Field Collection is the way to go.
> 1 votes

---
Tags: entities
---