title: form field not rendering

text:
# Question
Title: form field not rendering
i have a problem theming my user-profile-edit.php the user name field (name) is rendering nothing, while other fields like 'mail' are working good.

```
//contents of user-profile-edit.php
<?php
print render($form['form_id']);
print render($form['form_build_id']);
print render($form['form_token']);
print render($form['account']['name']);
print render($form['account']['mail']);
?>

//contents of template.php
...
function MY_THEME_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
    'user_login' => array(
      'render element' => 'form',
      'template' => 'templates/user-login',
    ),
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'templates/user-profile-edit',
    ),
    'user_pass' => array(
      'render element' => 'form',
      'template' => 'templates/user-pass',
    ),
    'user_pass_reset' => array(
      'render element' => 'form',
      'template' => 'templates/user-pass-reset',
    ),
  );
}

```

in the end when I open the page mysite.com/user/1/edit I can only see the mail field.

any idea of what am I doing wrong?? or how can I render that name field so I can customize the visualization?

# Answer
> 0 votes
Encountered a similar problem when trying to render the Forgot Password form in a block.

Since the form builder for the form is in user.pages.inc, the solution is to load the include file at the same time you do the drupal\_get\_form() to retrieve the form. e.g.

module\_load\_include('inc', 'user', 'user.pages');

If you are calling the form via a hook\_menu implementation, you will need to use the 'file' and 'file path properties'.

---
Tags: forms, theming
---


# Question
Title: Display a list of a user's Organic Groups
While searching, I've found a lot about how to programmatically add things to groups, but I'm wondering if there is a function that will take a parameter identifying the user and return a list of their groups.

Is there a function that takes user info and returns a list of groups for OG in Drupal 7?

# Answer
You can use og\_get\_groups\_by\_user() for that.

> Get the group IDs of all the groups a user is an approved member of.

The API linked to above might be for OG 1.x, it's slightly different for OG 2.x.

```
 function og_get_groups_by_user($account = NULL, $group_type = NULL) {
 ...

```

For instance:

```
 global $user;
 $user_groups = og_get_groups_by_user($user, 'node');

```

The above example is not really great as `$account` defaults to current user and without `$group_type` you get all types of groups, not just node groups, but you get the general idea.
> 3 votes

---
Tags: organic-groups
---


# Question
Title: Drupal multisites share modules and libraries?
I want to duplicate a drupal site to make subsites where each site will utilise the same basic modules and core but just have slight variations in theme and need own database on a dedicated server. To save memory I want to avoid having subsites all containing same modules, I have only briefly read the documentation for drupal multisites where they share the one core but is it possible to share sites/all/modules and libraries as well?

# Answer
> 8 votes
Yes.

In a multisite setup anything in sites/all is shared. This means sites/all/modules, sites/all/themes, sites/all/libraries are all shared.

In addition to that, if you have things that are specific to a subsite, for example, a sub-theme, or a module or library, you can add them in sites/subsite\_name/modules, sites/subsite\_name/themes, sites/subsite\_name/libraries.

---
Tags: multi-sites
---


# Question
Title: D7 - download files works for admin, not for other users
There is a content type for accepting job applications, including resumes and cover letters as files uploaded. The files are set to private.

The form/page is set to unpublished by default - largely to 'fix' some other wonkiness.

Users with admin privileges have no trouble downloading the resume and cover letter files.

The more limited users in HR cannot - Drupal returns a message

> *You are not authorized to access this page.*

I've been tweaking permissions trying to find the magic bullet. The HR user can 'Edit' the individual's application form, but even though the associated resume or cover letter file is shown as a link, once again, the HR role is not authorized.

Any ideas what permission I need to toggle? What's blocking the ability for the HR role to download the file?

# Answer
> 1 votes
As you setup the content type default as unpublished, this will prevent any one to see the individual content but the author of the content(if he or she has permission to "View own unpublished content") and User with the privilege of "Bypass content access control" which probably you don't want to give it to any one but admin, so basically there is a better approach to this :

I recommend to

1) setup content type default as published

2) Setup Content Access module http://drupal.org/project/content\_access

3) Setup content type access permission by Content Access module.

3-1) Use Content access module to prevent any user but HR to have access to the specified content type. This will prevent any one to have access to following content type but HR, so you don't need to worry about content being published.

3-2) give permission to the specified rules (maybe anonymous or authenticated) to be able to create the specified content type.

Note: Don't do this in production environment, first test it to make sure everything is as you want it since "content access" module will rewrite your current website permissions.

If it still seems confusing let me know I will add photos to explain it.

---
Tags: users, files, 7
---


# Question
Title: DB query for tabular results of all a db table's info
I'm really having a hard time getting my head around the DB abstraction layer.

I've got a simple 2 column table and I'd like to output the values in the at table to a template. I've seen plain php/mysqla like this:

```
$result = db_query_range('SELECT age, savingvalues FROM {savingvalues} 21, 65);
while($row = mysql_fetch_array($result))
{
echo $row['age'] . " " . $row['factor'];
echo "<br />";
}

```

and it's something like this I'd like to emulate, even if I have to strongarm it a bit, can anyone please help me figure this out? I'm in drupal 6

Thanks!

Steph

# Answer
Use this table theming, next code created from comments below with some fixes:

```
  $header = array(
    array('data' => t('Age'), 'field' => 'age', 'sort' => 'asc'),
    array('data' => t('Savings'), 'field' => 'savingvalues'),
  );

  $result = pager_query("SELECT age, savingvalues FROM {savingvalues} " . tablesort_sql($header), 30);

  $data = array();
  while ($row = db_fetch_array($result)) {
    $data[] = $row;
  }
  $output .= theme('table', $header, $data);
  $output .= theme('pager');
?>

```
> 1 votes

---
Tags: 6, database
---


# Question
Title: How call a block named Poll Recent from template?
I need to call the block Poll-recent from template. I have tried this code and not work for me. I am working in Drupal 7.

```
<?php
$block = module_invoke('block', 'block_view','poll-recent');
print $block['content']; ?>

```

or

```
<?php
$block = module_invoke('poll', 'block_view','recent');
print $block['content']; ?>

```

What is my error?

Thanks for your help.

# Answer
In D7, you will need:

```
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);

```

In the case of recent poll:

```
<?php
  $block = module_invoke('poll', 'block_view', 'recent');
  print render($block['content']);
?>

```

Curiously, although defined in poll\_block\_info the delta is actually ignored in poll\_block\_view, perhaps as the poll module only provides a single block.
> 1 votes

# Answer
@cabita: Try adding in a fourth argument 'block\_delta' and using the render function to print the output, as suggested in this detailed post on Drupal.org

Hope this helps :-)
> 0 votes

# Answer
Hope this work;

```
$block = module_invoke('poll', 'block_view','recent');
print render($block);

```
> 0 votes

---
Tags: blocks, theming
---


title: Access denied messaging and behavior

text:
# Question
Title: Access denied messaging and behavior
Currently my users are being redirected to a node after trying to first access that node's comment page (comment/reply/nid) via a link in a view. This is because I've set it so you have to be logged in to leave a comment. In the message area, on the node that they are redirected to, is an error message, "Error message: You are not authorized to post comments."

I want to change this so that when an anonymous user accesses the comment/reply/nid she is presented with a login page and then directed back to the comment/reply/nid.

I've tried logintoboggin, but that doesn't seem to work. This is possibly because an access denied message is being displayed, not a 403.

I have a view that displays links to comment on various nodes, and I tried altering the links in this view via `hook_views_pre_render`. I was going to try and add a modal window containing a login form if the user was anonymous by taking a more html and js approach a la Twitter Bootstrap. But I was unable to locate the link in the massive view array. I was hoping for a render array to modify (add a class, add an attribute, etc). Not even sure if this would be a "Drupal kosher" approach.

Any ideas?

# Answer
> 1 votes
You can do it in hook\_views\_pre\_render() like this:

```
/**
 * Implements hook_views_pre_render().
 */
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'VIEWNAME') {
    if (!user_is_logged_in() && !empty($view->field['FIELDNAME']->options['alter']['path'])) {
      $view->field['FIELDNAME']->options['alter']['path'] = 'user/login?destination=' . $view->field['FIELDNAME']->options['alter']['path'];
    }
  }
}

```

Where in this case I would say 'title' is your FIELDNAME.

This will, if the user is logged out, replace whatever you have for your link in the rewrite settings, with a link to the login page, with your original path as the query destination, which will be used to return you to that page after the login form is submitted.

Also, there is the modal\_forms module, which might be worth trying for a pop-up solution. However then you need to take them to the comment reply page after the modal form closes.

---
Tags: hooks, users
---


# Question
Title: Overlay and jQuery don't work, what should I do?
I have installed Drupal 7 on a local computer on stack called Denwer (similar to WAMP) and Windows 7; I see that all pages load without Overlay module (it is on, on modules page). I guess that jQuery does not work at all: Views slideshow doesn't work, when I add node all parameters load in a list instead of paging-listing mode.

I cleared all caches, reinstalled Drupal 7 using the development snapshot, clean-installed Denwer: all this doesn't work.

I remember I didn't have such problems on Windows XP.

# Answer
> 2 votes
Have you seen Overlay and jQuery dont work on Win 7, but work on XP?

The last comment reported in that report is the following one:

> Problem resolved. I still don't know why this problem arise, but after Windows 7 latest updates installed (on 18 apr 2011) overlay and jquery now working.

# Answer
> 1 votes
Check your URL.

The ovelay is enabled by URL in this way: `http://localhost/yoursite/#overlay=admin/appearance`; if you write `http://localhost/yoursite/admin/appearance` the overlay is "disabled".

Also check if the you have the "access overlay" permission in order to see the administrative pages on the overlay.

# Answer
> 1 votes
I noticed I had the exact same problem when I made the mistake of installing a test site in a folder with a space in the name; as soon as I went back and corrected the problem (so the URL did not contain any %20 character) the problem was resolved.

# Answer
> 0 votes
I couldn't get the overlay to work as well after I upgraded Drupal 7 to a newer version. Issue turned out to be some changes I had made to .htaccess. Reverted back to the original .htaccess, and the overlays appeared again.

This was with Server 2003, IIS 6.5 (I think?).

# Answer
> 0 votes
I had the same problem with Drupal 8, if you are using WAMP than go to apache modules, and enable **rewrite\_module** it solved the problem for me right away!

I figured the problem was there because kiamlaluno said (in this post) that is't a URL issue...

Hope this works for whoever googles this problem in the future

---
Tags: 7, javascript, modal-dialogs
---


# Question
Title: How to output content type title on page.tpl.php?
So I am using this code to output nodes title:

```
<?php print render($title_prefix); ?>
<?php if ($title): ?><h2 class="title" id="page-title"><?php print $title; ?></h2><?php endif; ?>
<?php print render($title_suffix); ?>

```

What code do I need to output the content type's name (i.e. content type is Article, so output 'Article' inside each Article content type node page next to node title, above or below it)?

# Answer
> 11 votes
In D7 there is node\_type\_get\_name

```
node_type_get_name($node)

```

**Parameters**

> $node: A node object or string that indicates the node type to return

**Return value**

> The node type name or FALSE if the node type is not found.

# Answer
> 2 votes
You can access the $node object in page.tpl.php typically, as long as a $node object exists (i.e. you are on a node page). So you can use:

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

```

If you want to inspect $node (or anything else for that matter), you can use Devel module. When installed and enabled, it provides a function, `dpm()`, that will let you inspect arrays, objects, etc. as long as you are logged in as a user with permissions to view it. so `dpm($node)` will allow you to inspect the $node object.

The value closest to what you want is probably `$node->type`, but as MPD pointed out, that will give you a machine name, with spaces converted to underscores.

If you want to do it without writing any code, your best option is probably to use Views or Panels to pull that value and display it.

If you don't want to use those, here's how you would do it with a block:

1. Create a block for the content type you want to display.
2. Make the content "My Content Type Name" or whatever.
3. Set the block to display in whatever region you want.
4. Set the block to only display on content of "My Content Type Name".
5. Save the block.

# Answer
> 0 votes
If article is your content type machine name ,

```
<?php
if($node_details->type == 'article'){
   print 'Article or $node_details->type';
 }
?>

```

it will print your content type name in all of is node.Print this in you page.tpl before print $content so that you can print it before the node title.

---
Tags: 7, theming
---


# Question
Title: How to append a Value in cck field in a for loop?
I want to keep a progress field in my content type so i can update value in it. But it doesn't take the previous value if saved in for loop.

```
for($i = 1; $i<=5; $i++) {
    $mynode = node_load(6);
    $myprevious = $mynode->field_progress[0]['value'];
    drupal_set_message("My Previous".$myprevious);
    $mynode->field_progress[0]['value'] = $myprevious." ".$i." ";
    node_submit($mynode);
    node_save($mynode);
}
$mynode = node_load(6);
drupal_set_message("My Value".$mynode->field_progress[0]['value']);
$myprevous_progress = $mynode->field_progress[0]['value'];
$mynode->field_progress[0]['value'] = $myprevous_progress.' end.'.$myprevous_progress;
node_save($mynode);

```

Output on page :

```
My Previous
My Previous
My Previous
My Previous
My Previous
My Value

```

# Answer
> 0 votes
Solved It by using

```
$mynode = node_load(6); //Load the node before for loop
for($i = 1; $i<=5; $i++) {
    $myprevious = $mynode->field_progress[0]['value'];
    drupal_set_message("My Previous".$myprevious);
    $mynode->field_progress[0]['value'] = $myprevious." ".$i." ";
    node_submit($mynode);
    node_save($mynode);
}
drupal_set_message("My Value".$mynode->field_progress[0]['value']);
$myprevous_progress = $mynode->field_progress[0]['value'];
$mynode->field_progress[0]['value'] = $myprevous_progress.' end.'.$myprevous_progress;
node_save($mynode);

```

---
Tags: 6, nodes, entities
---


# Question
Title: Prevent Multiple user registrations from single IP
I'm using Drupal 6.19.I need two things to be done.First thing, I want to disable multiple user registrations from the same IP.The Second thing is ,I want to allow only 3 user to register at a time. Anyone know this how to do in Drupal6.19?

Please help me to do this.

# Answer
I blocked multiple user registration from same IP by customizing the user core module , in the user table I added a column to store the IP address of the user registering. When the function user\_register\_submit calls, I will check if the IP of the user who is registering is already stored in that column or not.

And when the function user\_save executes i will save the IP of the user.

Thanks for the friends who are all posted their answers and comments.Thanks for your support!
> 0 votes

# Answer
You may find the problem there is that Drupal doesn't store the IP address of the user during normal core registration process.

Assuming you can hook in and store that IP address for later lookup, you could then validate that ip address count for the user with something like:

```
/**
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_user_register_alter(&$form, &$form_state) {
  $form['#validate'][] = 'mymodule_user_register_validate';
}

/**
 * hook_form_user_register_alter validation callback
 */
function mymodule_user_register_validate($form, &$form_state) {
  $account = (object) $form_state['values'];
  $ip_address = ip_address(); // api call
  // do something to look up ip_address on registered user..
  // for example:
  $count = db_query("SELECT count(uid) FROM {user_ip} WHERE ip = :ip", array(':ip' => $ip_address))->fetchField();
  if($count > 3){
    $error = t('Sorry, too many registrations.');
    form_set_error('name', $error);
  }
}

```
> 2 votes

# Answer
It\`s not a good idea to block multiple user registrations in this way, it might be possible that some users use the same ip (such as proxies etc.) But anyway you can use User IP Log module with Rules module, to block multiple user registrations. something like this:

1. Install User Ip Log module and rules module
2. Enable PHP Filter module
3. Create a rule ,use your custom php code to check the users Ip log and block theme with your custom conditions.

*** Note that your conditions should be date-realted because Internet Provider Services, assign this IPs to others too.
> 2 votes

---
Tags: users, 6
---


title: Drupal daylight savings issue

text:
# Question
Title: Drupal daylight savings issue
My drupal installation is still displaying summer time after the daylight savings switch yesterday. Wrong dates include the following pages:

* Views displaying nodes with created/updated fields
* Drupal reports page

My timezone is set in drupal config to Europe/Bratislava. I have tested the raw `date()` function in the web server, and it returns the correct time.

It seems that dates are saved correctly by timestamp using a `time()` function; the problem is displaying. Can anybody tell what is wrong? Is it a bug, or something else?

---

I have already found a problem. Drupal variable `date_default_timezone` was set to 7200 for Europe/Bratislava timezone. In fact, the correct value for winter time is 3600 for this timezone.

Solution was to resave the timezone settings under the Drupal "Date and time" configuration within the administration menu. It will then adjust the `date_default_timezone` variable.

I am just curious, why is this switch not happening automatically?

# Answer
> 1 votes
Try out Daylight saving time module.

> This module intended to work with Daylight saving time. It replaces system time offset and has preferences for each user and full site.
>
> Used to display correct time of creation of documents etc.

---
Tags: 7
---


# Question
Title: Autopopulate "Postal Code" from taxonomy in Location module
In Location module input I want to disable "Postal Code" field but the node will have a mandatory vocabulary selection (vocabulary name: Postal Code).

What I want is that when I create a node with the postal code term selection it should automatically populate the "Postal Code" field of location module input from this term.

What is the right way to do it?

# Answer
I think the only way to do this is with a custom module.

You would implement hook\_form\_alter to disable (or hide altogether) the location postal code on the node form.

You would then implement `presave` op of hook\_nodeapi (drupal 6) or hook\_node\_presave (drupal 7) to fill in the location data.

If you don't know PHP, you could also add some custom javascript that changes the location postal code when the taxonomy drop down is changed.
> 2 votes

# Answer
You could use the prepopulate module. My method was to use views to create a url for node creation on my taxonomy pages. Users select the city term and on the page click on "Add a post" link and the form is prepopulated with term from the url.
> 0 votes

---
Tags: taxonomy-terms, location
---


# Question
Title: Unknown column errors because of table alias
Because of truncated identifiers with more than 63 chars, causing Views to break

It causes errors like

> SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'taxonomy\_term\_data\_node\__draggableviews\_structure\_weight\_coalesce' in 'order clause'

**Goal:** I want to change the table alias from `_draggableviews_structure_` to `_dv_`

If I change

```
    $data['draggableviews_structure']['weight'] = array(
      'title' => t('Weight'),
      'group' => t('Draggableviews'),
      'field' => array(
        'help' => t('Display the weight value.'),
        'handler' => 'views_handler_field_numeric',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'help' => t('Sort entities by the draggableviews weight table field.'),
        'handler' => 'draggableviews_handler_sort',
      ),
    );

    $data['draggableviews_structure']['parent'] = array(
      'title' => t('Parent'),
      'help' => t('The parent entity id.'),
      'group' => t('Draggableviews'),
      'field' => array(
        'handler' => 'views_handler_field_numeric',
      ),
    );

  // Explain to every entity how to join with draggableviews structure table.
    $data['draggableviews_structure']['table']['join'][$info['base table']] = array(
      'handler' => 'draggableviews_join_handler',
      'left_table' => $info['base table'], // Because this is a direct link it could be left out.
      'left_field' => $info['entity keys']['id'],
      'field' => 'entity_id',
    );

```

to

```
   $data['dv']['weight'] = array(
     'title' => t('Weight'),
     'group' => t('Draggableviews'),
     'field' => array(
       'help' => t('Display the weight value.'),
       'handler' => 'views_handler_field_numeric',
       'click sortable' => TRUE,
     ),
     'sort' => array(
       'help' => t('Sort entities by the draggableviews weight table field.'),
       'handler' => 'draggableviews_handler_sort',
     ),
   );

   $data['dv']['parent'] = array(
     'title' => t('Parent'),
     'help' => t('The parent entity id.'),
     'group' => t('Draggableviews'),
     'field' => array(
       'handler' => 'views_handler_field_numeric',
     ),
   );

   // Explain to every entity how to join with draggableviews structure table.
   $data['dv']['table']['join'][$info['base table']] = array(
     'handler' => 'draggableviews_join_handler',
     'table' => 'draggableviews_structure',
     'left_table' => $info['base table'], // Because this is a direct link it could be left out.
     'left_field' => $info['entity keys']['id'],
     'field' => 'entity_id',
   );

```

This works. However, all of the views with draggableviews fields/sort components have disappeared. In the admin view, views complains able missing relationship, and it trying to fix them for you. If you read the fields, the view works again.

Is there a way to fix this, without manually changing everything? Is there a better way to solve it?

# Answer
> 2 votes
I've used the MD5 alias patch from that issue queue here: http://drupal.org/files/issues/views-571548\_40.patch (#40) to fix that issue.

You may need to apply the patch manually to views/includes/query.inc

The good news is, if you can do that, it should fix all those alias truncation issues for you.

---
Tags: theming, views
---


# Question
Title: What is the url for product page in drupal commerce. Its admin url is : admin/commerce/products/2
I am using drupal commerce for first time. I have created a product. I am unable to find the product view url. Its admin url is : admin/commerce/products/2

# Answer
> 1 votes
In Drupal Commerce, you need to add product entities separately from product display pages. We simply create a product display node and reference all of our product entities using the product reference field.

See the docs for more help on this.

http://www.drupalcommerce.org/user-guide/products

---
Tags: commerce
---


title: Problem blocking users in Drupal 6

text:
# Question
Title: Problem blocking users in Drupal 6
I have encountered a weird problem in a Drupal site. Whenever I try to ban an abusive user, by going to the user's profile, change his status from active to blocked, and click save, the change does not take effect. Instead I just get a server time out message. There are a couple of thousands of users so disability to ban abusive ones is quite a hassle. Any suggestion to solve this?

# Answer
Do it in the actual database, not via Drupal but via CLI, PHPMyAdmin, or whatever you have.

1. Find out the user's ID.
2. Go in to the raw database, i.e. not via Drupal but via CLI, PHPMyAdmin.
3. Go the user table.
4. Find their ID.
5. Set the status field for that user to 0 (which means blocked).

The raw SQL would be something like (I haven't tested this):

```
UPDATE users SET status = 0  WHERE id = [user's id]

```
> 5 votes

# Answer
To block certain users in drupal6 go to the user management-\>access rules this will take to you www.yoursitename/admin/user/rules/list . In this click "Add Rule" tab and select "Deny" under access type and "Username" under Rule type (as you want to block the user) and enter the user name in the text field under the "Mask" and click "Add rule".
> 0 votes

---
Tags: users
---


# Question
Title: how to do validation for duplicate primary key in database
I want to alert user for duplicate primary key insertion in database. here is the code:

---

```
<?php

function formModule_menu() {
  $items = array();

  $items['form/formModule'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Form', //page title
    'description' => 'A form with a text field and Submit button.',
    'page callback' => 'formModule_intro', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form

    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['form/formModule/form1'] = array(
    'title' => 'Form One',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

  return $items;
}

function formModule_form($form, &$form_state) {

 $result = db_query("SELECT n.nid, n.title FROM {node} n
                         WHERE n.type = 'product'");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->title;
    }
    //dsm($options);

    $form['productid'] = array(
    '#type' => 'select',
    '#title' => t('Select a product'),
    '#required' => TRUE,
    '#options' => $options,
    '#description' => t('Choose an option.'),
  );

  $form['stock'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'Enter the stock',
    '#size' => 10,
    '#maxlength' => 10,
    '#description' => t('stock should be integer value'),
    '#required' => TRUE, //make this field required
  );

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

  return $form;
}

function formModule_form_validate($form, &$form_state) {

if (!($form_state['values']['stock'] > 0)){
   form_set_error('stock', t('Stock must be a integer value only.'));
  }

}

function formModule_form_submit($form, &$form_state) {

global $user;

  // Here u can insert Your custom form values into your custom table.
  db_insert('formModule_stock')
    ->fields(array(
      'productid' => $form_state['values']['productid'],
      'stock' => $form_state['values']['stock'],
      'created' => REQUEST_TIME,

    ))->execute();
    drupal_set_message("successfully saved formModule_stock");

}

```

# Answer
> 1 votes
What you are doing is:

* Show a "select" form element containing a list of nodes whose content type is "product"
* Show an error if there is a row in a database about the node the user selected

That is poor UX.
Suppose that there are 20 nodes of that content type, and only two nodes don't have a row in the database table where you save the data; there is a high probability the user gets the error message about the data being already present at least two times. Imagine what would happen when all the nodes have a corresponding row in the other database table.

What you need to do is showing only the nodes for which there isn't a row in the other database table. That means, for example, using a query like the following one.

```
$result = db_query("SELECT n.nid, n.title FROM {node} n WHERE n.type = 'product' AND n.nid NOT IN (SELECT s.productid from {formModule_stock} s)");

```

The module should also show a message in the case all the nodes have a row in the other database table. In this case, the user should not see the form to select a node, rather than seeing a "select" form without any item.

As side note, avoid using upper case letters in the short name of modules. While PHP is case insensitive, you would have problems when you write update functions for your module.

---
Tags: forms
---


# Question
Title: Adding links to $content['links'] in theme layer
I know that I can use template\_node\_view\_alter() or template\_preprocess\_node() in template.php, but the problem is, that some of the information that I can alter there, seems to be processed already. For example:

```
$variables['content']['links']['node']['#links']['node-readmore']['title']

```

have some styling informations and a bit of text that is already translated. Is it possible to add a link even before, that structure was constructed? I don't want to overwrite something that was generated by Drupal for specific purpose.

# Answer
> 1 votes
You don't have to worry about overwriting what is there, just don't overwrite anything :)

The correct place for altering links is generally hook\_node\_view\_alter(), as you mentioned.

For adding your own links it is hook\_node\_view()

As an example see http://drupal.org/node/224333#node\_links

# Answer
> 0 votes
Before the node, comes the page. To process before the page, try

```
function MYTHEME_preprocess_page(&$variables) {

}

```

And before the page, comes HTML. To process before HTML, try

```
function MYTHEME_preprocess_html(&$variables) {

}

```

This would also go into your template.php

UPDATE:

You'll first need to know what's currently in the `$variables` array. To do so, you'll need to install & enable the Devel module. Then insert `kpr($variables);` within the preprocess function. When you'll refresh the page, you'll see what's actually inside the $variables array.

If you want to modify `$variables['content']['links']['node']['#links']['node-readmore']['title']`, you'd simply do this:

```
function MYTHEME_preprocess_page(&$variables) {
  $variables['content']['links']['node']['#links']['node-readmore']['title'] = 'title';
}

```

Say, you want to keep the title, but want to add a `<div>` tag around it. This is where you need to follow Drupal Forms API.

`['#prefix']` and `['#suffix']` will include string before and after form.

Here's the code:

```
function MYTHEME_preprocess_page(&$variables) {
  $variables['content']['links']['node']['#links']['node-readmore']['#prefix'] = '<div>';
  $variables['content']['links']['node']['#links']['node-readmore']['#suffix'] = '</div>';
}

```

Don't forget to change MYTHEME into your theme name, check if $variables array of the item you're changing, actually exists, and flush cache.

---
Tags: 7, navigation, theming
---


# Question
Title: custom node type that save to a custom table
I’m trying to convert one of my sites into a Drupal site. The site is a travel site and has a lot of data on there, so I’m trying to convert my database tables to custom node types, but my tables are large, I have about 30 different tables with a total of about 200+ fields.

If I would just convert all the fields to CCK fields I would end up with a database with 400 to 500 tables, I don’t like that, so I’m trying to create custom node types that save to custom tables.

Does anybody know how to do this, and if you know of an example somewhere that would be great

Thanks Rob

# Answer
You're probably best off if you use the Feeds module to import your data into Drupal. Messing with the database configuration yourself just because you "don't like that" a lot of tables would be generated seems like a lot of work for not much potential benefit.

If you're worried about filling up the Drupal database, it is possible to use one database for Drupal's content and configuration, and another for data that you're using Drupal to expose to users. D7 boasts master/slave database configuration support. It is also possible to integrate with databases that Drupal does not support for its main configuration database, e.g. Mongo.
> 2 votes

# Answer
You need to explore the Entity API module. You will have a lot of custom coding ahead of you. But when you're done, your new entities can act just like nodes.
> 0 votes

---
Tags: nodes
---


# Question
Title: Change label of an exposed filter button in Views
I have an exposed filter, and instead of having the button to activate it have an 'apply' label, I'd like to change it to something else. How can I do that?

# Answer
This question is regarding D6. However just fyi, in Drupal 7 you can change the label much more easily by going to "Advanced" in your view edit page, then in the exposed form settings you can change the button label as well as other look and feed settings.
> 4 votes

# Answer
You can change the submit button label using hook\_form\_FORM\_ID\_alter in a custom module. For example, to change "Apply" to "Search" add this function to example.module:

```
function example_form_views_exposed_form_alter(&$form, &$form_state) {
  $form['submit']['#value'] = t('Search');
}

```
> 2 votes

# Answer
You can use the Better Exposed Filters module. gives you greater control over the rendering of exposed filters.
> 1 votes

---
Tags: views, 6
---


# Question
Title: How to write .install file for a custom module
I am new to drupal and want to write a .install file for my custom module. here is the code of my module.

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

  $items['form/formModule'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Form', //page title
    'description' => 'A form with a text field and Submit button.',
    'page callback' => 'formModule_intro', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form

    'access callback' => TRUE,
    'expanded' => TRUE,
  );

  $items['form/formModule/form1'] = array(
    'title' => 'Form One',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
  );

  $items['form/formModule/form2'] = array(
    'title' => 'Form Two',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formModule_formOne_one'),
    'access callback' => TRUE,
    'file' => 'formModule_formOne.inc',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 2,
  );
  return $items;
}

function formModule_form($form, &$form_state) {

 $result = db_query("SELECT n.nid, n.title FROM {node} n
                         WHERE n.type = 'product'");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->title;
    }
    //dsm($options);

    $form['productid'] = array(
    '#type' => 'select',
    '#title' => t('Select a product'),
    '#required' => TRUE,
    '#options' => $options,
    '#description' => t('Choose an option.'),
  );

  $form['stock'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'Enter the stock',
    '#size' => 10,
    '#maxlength' => 10,
    '#description' => t('stock should be integer value'),
    '#required' => TRUE, //make this field required
  );

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

  return $form;
}

function formModule_form_validate($form, &$form_state) {

  if (!($form_state['values']['stock'] > 0)){
   form_set_error('stock', t('Stock must be a integer value only.'));
  }
}

function formModule_form_submit($form, &$form_state) {

global $user;

  // Here u can insert Your custom form values into your custom table.
  db_insert('formModule_stock')
    ->fields(array(
      'productid' => $form_state['values']['productid'],
      'stock' => $form_state['values']['stock'],

    ))->execute();
    drupal_set_message("successfully saved formModule_stock");

}

```

How do I create the table my module is using?

# Answer
> 5 votes
In Drupal 6, `hook_install()` is necessary to create the database tables used from the module; the code of that hook simply calls drupal\_install\_schema(), which then invokes the implementation of hook\_schema() present in the installation file.
In Drupal 7, or higher, only `hook_schema()` is necessary to create the tables used from the module.

So, in both the cases, you implement `hook_schema()`. I would implement it as follows.

```
function formModule_schema() {
  $schema ['formModule_stock'] = array(
    'description' => 'The base table for stocks.',
    'fields' => array(
      'productid' => array(
        'description' => 'The primary identifier for a stock.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'stock' => array(
        'description' => 'The current stock value.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('productid'),
  );

  return $schema;
}

```

# Answer
> 4 votes
Probably you have already created the database for your module. In that case you might want to check out the Schema module, which helps you to create the array to be used in hook\_schema().

---
Tags: 7, hooks, installation
---


# Question
Title: How do you contribute patches to Drupal core?
What is the proper process to contribute patches to Drupal core?

Let's say I find a bug in Drupal core, fix it, and create a patch. How do I submit it?

If the bug is in Drupal 7, do I have to also fix it in Drupal 8, and submit two patches? Does this also apply to documentation bugs/improvements?

Do all patches also require a unit test?

# Answer
> If the bug is in Drupal 7, do I have to also fix it in Drupal 8, and submit two patches?

If the bug is present in the version being developed (in this case Drupal 8), and the previous version (Drupal 7), then the bug should be first fixed the currently developed version, and then on the previous version(s).

If the bug is not present in the latest developed version, for example because the bug is for a function that has been removed, or that has been already changed, then the patch should be provided for the version before the currently developed one.

The workflow that is followed is:

* First the patch is created, and submitted for reviews, for the most recent version, even if still under development (such as in the case of Drupal 8)
* Once that patch is applied to Drupal, a patch that applies for the previous version is created, and submitted for reviews

You can create patches for two Drupal versions at the same time, but since the patch for the latest Drupal version could require changes, it is better to work on the patch for the currently developed version, than working on two different patches that both require to be changed.

See also: Backport Policy.

> Does this also apply to documentation bugs/improvements?

Yes, it does. Also in this case, if the currently developed version removed the function/method to which the documentation is referring, then the patch needs to be provided for the previous version.

> Do all patches also require a unit test?

If the patch is for the documentation, it doesn't require tests. The test bot running on http://qa.drupal.org checks the Drupal code after the patch is applied; if the patch introduces syntax errors (for example because the comment is closed before the needed), then the test bot will report an error about the patch before tests are run.

If the patch is for a new feature, then the tests are required.

If the patch is to fix a bug, then the tests could be required from the maintainers, if there isn't already a test checking a specific feature. The test is generally necessary to avoid re-introducing the same bug when changing in future the same code. If the bug is merely a variable that is initialized, but never used from a function/method, then chances are the tests are not required.
> 6 votes

# Answer
Every project page on drupal.org has a "Version control" tab at the top. It gives not only a great overview of all the code repository options for the specific project, all the git command examples are also tailored for the project. You can even interactively change it to a specific version too.

For Drupal core you find that page on http://drupal.org/project/drupal/git-instructions

Then when you have created your patch, you simply just attach the patch file to an issue that explains what you patch does.

Two important things to point out is to make sure the patch is ending with ".patch" and to set the status to "Needs review". This so that the testbot will notice it and automatically run its test.

New code always needs to be accompanied by tests.

Note that this is possible to turn off by projects and some do. For Drupal core it is on though so all patches will be tested.

You can find more at http://drupal.org/contribute/development .
> 3 votes

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


# Question
Title: Customise Title Mark Up from template.php
On my site, I have several content types. They all use the same node--content\_type.tpl.php file. However, the mark up applied to the node title has to change depending on the content type.

How can I modifying the title according to the content type from template.php?

(I don't want to use too many IF statements in my node.tpl.php file as you are supposed to keep those files clean, so I want the code to go in my template.php file).

(This question is for Drupal 7).

# Answer
I found the solution to this

1. Create a field called Title
2. Your users use this new field to enter a title
3. Use Auto Node Title to automatically title the node based on this field.

You can ow hide the original title in your theme and use the new title filed instead. The new title field can be customised like a regular field.
> 2 votes

# Answer
You could use Display Suite to control the layout of your content type including how to visualize each field which includes the title, you will need to activate Display Suite Extras so you can control how to output each field. I think the field template could be your answer for this. You can find a demo and extra information in the following links:

This could be a good alternative if you don't want to use many if's statements in your tpl.
> 0 votes

---
Tags: theming
---


title: Create ubercart ordes for users

text:
# Question
Title: Create ubercart ordes for users
I need to create ubercart orders for a bunch of users. Can this be done with views and VBO or do I need to make a custom module for that?

# Answer
> 0 votes
You would need to create a custom module for this as you want to create X number of orders for X number of users. Reason why you need a custom module is because each order is its own node with a bunch of references to other data on the site. Doing this in bulk would require you to know all the tables data that are updated and inserted when an order is created.

---
Tags: ubercart, views
---


title: Controller classes in Entity API

text:
# Question
Title: Controller classes in Entity API
I'm trying to follow this article to build my first entity using Entity API module. I'm unclear about the dependency between controller classes and include files. If it says:

```
'controller class' => 'ExampleTaskController',

```

does this mean the class has to be in a separate file named exactly as the class name (as it is in Views)?

# Answer
> 5 votes
No.

'controller class' =\> 'ExampleTaskController',

> controller class: The name of the class that is used to load the objects. The class has to implement the DrupalEntityControllerInterface interface. Leave blank to use the DrupalDefaultEntityController implementation.

Says *nothing* about where the class code actually lives in Drupal. The easiest place to put it is in the same file your declaring `hook_entity_info`. Because since it's in the same file it will be found by PHP because the class will have the same `file scope` as your hook\_entity\_info implementation, and likely the other hook functions needed for your entity.

In PHP there are only 3 scopes: file scope, function scope and global scope.

So how can it live outside of say `YOURMODULE.module`. You declare where this class can be found in your `YOURMODULE.info` file with the `files[]` directive.

Such as:

```
name = my custom module
package = other
files[]= EntityClassController.inc

```

Files defined by the `files[]` entries are scanned for class definitions and included automatically by Drupal in its bootstrap phase to be available as-needed by running code. So your class would live in the file location of `DRUPAL_ROOT\sites\all\modules\mymodule\EntityConroller.inc` as an example.

Alot of times to organize code better developers add subfolders, or submodules to their modules you could for instance declare the class to live in an `includes` folder in your modules folder with:

```
files[]= includes/ExampleTaskContoller.inc

```

Some hook functions such as `hook_views_api` and `hook_menu` allow you to define a file location where the `page callback` function can be found (in the case of hook\_menu) or where your views implementation classes/handlers/etc may be found in the case of views.

For instance hook\_menu allows for the following 2 keys to better organize where page callback functions live in your source code:

> "**file**": A file that will be included before the page callback is called; this allows page callback functions to be in separate files. The file should be relative to the implementing module's directory unless otherwise specified by the "file path" option. Does not apply to other callbacks (only page callback).
>
> "**file path**": The path to the directory containing the file specified in "file". This defaults to the path to the module implementing the hook.

Views allows 1 to define where views includes lives via hook\_views\_api:

> **path**: (optional) If includes are stored somewhere other than within the root module directory, specify its path here.
>
> **template path**: (optional) A path where the module has stored it's views template files. When you have specificed this key views automatically uses the template files for the views. You can use the same naming conventions like for normal views template files.

---
Tags: entities
---


# Question
Title: Should I log the user out after calling an API using the Services module?
I am using Services 3.X to make API calls in my Drupal installation. In order to update a user I:

1. Make an API call to log in with an account which has rights to modify users (I'm using an admin account)
2. Using the session I received from step 2, I make another API call to modify a user.

That works. My question is, should I have a step 3 and log out the account I used in step 1? The logout, of course will be done via the Services API. Would there be any bad side effects of *not* logging the account out?

Thanks.

# Answer
> 2 votes
If you log the user out, the session ID that you received and used to modify users will expire, so it's recommended to do so.

I can imagine the following scenario:

You leave the user logged in. Someone else who have access to the server that you used to do the aforementioned actions somehow figures out the recently used session ID. They can use it to log in to your Drupal site within the maximum session lifetime.

# Answer
> 0 votes
Basically, if you don't need that user session anymore, then you should log the user out.

e.g something like:

```
curl http://example.com/services/user/logout -d "" -H "Cookie: SESS46e169b3ee0c2423dbf60ab06d25e9d7=9cc1a2cfa782d3d614a947a6a48066a0;" -v

```

---
Tags: services
---


# Question
Title: Rules UI, accessing a Variable created in another rule
Any idea how to access a Variable created in another rule. I am trying to use the Data Comparison in the conditions section. Is doing this even possible or are Variables only visible within the Rule they were created?

Thanks

# Answer
> 2 votes
The variable you created in one rule will not automatically be available to other rules.

However, if there is a rule that creates a variable that you may need to reuse frequently, one thing you can do is create it as a **rules component**. Then you can reuse that setup multiple times. It can also keep your rules leaner and cleaner!

---
Tags: rules
---


title: How to use og_is_member() API?

text:
# Question
Title: How to use og_is_member() API?
> **Possible Duplicate:**
> OG groups: How to check if user is a member or not?

I don't know how to use this: http://api.drupalize.me/api/drupal/function/calls/og\_is\_member/7

I want to check if user is a member of group or not.

Can someone help me?

Thank you!

# Answer
I'm not sure what difficulty you're having using the function or what Drupal version you're on, but according to drupalize.me, in Drupal 7 `og_is_member()` takes parameters `$gid` (ID of group), `$entity_type` (defaults to 'user'), `$entity` (defaults to current user), and `$states` (optional, defaults to all), and returns `TRUE` if the entity (e.g. current user by default) belongs to the group.

For example, to find out if the current user is a member of group 4, I would use something like,

```
$current_user = global $user;
if (og_is_member(4, 'user', $current_user)) {
  // show the user some stuff from group 4
}

```

The above code is not tested but should get you started.
> 2 votes

---
Tags: organic-groups
---


# Question
Title: Drupal Commerce: How to manage different payments (a total amount can be pay in different shares and the user can choose in how many shares)
I´ve just installed the Drupal Commerce module in D7, and after watching the video tutorials I think it´s fairly complex, maybe it´s just too much for what I want to do.

I´ve this site where we only sell e-courses. Each course has a total cost, but people can pay just a small part to get enrolled. The problem is that people have a minimum to pay, but they can pay a bit more if they want, so even is the total price is fixed, I get people to pay different amounts of money each time.

In example:

Course A costs 1000.

To get enrolled you have to pay 100, and then 100 per month (those are recurring payments).

**Now, one student can pay 200 when he enrolls, and then after that he can, if he wants, to pay in 200 shares instead of 100 shares. Maybe he can pay 300 to get enrolled and then shares of 100 each.**

How may I manage that with Drupal Commerce? Is it possible?

Thanks!

# Answer
There is Commerce Installments

> Commerce Installments allows you to create installment payments for products in a Drupal Commerce store.

Make sure you read Issues for Commerce Installments
> 2 votes

---
Tags: commerce
---


# Question
Title: Drupal Commerce: Can I have product list and checkout in the same page?
I have a D7 site and I´m trying to implement Drupal Commerce.

I just need a page where the user can select the product from a list, and give some information about himself (billing information). And at the bottom it should be the "buy" button.

I don´t want a cart, the possibility of "continue shopping" and stuff like that.

How may I do that with Drupal Commerce? I´ve watched all day the videos and read some documentation, but it really seems over complicated when you just want a simple thing (opposed to a big ecommerce site).

Any guidance, tip or help will be very much appreciated. Thanks!

# Answer
Try Commerce Express Checkout

> The Express Checkout button redirects to the Checkout page directly, without going to the Cart first, It also removes the Review page and adds the Payment checkout pane to the Checkout page, so the whole checkout process is done on one page.

Ckeck

1. http://www.drupalcommerce.org/discussions/952/all-checkout-steps-one-page
2. http://atendesigngroup.com/blog/express-checkout-drupal-commerce
> 4 votes

---
Tags: commerce
---


# Question
Title: how to get nid of a node when user is not on a node page
I had made a custom form and want a field in it that would work as a node reference field. Currently iam not on the node page but i want the nid of nodes of a content type to be the options of the select field which is my node reference field. here is the code for the select field that should work as node reference field.

---

```
function formModule_form($form, &$form_state) {

    $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('What is your Qualification?'),
    '#required' => TRUE,
    '#options' => array(
      '1' => 'UnderGraduate',
      '2' => 'Graduate',
      '3' => 'Post Graduate',
         ),
    '#description' => t('Choose an option.'),
  );

return $form
}

```

---

the #option in the above code should have the nid of nodes.

# Answer
> 4 votes
You'll want to Query the database for the nodes you need and then use the results of that query to populate the #options property. Something like this:

```
<?php
    $result = db_select('node', 'n')
    ->fields('n')
    ->condition('type', 'node_type_name','=')
    ->condition('status', 0,'>')
    ->execute()
    ->fetchAssoc();
?>

```

You can then use the results of that query easily since it comes back as an associative array. You'll want to specify exactly which fields you want (in your case, probably just title and node. See http://api.drupal.org/api/drupal/includes!database!database.inc/function/db\_select/7 for how to do a proper select.

# Answer
> 1 votes
You could call a simple query and create the option list something like this

```
    $result = db_query("SELECT n.nid, n.title FROM {node} n
                         WHERE n.type = 'content type name'");

    $options = array();
   foreach($result as $row) {
      $options[$row->nid] = $row->title;
    }

```

Now you can assign `'#options' => $options`

# Answer
> 1 votes
If you're in Drupal 7, I'm a big fan of Entity Field Queries. To get a list NIDs of all nodes of type article, that are published, and have a value in `field_foo` of "bar":

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_foo', 'value', 'bar', '=')
$result = $query->execute;

```

EFQs enable you to write queries without knowing the details of the table and column names, and you can also run them with the permissions of a specific user. They return an array of entity IDs so they're ideal for just finding the NID of a node.

---
Tags: database
---


title: Views "post" filter (complex query)

text:
# Question
Title: Views "post" filter (complex query)
I have a View (let's call it A) that gets the 4 more recent nodes of type News. The News node has a boolean field called IsImportantNews. Since I render the most recent important News (IsImportanNews = true) in another View (B), I'd like to filter out from View A the most recent important News that I already shown in View B.

Eg:

```
News1 -> date: 02 Mar 2013, IsImportant = false
News2 -> date: 01 Mar 2013, IsImportant = false
News3 -> date: 25 Feb 2013, IsImportant = true
News4 -> date: 21 Feb 2013, IsImportant = false
News5 -> date: 19 Feb 2013, IsImportant = true
News6 -> date: 11 Feb 2013, IsImportant = true

```

I'd like to show the News3 in the View B (and I can do that easily). I'd like to show News1/2/4/5 in the View A, somewhat filtering out the News3.

Is there a way to do that? I thought about taking the 5 more recent News and than apply some php code to filter out the unwanted News but I can't seem to find a place to put that code without writing a new module. Is there another way to do that?

# Answer
hook\_views\_pre\_render() would enable you to filter out results *after* the query has already been run. Keep in mind that the results that are filtered out are still part of the query, with all the performance ramifications of that. Putting that in a custom module would be how I would do that.

If you don't want a view that's just a filtered version of the `IsImportant == TRUE` view, you could clone the first view and create a similar one whose only difference is that it returns four more results than the `IsImportant == TRUE` view. You could then add whatever filtering logic you want, and then limit the display to a certain number of items before rendering.

You may also want to take a look at the Peek Summary module, since it gives some further granularity to number of results returned beyond what Views alone offers.
> 1 votes

# Answer
If the most recent important view was a page view you could use hook\_get\_page\_view() to get the important view from within hook\_view\_pre\_view() of the other most recent view. Then you can check the results of the important view and use those results to add an nid argument that excludes those nids.

However I'm guessing you are using two blocks, in which case that solution won't work.

The most number of results you will need to choose from in the other most recent view is 8. This is in the case that you have to pull out all 4 of the items from the other view.

So set your other most recent view to return 8 results. Also, make sure that the important field is a field of the view.

Then from those 8 results, the first 4 important ones will always be the ones from the other view. So you can loop through the results and display the first 4 results that don't include the first 4 important ones.

There are a number of ways you can strip out the ones from the other view. A couple are: Use hook\_views\_pre\_render() in a custom module and loop through the results and pull out the ones you don't want. For example:

```
/**
 * Implements hook_views_pre_render().
 */
function MODULE_NAME_views_pre_render(&$view) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME' && !empty($view->result)) {
    $important_count = 0;
    foreach ($view->result as $key => $result) {
      // Exclude the first 4 important results.
      if ($result->IMPORTANT_FIELD_NAME) {
        if ($important_count < 4) {
          unset($view->result[$key]);
        }
        $important_count++;
      }
    }
  }
}

```

Or you can do it in your theme in template.php like this (I'm assuming you have a HTML list type view, as that would be most semantic):

```
/**
 * Preprocess variables for list views.
 */
function THEME_NAME_preprocess_views_view_list(&$variables) {
  if ($variables['view']->name == 'VIEW_NAME' && $variables['view']->current_display == 'DISPLAY_NAME') {
    $important_count = 0;
    foreach ($variables['view']->result as $key => $result) {
      // Exclude the first 4 important results.
      if ($result->IMPORTANT_FIELD_NAME) {
        if ($important_count < 4) {
          unset($variables['rows'][$key]);
        }
        $important_count++;
      }
    }
  }
}

```

You could also do it in the views-view-list.tpl.php (or whichever template file is relevant to your view) template file but that is not recommended. I would recommend the pre\_render first then the template.php preprocessor second if you really for some reason have an aversion to making custom modules. The reason being is that the theme is meant for front end display and this is ore of a back end functionality task, which really should be in a module.
> 0 votes

# Answer
You would use a new filter group to achieve this. To use this you would follow the below steps.

The first step would be to add all the filters that you used in the View B but with just the oposite filtering. for example in View B you added a filter say IsImportant = TRUE. then here it would be IsImportant = false. If you have put the date as less then some value then in this case it would be greater than. What this does is create a filter that would return all the values except the one in the View B.

Now we go ahead and create w filter group as shown below

Click on and/or, rearrange

You would get a screen similar to the one below

Click on Create new filter group. which creates a new group and should be shown as below.

From the dropdown that is there in between the two groups you can select the operator AND/OR. In your case I think you would need the AND operator as you would want both the operation to filter it out.

We select the filters that we created for excluding view B in to the second group. So that it would stay as group and filter it out.

A bit more clarity on the Group Filtering.

Let us assume that the first group filters out in the following manner.

* Published Nodes (AND)
* Nodes of the type News

Now this would return all the nodes irrespective of if it is important or not.

Now the second group would do the following

* Nodes without the isImportant = False (OR)
* Nodes That are Older than X days.

Now this would give us all the nodes that are not important OR are x days old. That means it would return all the nodes that are not important with in x days and would return all the nodes that are older than x days irrespective of if that is important OR not.

Now if we AND these two groups we would get a list of all nodes that are Not Important with in x days and All nodes older than x days irrespective of wether they are important or not.

Now you can sort it with respect to the date and limit the number of entries to 4 or what ever you want it to be.

I hope that is what you are looking for.

Hope that clears it.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Page not found - Even after I implemented Hook_Menu()
I have implemented hook\_menu() & called a function, but if I am trying to browse the page URL it's giving me "Page not found" error...

This is the code --

```
function user_type_registration_menu(){
  $items = array();
    $items['paypal/payment/ipn'] = array(
          'title' => t('Paypal Payment IPN'),
          'description' => t('Paypal Payment IPN'),
          'type' => MENU_CALLBACK,
          'page callback' => 'paypal_payment_paypal_ipn_callback',
          'access callback' => TRUE,
        );
      return $items;
}
function paypal_payment_paypal_ipn_callback(){
  dpm("here");
}

```

I have cleared the cahche too..so cahche can't be the problem...

# Answer
> 2 votes
With the code you posted you will get a blank page.

If you actually return something from your callback you will get a proper page, with no 404 error. A menu callback has to actually return something.

For example, this works:

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

  $items['paypal/payment/ipn'] = array(
    'title' => t('Paypal Payment IPN'),
    'description' => t('Paypal Payment IPN'),
    'type' => MENU_CALLBACK,
    'page callback' => 'paypal_payment_paypal_ipn_callback',
    'access callback' => TRUE,
  );

  return $items;
}

function paypal_payment_paypal_ipn_callback() {
  dpm("here");
  return 'test';
}

```

Also, make sure your module is named "user\_type\_registration" or else your menu hook will not get picked up.

---
Tags: 7, routes
---


# Question
Title: D6 + Services 3 + Appcelerator = Login help!
I am in the process of (slowly) converting a community forum site from vb4 to drupal. Before I can make the full switch I need to put together a mobile app similar to tapatalk as a large number of my users post almost strictly from their phones.

I had done a little work previously with Services 2 but only on one project that didn't end up coming to fruition.

I am using D6 and Services 3 on this project and I am having trouble figuring out how to login.

I have set my endpoint to 'api/user' for all user resources. That means my login url would be 'api/user/user/login', correct? Using Poster on Chrome I get a "406 Not Acceptable: Unsupported request content type application/xml" when I try to pass along POST data.

Are there any tutorials or docs out there that I am missing? Any clues on what I might be doing wrong? I am finding it extremely difficult to find much out there for Services 3.

# Answer
> 0 votes
make your endpoint 'api'

THen your login url is, 'api/user/login' POST

And also check to make sure you have allowed application/xml as a value response format at admin/structure/services/list/api/server

Although you might need to wait for this patch to be committed http://drupal.org/node/1232984

# Answer
> 0 votes
Check your Request parsing under SERVER tab. Make sure

multipart/form-data & application/x-www-form-urlencoded is checked

---
Tags: 6, services
---


# Question
Title: Drupal 7: Modifying the view page and edit form of a content type programmatically
a Drupal newbie here trying to create his first module for Drupal 7.

In my site I've created a new content type (machine name: abstract) from the site's admin's front-end. A user can add a new instance of this content type by using a form I've defined using the FAPI. In this form's submit function I do the following:

```
function form_add_abstract_submit($form, &$form_state) {

  global $user;

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

  $node->title = $form_state['values']['abstract_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid;

  // ... fill the rest of the node's fields here [...]

  if($node = node_submit($node)) {
    node_save($node);
    // Not sure about this way of defining the path to the created node
    $path = 'abstract/' . $node->nid;
    $node->path = array('alias' => $path);
    node_save($node);
    drupal_set_message(t('Abstract submitted');
  } else {
    form_set_error('description', t('ERROR'));
  }

  $form_state['redirect'] = 'index.php';
}

```

As shown above, I define the path to these nodes to be 'abstract/\[its-node-id\]'. Then, when a user visits this URL I'd like to show two tabs, one allowing the user to see the node's fields and another linking to a form to edit it. I've tried to implement it by adding the following three menu items in my hook\_menu function:

```
$items['abstract/%'] = array(
      'title callback' => 'abstract_page_title',
      'title arguments' => array(1),
      'page callback' => 'abstract_page_view',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );

  $items['abstract/%/view'] = array(
      'title' => 'View',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => -10,
  );

  $items['abstract/%/edit'] = array(
      'title' => 'Edit',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('my_module_form_abstract_edit', 1),
      'access callback' => TRUE,
      'file' => 'my_module_forms.inc',
      'type' => MENU_LOCAL_TASK,
  );

```

However, if I visit abstract/\[a-node's-id\], my abstract\_page\_view function is not being called and the default view for rendering my content type is displayed. The 'Edit' tab on this view also links to abstract/\[the-node's-id\]#overlay=node/\[the-node's-id\]/edit, not to abstract/\[the-node's-id\]/edit, as I'd like to.

What am I doing wrong? Should I programmatically define my content type instead of doing it from the admin's backend or is my problem somewhere else?

# Answer
> 2 votes
If I understand what you are trying to do, you want to customise the node add/edit page and the node view page for your 'abstract' content type.

It seems like you are trying to duplicate what drupal already does for you for no apparent reason. Your code doesn't seem to really be doing anything that drupal does not do for you already (from the code sample you provided). (As a side note, what are you actually trying to achieve?)

If so, I wouldn't be creating fully custom pages. Drupal gives you hooks so you can modify what it gives you by default.

For example, the node add/edit page (node/add/abstract & node/\[nid\]/edit) can be modified by using hook\_form\_BASE\_FORM\_ID\_alter() or hook\_form\_FORM\_ID\_alter(). While form altering these forms you can add your own custom validate and submit functions if you need to do additional submission.

For path aliases, use the pathauto module, which will allow you to set the path alias for your page to abstract/\[nid\] - although you would generally be better off doing something like abstract/\[title\] for the sake of SEO and more user-friendliness.

For the node add page you can add a path alias by going to admin/config/search/path. Then you can make it something like abstract/add instead of node/add/abstract.

Drupal fields should be able to handle pretty much any of the data you want to handle, especially with the help of modules like date, link, email, and many many more.

Now that I know you want to store some node data in an external database then this next part is of interest to you. These node hooks allow you to hook into the node CRUD system:

If you really really do need to have extra data (not so common, you can generally do what you need with fields), for example, data you custom store in a separate database table, you can use the hooks hook\_node\_view() for showing your custom data on the node view page, hook\_node\_load() to load your custom data into the node object each time it is loaded, hook\_node\_delete() to delete your custom data when a node is deleted, hook\_node\_insert() for inserting your custom data when a node is created, hook\_node\_update() for updating your custom data when a node is saved.

There are other hooks too, like revision related ones if you are using revisions and search index related ones, for adding data to search index & search results. See them here - http://api.drupal.org/api/search/7/hook\_node\_

Also, if you are adding data to nodes from your external database that aren't in drupal fields, you might also be interested in the APIs that the Entity module provides. In particular, you can define your data as properties of the entity, so they can be easily handles by modules such as rules and search api (and other modules that utilise the entity api). See http://drupal.org/node/1021466

If you really must do it that way, your hook\_menu() also has some issues: The % characters in the menu paths should really be replaced with %node - which will then call node\_load and properly validate the nid in the path. See http://drupal.org/node/224170 for more information on menu wildcard loaders.

abstract/% also should not be MENU\_CALLBACK, it should be MENU\_NORMAL\_ITEM.

Basically, you are trying to replicate the node/% node/%/view node/%/edit pages so you should try copying what the node module has in node\_menu() for those items, but just change the path. Then you can have your new paths doing what the node module would do at node/% node/%/view and node/%/edit. However you will then have issues with other modules that add node/%/something paths (if you are using any such modules). In this case those extra tabs on the node page would not be present on your pages because their paths would not match.

So unless you really really have to have abstract/%/edit, I would leave the menu alone and just use path auto to have abstract/\[nid\] or abstract/\[title\] and leave the edit pages as node/\[nid\]/edit.

An alternative solution, depending on whether or not it suits your use case better, is to not use the node system at all and create your own custom entity type. So you would have an abstract entity type, like the user, node and taxonomy term ones.

If you aren't really using any of the features that the node system provides this might be a better solution. It is relatively straight forward to do but the downside is a lot of existing contrib modules work only with nodes, and not other entity types. So those additional functionalities you might require you would also have to code yourself. So it depends on whether you have the time to do the additional custom work required or if you are better off utilising nodes, so you get compatibility out of the box.

---
Tags: 7, nodes, routes
---


title: A sub-domain for each user blog

text:
# Question
Title: A sub-domain for each user blog
Is there any module, or a way to get a user blog in a separate sub-domain, such as user1.example.com for user1, and user2.example.com for user2?

# Answer
> 2 votes
Maybe a combination of blog module and Subdomain module:

> Automatically creates subdomains and places content on them. There are 4 modes:
>
> User: e.g. "Mary" and content at http://mary.example.com
>
> Taxonomy: e.g. "Seattle" and content at http://seattle.example.com
>
> Organic Group: e.g. "MyGroup" and content at http://mygroup.example.com
>
> Content type subdomains: e.g. "News" content at http://news.example.com

# Answer
> 1 votes
Depending on your requirements, the Domain Access module might also be a good fit. It can give you user based subdomains.

---
Tags: nodes, uri
---


title: How to hide administrator under role

text:
# Question
Title: How to hide administrator under role
When an administrator (except user 1) editing a user how to hide "administrator" under role in a user edit page in D7 site? or how to prevent assign a role of administrator while editing a user?

# Answer
> 2 votes
I believe the RoleAssign module can help you with that:

> RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
>
> RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.

# Answer
> 1 votes
Use the role delegation module.

It gives new permissions to restrict the roles that are allowed to be assigned.

---
Tags: users
---


title: Node edit area alterations

text:
# Question
Title: Node edit area alterations
In my node edit area there are some hyperlinks exposed by the References Dialog module. I need to alter these links by appending some extra information to the url.

**Can anyone tell me what hook to implement which will allow me access to the hyperlinks data and modify them - or even simply altering labels?**

UPDATE:

I code which generates the link I am trying to customize is as follow:

```
function references_dialog_node_reference_add_link($element, $widget_settings, $field, $instance) {
  $add_links = array();
  foreach ($field['settings']['referenceable_types'] as $type => $active) {
    if ($active !== 0) {
      $node_type = node_type_load($type);
      if (node_access('create', $node_type->type)) {
        $add_links[] = array(
          'title' => t('Create @type', array('@type' => $node_type->name)),
          'href' => 'node/add/' . strtr($type, array('_' => '-')),
        );
      }
    }
  }
  return $add_links;
}

```

Here is an image highlighting the links which I am attempting to customize:

# Answer
> 0 votes
There was a patch recently committed to the references dialog module that allows for altering these links. See http://drupal.org/node/1416922

So if you use the latest development version of the module you can then in a custom module of your own, implement:

```
/**
 * Implements hook_references_dialog_widgets_alter().
 */
function MODULE_NAME_references_dialog_widgets_alter(&$widgets) {
  // Modify $widgets here.
  // $widgets, should be an array of links, including the one you want to alter.
}

```

---
Tags: 7, navigation
---


# Question
Title: Mention/Reply to users in comments using @ (@name)
I am looking for a feature that makes it possible to reply to comments, or mention users in a comment using the @ symbol.

So, if I was to write the following in a comment on a node:

> @Michael Jackson Cool stuff dude.

"@Michael Jackson" would turn in to a link that leads to his user page.

Also, if it is possible without to much hassle, it would be great if it only turned in to a link if the user exists, to prevent a 404 error.

Thanks.

# Answer
I think you might be looking for this module but the 7 version is still in dev.

Mentions

> The Mentions module offers Twitter like functionality, recording all references to a user's username - using the \[@username\] or \[@#uid\] filter format - from various locations, providing a centralized page to track all mentions.
> 8 votes

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


title: link field does not validate http://

text:
# Question
Title: link field does not validate http://
I have link CCK field but the field does not validate "HTTP://" like this

how I can make the validate "HTTP://" for this field

# Answer
i do it by using this model advanced\_link in drupal model, thanks all
> 0 votes

# Answer
In drupal 7, go to your content type in:

**/admin/structure/types/manage/yourcontentype/fields/**

Edit your field and check if it is validating your URL. I have attached a picture for better explanation.
> 4 votes

# Answer
I would have a look at clientside validation. Alternatively you could use hook\_form\_alter to add in your own validation by changing $form\['#validate'\] to point to your custom validator.

If you go down the programtic route and just want to check the format you could use PHP FILTER\_VALIDATE\_URL Filter function which would return true if its a url. Additionally, I would look at using CURL to verify the url actually exists.

Hope this helps.
> 3 votes

# Answer
In the D6 version at least, there is a checkbox for validating the link:

so I'd first make sure that's checked on your site before any custom coding...
> 3 votes

---
Tags: entities
---


# Question
Title: Remove or rename menu's <li> class .last
I need to remove class .last from menu's `<li>`. I browsed this nice website for a solution and find some code that removes ALL classes:

```
function THEME_menu_link(array $variables) {
  //unset all the classes
  unset($variables['element']['#attributes']['class']);

  $element = $variables['element'];

  if($variables['element']['#attributes'])

  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

And:

```
function mymod_menu_tree__menu_about_us($variables) {
  return '<ul class="side-menu">' . $variables['tree'] . '</ul>';
}

function mymod_menu_link__menu_about_us(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $class = "";
  $classes_of_this_li = $element['#attributes']['class'];
  if (in_array($classes_of_this_li, 'active-trail')) {
    $class = 'active';
  }
  $output = l($element['#title'], $element['#href']);
  return '<li class="' . $class . '">' . $output . $sub_menu . "</li>\n";
}

```

I need to remove only .last class and also somehow I need it to work only on a selected region. What I mean is that the function must apply to menus that are rendered i.e. in Sidebar region.

# Answer
You can do it like this:

```
/**
 * Theme menu links.
 */
function THEME_NAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  // This is the part that removes or changes the last class.
  if (!empty($element['#attributes']['class'])) {
    foreach ($element['#attributes']['class'] as $key => $class) {
      if ($class == 'last') {
        // Use only one of the two following lines.

        // To change the last class.
        $element['#attributes']['class'][$key] = 'new-last-class';
        // To remove the last class.
        unset($element['#attributes']['class'][$key]);
      }
    }
  }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

However, if you are referring to the primary links and secondary links as printed out by default in most themes, they do not run through that function, because they are generated by menu\_main\_menu() and menu\_secondary\_menu(), which in turn use theme\_links() to generate the links instead of theme\_menu\_link() - very annoying.

So to get to those you either need to stop using theme default theme menus and use the menu blocks provided by default by the menu module. These blocks use the theme\_menu\_link() function to generate links so will be affected by the above code.

Alternatively, you would have to override theme\_links() also, like so:

```
/**
 * Theme links.
 */
function THEME_NAME_links($variables) {
  $links = $variables['links'];
  $attributes = $variables['attributes'];
  $heading = $variables['heading'];
  global $language_url;
  $output = '';

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

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

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

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

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

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

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

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

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

  return $output;
}

```

I have added *** to the start and end of comments for the line you need to be interested in. The problem with this approach (maybe it isn't a problem for your site) is that this affects a lot of other lists of links on the site, not just the two menus in question.

It is possible to use if ($attributes\['id'\] == 'main-menu-links') and if ($attributes\['id'\] == 'secondary-menu-links')

to distinguish between the main menus however that isn't foolproof and isn't the best idea.

For example, the important part of the above theme\_links() would be:

```
if ($i == $num_links) {
  // This would skip the last class for main & secondary menus
  // but would keep it for other links lists.
  if ($attributes['id'] != 'main-menu-links' && $attributes['id'] != 'secondary-menu-links') {
    $class[] = 'last';
  }
}

```
> 0 votes

---
Tags: 7, theming
---


title: How can I get rid of this error?

text:
# Question
Title: How can I get rid of this error?
The error that I am getting is as follows

> Strict warning: Only variables should be passed by reference in include() (line 73 of /Applications/MAMP/htdocs/.../sites/all/themes/bootstrap/templates/page.tpl.php).

The code producing this error is

```
<?php
$path = drupal_get_path_alias($_GET['q']);
$block = block_load('block','2');
if ($path == 'home') {
  print render(_block_get_renderable_array(_block_render_blocks(array($block))));
}
?>

```

I don't know why this error is coming up because the code is working perfectly.

Could anyone Helo me please?

# Answer
> 4 votes
The solution for this will be to do the same thing with the code below.

```
$region = _block_get_renderable_array(_block_render_blocks(array($block)));
print render($region);

```

After changing your code make sure that you clear your cache. And try refreshing. Also make sure you have made this changes every where.

So you know what the problem is: The render() function takes a parameter by reference. In that case you must pass in a variable, not a function call, because the function call is not something that can be passed as a reference.

# Answer
> 1 votes
As a side note, you generally should not be calling functions that start with an underscore as they are intended to be private functions - not to be used from outside that module.

You should also be doing the block loading in a preprocess function, and only printing it in the page.tpl.php file.

The proper way to do what you are doing is this: In your template.php file:

```
/**
 * Implements template_preprocess_page().
 */
function bootstrap_preprocess_page(&$variables) {
  // No need to pass in the q arg, as it is the default.
  $path = drupal_get_path_alias();
  if ($path == 'home') {
    // Load the block inside the if statement so you aren't loading
    // it when you don't need it.
    $block = module_invoke('block', 'block_view', '2');
    $variables['my_block_content'] = $block['content'];
  }
}

```

then in your page.tpl.php:

```
<?php print render($my_block_content); ?>

```

If you really want it all in the page template, just do this:

```
<?php
  // No need to pass in the q arg, as it is the default.
  $path = drupal_get_path_alias();
  if ($path == 'home') {
    // Load the block inside the if statement so you aren't loading
    // it when you don't need it.
    $block = module_invoke('block', 'block_view', '2');
    print render($block['content']);
  }
?>

```

For more information on rendering blocks see http://drupal.org/node/26502

---
Tags: blocks, 7
---


title: Menu structure and URL paths

text:
# Question
Title: Menu structure and URL paths
I am using a Superfish 2 level navigation menu, and have 3 sub-items under an item. The url path for the second level item is NOT item/subitem but instead just subitem, if that makes sense.

I've got Generate automatic URL alias checked.

Is it acceptable for the subitems to not have their parent items in the url path? If not, what is the easiest way to automatically have the item appended to the subitems url path?

# Answer
Yes, it is acceptable for child menu items to not contain any of the parent item's path.
> 1 votes

---
Tags: routes, path-aliases, navigation
---


# Question
Title: Drupal 7 - Suppress output of nodes on Taxonomy Pages
Is there a way to suppress the output of nodes on taxonomy pages, without having to install a module (i.e. just in template.php)?

Nodes tagged with a taxonomy term appear on the "Taxonomy Index page" (e.g. yoursite.com/taxonomy/term/\[id\]).

New in Drupal 7, Taxonomy Index pages can have fields attached to them. However, if you try to over ride the taxonomy page with a View (for example, to control how the nodes are displayed), the fields on the Taxonomy Index pages will not appear.

I have therefore placed my Taxonomy View as block on the Taxonomy Index page. That way, I can control how the nodes appear and still have the Taxonomy Index page fields.

Because of this, the taxonomy page is still outputting its nodes. I can hide them by setting the teaser of the nodes to hidden, but it still loads up the nodes (and therefore any CSS/Jquery attached to nodes even though the nodes aren't being displayed). How can I suppress the nodes from appearing, ideally from inside of template.php?

# Answer
> 5 votes
I know, that wanted a no-module solution, but in Drupal 7, there is a module that does exactly what you need: Disable Term Node Listings

It lets you choose per Vocabulary, if you want to disable the output of the term listing.

# Answer
> 8 votes
Solution from http://www.wardontheweb.com/remove-node-lists-from-taxonomy-pages-in-drupal-7/ works for me well:

```
function THEMENAME_preprocess_page(&$vars){
   if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))){
     unset($vars['page']['content']['system_main']['nodes']);
     unset($vars['page']['content']['system_main']['pager']);
     unset($vars['page']['content']['system_main']['no_content']);
   }
}

```

Note: you should reset your site's cache.

# Answer
> 2 votes
You have to remove the nodes from the $page variable.

In **template.php** you can do it like this:

```
function MY_THEME_preprocess_page(&$variables) {
  if(arg(0) == "taxonomy" && arg(1) == "term") {
    $variables['page']['content']['system_main']['nodes'] = null;
  }
}

```

In your **page.tpl.php** use this code:

```
if(arg(0) == "taxonomy" && arg(1) == "term"){
  $page['content']['system_main']['nodes'] = null;
}

```

This removes the nodes from **all vocabularies and terms**. If you want to remove them only on certain terms or all terms from a vocabulary use `arg(2)` which contains the `tid` to load the term and then update the if statement.

# Answer
> 0 votes
You can do practically anything in template.php, but that's not recommended. The point of using a CMS, is that you separate data, behavior and appearance. The template.php file is part of the theming layer, and you should use it to adjust the visual style of your site.

If you want to adjust the behavior of a site (in this case: control which items are shown in a certain list) you need to change the behavior, so you install and configure modules. If you want to build custom lists of content, the Views module is exactly what you need.

In your case (if I understand correctly) you want the taxonomy term's fields to be displayed above the list of nodes tagged with that term. You can re-create that in your view by creating a views block that takes the term ID from the URL and displays the info you need.

# Answer
> 0 votes
I was using CSS to hide the taxonomy stuff but setting their display to custom and blanking that seems like a better option.

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


# Question
Title: Getting front page blocks to show on redirected front page
Here's what I did

* I have working content pages I like
* I want to have the latest of these display as the front page of my site
* When that node displays as the front page, I'd like a few additional blocks to display. This was easy to solve by configuring the blocks to only show on \<front\>
* I built a view to show the latest page, creating a "node page" display, with "single node" as the style (from Top Node module). I sort by Node: post date. I give it the path "latest"
* I set "latest" as the front page of my site.
* The front page now goes to the latest node, but the front page only blocks do not display. When I check the source, the body tag does have class "front", but the blocks aren't showing. I tried setting the block configuration to show on page "latest", but that didn't work either.

How do I get the blocks to show? I don't want to build an all new front page using views because I have some programatic things in my template.

# Answer
My problem appeared to be with the Top Node module. Apparently, the views display it introduces redirects in a way that causes the \<front\> tag not to work as it should. The answer is actually quite simple, and honestly makes the Top Node module seem a bit redundant. Although it's not intuitive to me, under "Row Style" on views, you can specify full node content, which, as the name implies, renders node results as they would appear if you typed in the URL directly. I simply made a view that returned one result, Row Style set to full node, and then created a page display at the URL "latest". Problem solved.
> 0 votes

---
Tags: 6, blocks
---


# Question
Title: Why is css not working as expected with Omega
Making site with left side menu items built on Omega responsive grid. Setting up the global.css to theme out some page elements, like this menu.

Problem: Used css not used in the browser. Instead system.menus.css is used. Question: Why.

CSS: for menu

```
/*============== Menu Items ====================*/
.menu ul
{
    padding:8px;
    margin:0px;
    font-family:Arial, Helvetica, sans-serif;
    font-size:1em;
    color:#FFF;
    list-style:none;
    text-indent:15px;
    background:#0000a2;
}
.menu ul li
{
    background:#0000a2;
    line-height:28px;
    border-bottom:1px solid #000;
}
.menu ul li a
{
    text-decoration:none;
    color:#FFF;
    display:block;
}
.menu ul li a:hover
{
    background:#3ea5ea;
}
.menu ul li#active
{
    background:#3ea5ea;
}

====================================

Chrome inspector data:
media="all"
ul.menu {
border: none;
list-style: none;
text-align: left;
}
dea.harland.tkmedia="all"
.menu {
margin: 0;
padding: 0;
}
dea.harland.tkmedia="all"
p, dl, hr, h1, h2, h3, h4, h5, h6, ol, ul, pre, table, address, fieldset {
margin-bottom: 20px;
}
dea.harland.tkmedia="all"
ul {
list-style: disc;
}
user agent stylesheetul, menu, dir {
display: block;
list-style-type: disc;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
-webkit-padding-start: 40px;
}

```

Inherited from `body.html.front.logged-in.page-node.toolbar.toolbar-drawer.omega-mediaqueries-processed.omega-equalheights-processed.alpha-debug-processed.responsive-layout-wide`

```
dea.harland.tkmedia="all"
body {
font: 0.75em/1.3em Verdana, Helvetica, Arial, sans-serif;
}
dea.harland.tkmedia="all"
body {
font: 13px/1.5 Verdana, Helvetica, Arial, sans-serif;
}

```

# Answer
I think your CSS is incorrect. You wrote:

```
.menu ul li {/*stuff*/}

```

when I think it needs to be:

```
ul.menu li {/*stuff*/}

```

Is this correct?
> 2 votes

---
Tags: theming
---


# Question
Title: How to list all fields of a content type with views?
I would like to create a product comparison view. Each product has lots of features which all need to appear in the comparison view. Each feature is a separate field in the “product” content type.

Instead of *manually* adding all fields of the “product” content type to my view, I’d like to have *all fields added automatically* to the view – for example when adding a new field to the “product” content type. Is this possible?

Bonus question: can I add all fields to the view by default and later exclude only a few of them?

---

**Edit:** Further Notes

I’d like to create a comparison table where corresponding features appear in the same row with a single row/column label for the feature. Many features are optional, though. Therefore I need the feature fields of the “product” content type to be available as separate fields in the view – so that I can properly align them in the table.

# Answer
According to me the best way to configure a view is to use display modes ("Show: content" and select the display mode). So that when I add a field to a content type I just have to configure the "Manage Display" sections (1 per view mode) of the content type.

Note that sometimes I need extra fields to render, to use as token for other settings (rewrite a field, header/footer text, more link,...) or to make grouping. To achieve this I switch the "Show" option to fields and add a "Content: Rendered Node" field (that comes with Entity API module). Then the "Show complete entity" display option of this field allows you to choose a display mode (Full content, teaser, list item or any other display mode) and render the nodes.
> 1 votes

---
Tags: views
---


title: I can't run "drush core-cli"

text:
# Question
Title: I can't run "drush core-cli"
I have installed drush on crunchbang linux and while most of the drush commands are working, I can't get core-cli to work. Running `drush @dev core-cli` returns this error message.

> The drush command 'core-cli' could not be found. Run\[error\] `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.

I initially tried installing Drush via APT; when core-cli didn't work, I tried getting it via PEAR, but it's doing the same thing. With the version I got from pear(5.8) `drush self-update` works, when it didn't with the APT version, an earlier release.

I've made sure that my user has full rights to the /usr/share/php/drush folder.

# Answer
> 3 votes
`drush core-cli` has been removed in Drush 5.

> Drush 5 supports bash completion which is much more native and superior to the old core-cli command, which has been removed.

For more information, see Core-cli command removed in favor of Bash completion.

---
Tags: drush
---