# Question
Title: How to remove the "Add new Comment" link from book pages
I have created two books, and both of them have child pages (which are also book pages). I have activated the option of commenting, in which the comment box is shown in the same book page.

All works fine when there is no comment on a particular page, but even when any user posts at least one comment on the page, the "Add New Comment" button appears in the links area below *page-links* and above the *comment-wrapper*; the comment box is shown below. I just wanted to ask how to remove this link because it is messing with the other options in the links area (e.g. printer friendly page, PDF).

I did create a *hook* using the following code.

```
<?php
  /**
  * Implementation of hook_link_alter
  * Remove add comment link from a content type
  * MODULENAME = remove_comment
  **/
  function MODULENAME_link_alter(&$links, $node){
    if($node->type == 'book'){
      unset($links['comment_add']);
    }
  }
?>

```

I have set the permissions for the users to post comments and have kept the comment box open by default. So, it makes no sense in having the *Add new comment* link.

And in *admin/structure/types/manage/book*, the settings are as shown below.

# Answer
> 5 votes
I did get the solution and was able to remove the "Add new comment" link, from the *links* area. I just went to *comment* module and commented the following lines of code on line #675.

```
// Show the "post comment" link if the form is on another page, or
// if there are existing comments that the link will skip past.
if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE || (!empty($node->comment_count) && user_access('access comments'))) {
  $links['comment-add'] = array(
    'title' => t('Add new comment'),
    'attributes' => array('title' => t('Share your thoughts and opinions related to this posting.')),
    'href' => "node/$node->nid",
    'fragment' => 'comment-form',
  );
  if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) {
    $links['comment-add']['href'] = "comment/reply/$node->nid";
  }
}

```

I know it is not recommended to modify the core. I have implemented *a hook* to remove the link.

**Solution found**
The following *hook* in my custom module works for me :)

```
function MODULENAME_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    unset($build['links']['comment']['#links']['comment-add']);
  }
}

```

# Answer
> 4 votes
You can edit the comment settings per content type or node to close comments which will remove the add new comment link.

Or alternatively you could do this programatically with a snippit of code added to your template.php

```
function THEMENAME_preprocess_node(&$variables) {
//find the comment link
print_r($variables);

  if ($variables['node']->nid = #) {
    unset($variables[*find the comment link*]);
  }
}

```

Replace the # with the book page nid you want to effect, the THEMENAME with your themes name and also *find the comment link* with the array key which contains the add comment link

# Answer
> 2 votes
You could do it using hook\_link\_alter, an example below. This needs placed into a custom module and not template.php.

```
<?php
/**
* Implementation of hook_link_alter
* Remove add comment link from a content type
**/
function MODULENAME_link_alter(&$links, $node){
  if($node->type == 'YOURNODETYPE'){
    unset($links['comment_add']);
  }
}
?>

```

# Answer
> 1 votes
```
// $(this).html('<a href="' + action + '" id="comment-form-title">' + title + '</a>');

```

Comment the above line in the ajax\_comments.js file which is present in AJAX Comments module.

---
Tags: 7, comments
---


# Question
Title: Drupal 7 Core Module Function for node_save?
In Drupal 7, i want to put a additional code when the `Save` button is `Clicked` (Saving) in "a content" form (New or Edit).

I don't want to know the hook (because i don't want to make an obvious `Custom Module`). Because i don't want to let other users know the operation by having a obvious Custom Module which will be listing inside the Module Panel. So i want to make a `Silent Customization` inside the `Existing Drupal Core Module (correspondence Function)`.

Thats why I just want to know `the Function in the Core Modules` which finally process the Node Save task.

* Can anyone please describe which `Function (in Core Modules)` is finally processing the Drupal Node Save? (Save\` finally may be for both New Item Insert or existing Item Edit.)

# Answer
> 3 votes
**DO NOT HACK CORE**

Now that's out of the way, let's continue.

The way I see it, you have a couple of options:

1) Use Rules.

> The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

Although this will allow people to see that there is code being run.

2) Create a custom module, but in your info file make use of the hidden property:

> As of version 7.x, modules and themes may specify that they should not be visible on the modules page by adding hidden = TRUE. This is commonly used with testing modules used with SimpleTest where end-users should never enable the testing modules.

---
Tags: 7, nodes
---


title: Change Image cut

text:
# Question
Title: Change Image cut
i have this problem: i need a image (the image has its own image-field) inside a node with a specific size and cut. the size is always fixed for example at 300x300px. now i want the user choose the cut of the image, so he can drag the image inside the boundary box like facebook does with its thumbnail profile pictures. this user choosen cut should be visible as thumbnail on the site.

i know there is such a module which can create a thumbnail for including into text but i dont know how its called and if its works with imagecache...

# Answer
> 2 votes
Something like Image javascript crop:

> This module makes an Imagecache 2 (D6) or Styles (D7) 'javascript crop' toolbox action available for use with several modules...

or Imagefield Crop

> imagefield\_crop provides a widget for cropping an image after upload.

---
Tags: 7, media
---


title: How do I install the Profile2 module?

text:
# Question
Title: How do I install the Profile2 module?
I am new to Drupal and I have recently installed Drupal 7.15 and downloaded profile2 but I don't know how to install profile2 to Drupal. I came across this link but I can't find any *profile types* in my Drupal structure. Below is the screen shot of my Drupal struture:

# Answer
> 2 votes
1. Inside every Drupal module there is file called README, you must read that to findout how it's should be installed and used.
2. Always clear Drupal's cache just in case : admin/config/development/performance
3. According to README you much visit this link admin/structure/profiles top manage profiles

---
Tags: users
---


# Question
Title: Dynamically hiding / showing Field API fields in Drupal 7
I've created an entity with an 'add new' form. The entity itself has a limited number of actual variables. I've added most of the extra data I need using custom Fields (i.e. the Field API).

What I need to do at this stage is be able to dynamically hide one field based on the value of another. i.e. if a drop-down field has it's value set to No, another field should be hidden, otherwise it should be shown.

From what I can see, it is somewhat easy to add this functionality to fields created using the Form API (i.e. via the AJAX property), however is there any way to achieve it using attached fields? I have no issues using custom Javascript if that is what is required to solve this.

# Answer
jQuery works well for this:

```
(function($) {
  $(document).ready(function() {
    $('#select1').change(function() {
      switch ($(this).val()) {
        case '1':
          $('#field2').hide();
          break;
        default:
          $('#field2').show();
          break;
      }
    });
  });
}) (jQuery);

```
> 5 votes

# Answer
In Drupal 7, Drupal 8 you can use $form `#states` instead of custom jQuery script. Example:

```
  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    // This #states rule says that this checkboxes array will be visible only
    // when $form['student_type'] is set to t('High School').
    // It uses the jQuery selector :input[name=student_type] to choose the
    // element which triggers the behavior, and then defines the "High School"
    // value as the one that triggers visibility.
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

```

Here is example if you want to use `#states` for multiple values condition:

```
 $form['student_type'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'textfield',
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type[high_school]"]' => array('checked' => TRUE),
        ':input[name="student_type[undergraduate]"]' => array('checked' => TRUE),
        ':input[name="student_type[graduate]"]' => array('checked' => FALSE),
      ),
    ),
  );

```

See the `form_example/form_example_states.inc` from examples module for more details and examples.
> 19 votes

# Answer
You should try Conditional Fields, I think this module is a must-have for this task. You can set dependencies between fields on a user-friendly admin interface. For example, you can set `A` field to be only *visible* if `B` field has value "*1234*", or you can set `C` textfield to be *visible* only when `D` field is checked, or set `E` field to *invisible* if `F` is *focused* etc.

On the upload form, these dependencies will be set client-side, on node display, these dependencies will be set on the server-side.

You can set these dependencies at `admin/structure/types/manage/[YOURCONTENTTYPESMACHINENAME]/dependencies`.

<sub>(Source of the image: the project's page)</sub>
> 4 votes

---
Tags: entities
---


title: Category Coupon

text:
# Question
Title: Category Coupon
I would like to setup a flexible system using the coupon module. I would like to add a term reference field to the coupon entity that refers to a product category/taxonomy.

Now my client can create a coupon and designate "10% off all Baby Shoes" where Baby Shoes is a taxonomy term set on each product display that contains baby shoe SKUs.

On coupon redemption, only products whose product displays are in the Baby Shoes category receive a discount.

Has anyone set something like this up before and would care to share the detail on how they did i

# Answer
> 1 votes
Here is a similar module that allows you to add products directly to the coupon via an entity reference field : Commerce Coupon by product reference.

Unfortunately Coupon module does not support this by default, however you can either wait for the next version which is suppose to be much more flexible, or follow the instructions in README.txt to install this sandbox module, which is like coupon by product reference, but uses terms.

---
Tags: commerce
---


# Question
Title: Addressing objects and arrays nested in an object?
I'm working a .tpl file for my view that is named `views-view-fields--viewname--block.tpl.php`. With the Devel module, I did a `dsm($field);` One of the field objects that are returned in the Krumo goes as follows:

```
fieldObject
    --handler(object)
    ----last_tokens(array)
    ------[title](string, 15characters)

```

I figured I should address this as

```
    <?php foreach ($fields as $id => $field): ?>
  <?php dsm($field); ?>
    <?php if ($field->class == 'field-evenement-performer'){
        print $field->handler->last_tokens['title'];    }

?>

```

but this returns `Notice: Undefined index: title in include() (line 34 of /....../sites/all/themes/ibrain092012/templates/views-view-fields--presentatie-kraakhuis--block.tpl.php`

How can this be while title does have a value in the Krumo?

# Answer
This is the correct way to use it (see the usage of the square brackets in the string):

```
print $field->handler->last_tokens['[title]'];

```
> 0 votes

---
Tags: 7, views, entities, theming
---


# Question
Title: D7: HTML email sent shows markup, how to fix?
Im using Linode VPS but mails are routed via SMTP authentication to Google. Email is sending correctly and I'm using mail system and html mail with smtp authentication.

When I send test email as html to test mailbox, it shows markup and wont render to html. How can I fix this?

HTML Mail \> Send Test

Creating HTML mail and sending it with SmtpMailSystem sending class. Output when viewed at gmail receiving it:

```
<p>This is a test letter.</p>
<p>Lets add some <u><strong>html</strong></u></p>

```

So all markup is visible. What I'm missing?

# Answer
Fixed.

Edited php.ini: /etc/php5/apache2 # nano php.ini

--\>

; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). sendmail\_path = /usr/sbin/sendmail -i -t

Set mailsystem to htmlmail, voila.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: how to hide the main menu which is not listed in a block
I downloaded a theme which automatically puts my main menu in the header region. However, when I look at my blocks you can't edit that region.

I would like to BLOCK ALL unauthenticated users from seeing the main menu. How would i do this? thanks!

# Answer
It seems that you want to lock down specific areas of the site with permissions that are not readily available on the Permissions page. I would address that issue in the following way.

I would update the theme to make the region editable and make it so that the menu was not part of the theme by default.

Next I would install the Context module so that I could display specific blocks, in specific regions, when specific conditions are met.

Finally I would create a Context with the settings:

**Conditions**

* "Sitewide: Always active"
* "User Roles": "Authenticated User"

**Actions**

* "Block": Main Menu
> 2 votes

# Answer
It is probably a 'Feature' of the theme. The control for that can be found under Appearance -\> Settings -\> 'Theme Name' -\> Find the 'Toggle Display' section and uncheck 'Main menu'.

Then you re-add the menu yourself under 'Structure' -\> 'Blocks'. Drag it to the region you want it in. Then click 'configure' and go to 'Roles' where you can choose which roles to display the block for. (Leave anonymous user unchecked to hide this block from unauthenticated users)
> 0 votes

---
Tags: routes
---


# Question
Title: Why does drush say "command not found" when I try to execute remote commands?
When I use a drush command to do something on a remote machine, I get the following message:

> bash: drush: command not found

What's the problem?

# Answer
This message is from the remote machine complaining that it didn't understand where to find the `drush` executable, *not* Drush complaining that it can't find the (sub)command you may be trying to give it, even though the punctuation suggests the latter. (If `bash:` means Bash is passing you a message, then `drush:` should mean the same thing--if there's any consistency. But actually it is intended to mean `drush:` is the subject of the message, not the source of the message passed through `bash:` to you. It would be clearer if the second `:` were removed.)

Drush logs into your remote machine over ssh, but it's not a normal interactive login, so it doesn't source the .bash\_profile. It does, however, source the .bashrc file.

Add the drush path (not including drush itself, just including the directory containing drush) to the PATH variable in your remote .bashrc and all should be well. For instance, that may look like this:

```
PATH=$PATH:/usr/local/zend/bin

```
> 16 votes

---
Tags: drush
---


# Question
Title: Drupal 7 Rules : How to get Node Object (from Custom PHP) after a node event is triggered?
In Drupal 7, i am setting up a rule. That rule is applying to trigger on the `Node Save` event.

* After the `node is saved` \[***Condition***\] and the `rule is properly triggered`, then how can i get that saved `Node Object ($node)` from the `Execute Custom PHP Code` \[***Action***\]?

Because i put `var_dump($node)` (*in the Custom PHP Code Box*) but it doesn't work.

# Answer
you can use `watchdog("<pre>".print_r($node,true)."</pre>",'debug');`then see the log in admin/reports/dblog also you can define your own action use `hook_rules_condition_info()`. This link may help.
> 1 votes

---
Tags: nodes, rules, actions
---


# Question
Title: Is it possible to create a references from text?
I'll explain problem with an example:

We have:

1. Text about apples
2. List of types of apples

Problem:

1. User inputs text about apples.
2. User selects text that describes certain type of apple, and then click 'magic button'
3. 'Magic button' creates a small window with input field for type of apple.
4. User enters type of apple, drupal creates that type of apple in list of types of apples.

Details:

1. Apples are described in text.
2. Types of apples will not be a plain text(fieds in content type called 'Apple Types')

Is this even feasible in drupal?

Can you point me in right direction of search? What kind of modules(combination of modules) would help me?

# Answer
> 1 votes
It should be simple and straight forward as far as i understand. Below steps should solve the problem. You can solve it using Drupal Core itself and taxonomy module that comes with core.

* Create a Content Type called "About Apples".
* Add a text area field called "Apple Details".
* Create a Vocabulary called "Apple Types"
* Add a field called "apple type" , select field type as "term reference" and widget types as "Auto Complete term widget (Tagging)"

That's it ! You just created a content type called About apples which gives you a form to add Apple Details & Auto Complete Category widget which stores new terms to Apple Types vocabulary and shows autocomplete results when user tries to add categories.

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


# Question
Title: Adding/ Editing list of people with photos
I've created a content type called 'Cast'. Authorized users need to have ability to create a different list of cast members, add/edit their info, upload photo. Essentially, it's a team roster problem.

I'm having hard time figuring out how to solve this problem? What module is most suitable for this purpose?

# Answer
You can do it using Drupal Core itself with out using any module. Just follow below steps to solve the problem.

* Login as Super Admin
* Go to admin/people/permissions/roles
* Add a new role called "Cast Manager"
* Give Edit any and Create new "Cast" Content Type permission to "Cast Manager" role in admin/people/permissions/roles

That's it ! Now, users who have "Cast Manager" role can edit any cast content and manage them !
> 2 votes

---
Tags: users, nodes
---


# Question
Title: Custom module error, does'nt show on the page
I am new to drupal, so basically i have made a simple registration form. The problem is when i go to the registration form it shows a blank page .

i have made 3 files by the name of my custom module -registerme i.e.-

1.registerme.info

```
name = Register Me
description = A custom registration form
package = Drupal 7 Development
core = 7.x
files[] = registerme.module

```

2.registerme.module

```
<?php

function registerme_menu()
{
$items['registerme/newform'] = array(
  'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => 'registerme_newform',
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
 );
return $items;
}

```

3.And finally i have registerme.newform.inc

```
<?php
function registerme_newform(&$form_state)
{
$form = array();
$form['account details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account Details')
);
$form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name')
    );
$form['account details']['last name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name')
    );
$form['account details']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name')
    );

$form['account details']['pass'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 15,
    '#required' => TRUE,
    );
$form['account details']['pass'] = array(
    '#type' => 'password_confirm',
    '#description' => t('Enter the same password'),
    '#size' => 15,
    );
$form['home'] = array(
    '#type' => 'fieldset',
    '#title' => 'Home Address',
);
$form['home']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);
 $form['home']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);
 $form['work'] = array(
    '#type' => 'fieldset',
    '#title' => 'Work Address',
);
$form['work']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);
 $form['work']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);
 $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Register Me'),
 );
 return $form;
}
function registerme_newform_submit(&$form, &$form_state)
{
dsm($form_state);
}
function registerme_newform_validate(&$form, &$form_state)
{
// Some validation to be done on fields.
}

```

where i am doing wrong getting errors like

```
Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of
    C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: array_merge() [function.array-merge]: Argument #1 is not an array in
    menu_get_item() (line 479 of
    C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: call_user_func_array() expects parameter 2 to be array, null given in
    menu_execute_active_handler() (line 516 of
     C:\webserver\Apache\htdocs\Starter\includes\menu.inc).
Warning: Invalid argument supplied for foreach() in menu_unserialize() (line 400 of
      C:\webserver\Apache\htdocs\Starter\includes\menu.inc).

```

The form dislpays a blank page when i click on the menu listing Register Me and the url is localhost/Starter/?q=registerme/newform

# Answer
> 5 votes
Error in hook\_menu implementation ! See right code below.

```
function registerme_menu() {
  $items['registerme/newform'] = array(
    'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('registerme_newform'), // Should be array !
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
  );
  return $items;
}

function registerme_newform($form, &$form_state) {

}

function registerme_newform_submit($form, &$form_state)
{
  dsm($form_state);
}
function registerme_newform_validate($form, &$form_state)
{
// Some validation to be done on fields.
}

```

Clear menu cache before checking !

---
Tags: 7, forms
---


# Question
Title: Views theming: How to grab the contextual filter?
My setup is really simple. I have a taxonomy view that takes two contextual filters:

* Has taxonomy term ID (with depth)
* Has taxonomy term ID depth modifier

Due to a new request I need to be able to change the footer of the view based on the contextual filter. Since the contextual filter isn't inside the \[fields\] array of the view how can I access its value in my template file?

# Answer
You can achieve this functionality in views itself

* In footer add a global text area
* Select PHP code in the text format select box
* Enter the following code

```
$view = views_get_current_view();
/* $view->args will contain all the argument values in the order */

```

However make sure to include php opening and closing tags and read this one if you have multiple views in same page.
> 3 votes

---
Tags: views, theming
---


# Question
Title: drupal_goto ignored in custom form submit handler
I'm working on a site at the moment where some nodes are hidden behind a login. You can see a list of them, but to view them you need to sign in.

The sign in is done by showing the user login block in a lightbox.

Now the problem I'm having is the submit handler for the form isn't working properly. In my template.php file, it looks like this:

```
function fisita_redirect_after_login(&$form, &$form_state) {
   drupal_set_message($form['hidden_paper_url']['#value']);
   drupal_goto("http://www.google.com");
   //$form['#redirect'] = $form['hidden_paper_url']['#value'];
   //$form_state['#redirect'] = $form['hidden_paper_url']['#value'];
}

```

The Drupal set message, works fine, and it is outputting what I want (the URL we're trying to redirect to), but any attempt at changing the page isn't running. Either redirect or drupal\_goto.

Does anyone have any clues?

Thanks

# Answer
I had a problem like this and I used this as a workaround to get the page to redirect:

```
$url = url("node/$nid");
header("Location:$url");
drupal_set_message(t('Message to be displayed in the next page'));
drupal_exit();

```
> 4 votes

# Answer
I think it's `redirect` in `$form_state` not `#redirect`:

`$form_state['redirect'] = 'path/to/page';`
> 1 votes

# Answer
Dave's answer works, but it just felt wrong, like wasn't **"the Drupal way"**...

```
function mymodule_user_login(&$edit, $account) {
    $GLOBALS['reasons_to_h8_drupal']='this';
}
function mymodule_drupal_goto_alter(&$path, &$options, &$http_response_code){
    if (@$GLOBALS['reasons_to_h8_drupal']=='this'){
        $path = '/first-page-after-login';
    }
}

```
> 1 votes

# Answer
1.Are you sure "fisita\_redirect\_after\_login" is working?

2.I had met a similar problem like this, change form redirect or `druapl_goto` in form\_submit not work, it maybe this function is not last change form function, because `form['#submit']` is an array.
> 0 votes

# Answer
Try this Login Destination

> The Login Destination module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x). The destination can be an internal page or an external URL. It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations. It is also possible to keep users on the currently visited page after logging in or out.
> 0 votes

---
Tags: forms, users, redirection
---


# Question
Title: Show facebook friends activities from my site
I have connected Facebook on my Drupal site. My requirements are as follows.

Suppose user X log in using Facebook. He does different sorts of activities like creates an order, writes a review, likes a content etc.

When another user Y logs in to my site through fbconnect, I have to show him his friends' activities on my site. For example, in this case if X and Y are friends in Facebook, Y needs to see all of X's activities in my site.

How can I achieve this feature? I'm using Drupal 6.

# Answer
I used Drupal for Facebook module, it provides a views filter 'Friend of current user'. For showing various activities, 'Activity' module used. Then with help of view the friends activities filtered.
> 0 votes

---
Tags: 6, social-network
---


# Question
Title: How do I add conditional shipping cost to an order?
I am building an e-commerce site. When a shippable item is added to the cart I have to add some fixed shipping cost to the order which I am able to do with flat rate. But I have to add an option "Residential Delivery Fee" while showing shipping cost on checkout page. If user select this option during checkout then I have to add another shipping cost to the order.

I am unable to figure out that how to add this conditional shipping cost.

# Answer
> 1 votes
Here the idea,

1. Using `hook_checkout_pane()` include your option *Residential Delivery Fee* as checkbox
2. Then while saving order check if user selected this option. Use `hook_order`
3. If user chose this option, you can add your shipping charge as line item with the function `uc_order_line_item_add()`.

foreg:

```
function hook_order(){
switch ($op) {
.....................
case 'save':
if($arg1->residential){
//if the checkbox was selected, we add the line item to the order. the following function  will add 100 to order total as shipping charge
uc_order_line_item_add
    (
      $arg1->order_id,
      'shipping',
      t('Residential Delivery Fee'),
      100,
      NULL,
      array ()
    );

 }
}

```

---
Tags: 6, ubercart
---


title: Create a list like draggable menu

text:
# Question
Title: Create a list like draggable menu
I am using Drupal 7. I would like to create a list of items in which all items can be arranged using Drag 'n' Drop. Just like Menu system in Drupal.

I found drupal\_add\_tabledrag() but it seems it is used in table display/output. I want to create a simple list with rows and it should be arranged, just like menu in Drupal7.

Though there is DragableView module, but I want that every logged in users can create a list and they can manage their own list.

# Answer
> 1 votes
Do you know Node Queue? It could be useful for you:

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose

# Answer
> 1 votes
Drupal 7 comes with jquery UI library. You can use them to achieve above functionality with small snipped of jquery code.

Check droppable and draggable documentations. This will surely help you.

---
Tags: 7
---


# Question
Title: How to display a node in overlay popup effect?
I have a content type 'students' with fields name, description and a photo. I have created a view(Block) to display only the images of the students. When the teacher/user clicks the photo of the student, It must show up the name, description and the photo of the student in a overlay/lightbox effect.

I have tried using Lightbox2 and colorbox node module to achieve as per my needs, But needed up in failure. Any help is widely appreciated.

Thanks.

# Answer
> 7 votes
Let me answer my own question. Based on j2r's comments and http://drupal.org/node/1378438 question from this node I was able to solve my issue.

Create href as node/nid/lightbox and rel as lightframe. This will result in displaying the whole page in the lightbox. To avoid this U need to create a page--contenttype.tpl.php (In my case) http://www.digett.com/blog/01/11/2012/overriding-page-templates-content-type-drupal-7 and then remove the header, footer and other unwanted regions in the page.

Once this is done I am sure u will get as what I got.

# Answer
> 0 votes
You can do it using Ctools module. You need module development skills to achieve above functionality. You need to create a new ctools menu path, and pass the nid to that menu callback to display related details.

Check it out the ctools\_ajax\_sample module inside ctools module for implementation of overlay popup.

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


title: My first custom module

text:
# Question
Title: My first custom module
I found some code on the Drupal forum that solves a problem I have. Several users report the code works for them so I suppose I did not exactly get how to create a custom module. I followed the following steps:

Create a folder called `i18nblocktran` in sites/all/module and added two files:

**i18nblocktran.info**

```
; $Id$

name = Wysiwyg taxonomy translation
description = Displays the wysiwyg editor in the taxonomy term translation interface
package = Nathan
core = 7.x
files[] = i18nblocktran.module

```

and **i18nblocktran.module**

```
<?php
function i18nblocktran_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'i18n_string_translate_page_form'){
    foreach($form['strings'] as $name => $field){
      if(preg_match('/blocks:block:[0-9]+:body/i',$name)){
        // Change textarea to text_format
        $form['strings'][$name]['#type'] = 'text_format';
        $form['strings'][$name]['#description'] = '<br/>';
      }
    }
    $form['#submit'] = array_merge(array('i18nblocktran_string_translate_page_form_submit'), $form['#submit']);
  }
}

function i18nblocktran_string_translate_page_form_submit($form, &$form_state) {
  // Remove wysiwyg format because i18n cant handle it
  foreach($form_state['values']['strings'] AS $name => $field) {
    if(preg_match('/blocks:block:[0-9]+:body/i',$name)){
      unset($form_state['values']['strings'][$name]['format']);
    }
  }
}
?>

```

Then I activated the module in the admin but nothing happened. What did I miss ?

# Answer
You're adding a submit handler called `mymodule_string_translate_page_form_submit` instead of `i18nblocktran_string_translate_page_form_submit` to the form. After that, as NenadP suggested, you can put a `dpm()` at various places in the code to check if execution ever reaches there. Is the form alter being run? Is the preg\_match matching? Is the submit handler being called? Is that preg\_match matching?
> 0 votes

# Answer
Change line 4 in your .module file

```
foreach($form['strings'] as $name => $field){

```

with this

```
foreach($form['strings']['all'] as $name => $field){

```

It should do the job
> 3 votes

# Answer
```
function i18nblocktran_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'i18n_string_translate_page_form'){
    foreach($form['strings']['all'] as $name => $field){
          if(preg_match('/blocks:block:[0-9]+:body/i',$name)){
              $form['strings']['all'][$name]['#type'] = 'text_format';
              $form['strings']['all'][$name]['#description'] = '<br/>';
          }
      }
      $form['#submit'] = array_merge(array('i18nblocktran_string_translate_page_form_submit'), $form['#submit']);
  }
}

```

You have missed the \['all'\] in the foreach statement as well as in the foreach loop.
> 1 votes

---
Tags: 7, forms
---


title: Uploading custom files, using CKFinder

text:
# Question
Title: Uploading custom files, using CKFinder
I installed CKFinder & CKEditor. They work well, and I uploaded the images. But I must give users the ability to upload pdf-s. When I try to do it through the image button uploading form, it says: "Invalid file extension.".

In /ckfinder/config.php I found this code:

```
$config['ResourceType'][] = Array(
        'name' => 'Files',              // Single quotes not allowed
        'url' => $baseUrl . 'files',
        'directory' => $baseDir . 'files',
        'maxSize' => 0,
        'allowedExtensions' => '7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pptx,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,zip',
        'deniedExtensions' => '');

```

I created the files dir under $baseDir, but it still doesn't work. What to do?

# Answer
> 1 votes
To upload a PDF or another arbitrary file, go through the generic Link dialog:

Then use the upload form:

---
Tags: wysiwyg
---


# Question
Title: Commerce Kickstart demo: How do I change the region for the blocks Main Menu and Secondary Menu?
In the Commerce Kickstart demo the blocks Main Menu and Secondary Menu are assigned to the Menu region. **You can see in the image:**

But I go to /admin/structure/block these blocks are Disabled. I mean they are not assigne to the menu region

Is this done programmatically? I need to move the blocks to other region. How can I do it?

# Answer
Menus are printed in the **region--menu.tpl.php** @ profiles/commerce\_kickstart/themes/commerce\_kickstart\_theme/templates .

You can see the settings for the same in the link admin/appearance/settings/commerce\_kickstart\_theme

If you would like to change the positions of menus, then disable the Main Menu & Secondary menu in above link settings as shown in screenshot and enable the blocks using Blocks page.
> 6 votes

---
Tags: blocks, theming, commerce
---


title: External site authentication

text:
# Question
Title: External site authentication
I apologize if this has been asked many times before, but I'm wondering if anyone has a link to a good tutorial on implementing a working remote authentication system in Drupal 7. I'm new to Drupal.

I've found various examples online, but the system for doing this seems to have changed substantially between Drupal 5 to 6 to 7.

I have a working system that will allow me to authenticate a user remotely and adds the user to my drupal installation. However now I cant log in any Drupal only (eg the admin) as I get an error saying that the username is unknown since the code is looking for my admin username in the external system.

I get an unrecognised username error. The code is being executed for both an external and an internal user.

I know it's something simple.

# Answer
> 4 votes
The OpenID core module is a good example of a module that authenticates users using an external site (which is a OpenID provider).

The most relevant code is contained in openid\_form\_user\_login\_block\_alter(), which alters the login block to allow users to log in using OpenID, openid\_login\_validate(), which is the validation handler for the login form, and openid\_user\_insert(), which calls user\_set\_authmaps(), the function that allows to associate external user names to the user IDs present in the user table.

# Answer
> 2 votes
I had success modifying the Portal Plus Authentication module.

This module uses a SOAP web service to check if the user & password exist in the remote system and if so, creates/updates the user in the Drupal database. It also has some nice features such as the option to add a role to the user at login for the first time, or to not allow drupal-only members to log in.

I recommend looking at the source of this module, specially because it's small, simple and easy to understand (Drupal 6/7 versions available).

---
Tags: 7, users, database
---


# Question
Title: Views relationships with two views blocks
I am trying to connect two different block views so as when you click the title of the first view block the second block will display the content of the url. Both views are of the same content type. How do i do this? or any usefull tutorials i can count on?

**EDIT:** I have this company news page which is accessible from the main menu so that's why i wont to keep the same url. So i created a content type called company news and two views. The first view will display the date and the title of the company new and the second view block will display the content of the company new clicked. My first view is like a left-hand side bar with the 10 newly added. So if a user clicks for example at the second company new the second view block willk display the content of that new. I hope i made it more clear!

# Answer
> 1 votes
In this case I think you need one view who shows title, date and body.

So now you will have a full list of all the news and through jquery you can do something like this.

```
 $('.field-name-body').hide(); //it hides all the body fields.
 $('.views-row').click( function() { // The body is a children of the row.
$('.field-name-body').hide(); // it hides all the open body fields if there is one.
  $(this).children('.field-name-body').show();
});

```

Do you want something like this? Fix the css with more specifications (view name, block name...) With the css you can do the style you want.

---

If you want to have two different blocks you need to show in one view all the title fields and in the other view all the body fields. You don't need contextual filter for the second view (a part from the company id). You will show all the body fields and then hide them.

Now you need to change the files views-view-unformatted.tpl copy it from views/theme, paste it into you template folder inside your theme and rename it with the name of the view. To find the name of that view, you have to open your view, on the third column you click on theme and you will see the files and the suggested name to specify that view (views-view-unformatted-YOURVIEW-BLOCK\_1.tpl or something like this). Do it for both views block, they have to be different, one could finish with block\_1 and the other with block\_2. Clear the cache after you rename the files. In the views you can add the node id and exclude it from display.

This is views-view-unformatted.tpl

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

AND YOU CAN MODIFY ADDING THE ID IN THIS WAY WITH $view-\>result\[$id\]-\>nid;

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>" id="<?php print $view->result[$id]->nid; ?>"> // in the body view use body-id
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

So, now again the js

```
$('.field-name-body').hide(); //it hides all the body fields.
$('.field-name-body:first').show(); // It will open the first news.
$('title:first').addClass('active');// add class active to the first title
$('.title').click( function() { // The body is a children of the row.
$('.title').removeClass('active'); // remove class active to all the title
    $('.field-name-body').hide(); // it hides all the open body fields if there is one.
    $(this).addClass('active'); //add class active to the clicked element
    var activeBody = $(this).attr('id'); //find the id of the clicked element
    $('#body-'+activeBody).show();
    });

```

---
Tags: 7, views
---


# Question
Title: How to add a cck email field as default value in webform
I have a content profile type with a cck email field (this is not the user email and so is not the author's email field). I would like guests to be able to send a contact form (webform) to the email address in the cck mail field.

I have the field displayed via views in a panel so I can change the link to output the url to include the email address and use %get in the webform but that is obviously not the way to go as it exposes the email address.

So can it be done using %post or php in the webform?

Using D6 & webform 3

Many thanks

# Answer
> 1 votes
If you are using the Email Field module then it is possible.

In your view choose your email field , on Format option choose the *Email contact form* option. It won't expose the email.

---
Tags: entities, webforms, emails
---


title: multilingual support

text:
# Question
Title: multilingual support
I would like to create a content type in Drupal 7, which is available in both Italian and English. This is why I enabled multilingual support in the options of publications that allows me to choose the creation of each new node language. But...How do I then change the choice of language in which I see the node in the web pages?

# Answer
> 2 votes
You need i18n module. It gives you a possibility to display a language switcher block on the front end.

Also check Localization update module for automatic update of translations.

---
Tags: theming, 7
---


# Question
Title: How can I list the current user's orders with Drupal Commerce?
I need a View which shows the list of all orders belong to the currently logged in user.

I looked at the Administrators Order View, there are some stuff with Commerce-Line Items but I couldnt figure out how they made that

# Answer
> 5 votes
Create a new view showing "**Commerce order**" not "**Content**" as it is by default. Then add a contextual filter for "**Commerce Order: Uid**" and make it validate as the logged in user.

then you can add all the fields you want for that view

# Answer
> 6 votes
There already is one provided with commerce\_order\_ui called commerce\_user\_orders. By default it's available at user/\[uid\]/orders. It needs the permission *View own orders of any type*.

---
Tags: 7, views, commerce
---


# Question
Title: Drupal 7 custom form submit handler is not being called
I am trying to write a custom handler for one of the Drupal 7 forms:

```
function mymodule_formid_alter(&$form, &$form_state, $form_id) {

 array_unshift($form['#submit'], 'mymodule_formid_submit');

}

function mymodule_formid_submit($form, &$form_state) {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
    return
}

```

But it is not accessing the handler. Alter method *is* being called and printing 'mymodule\_formid\_submit' in the #submit array.

Maybe I am missing something, but exiting answers on Stack Overflow related to custom handlers are not helping in my case.

# Answer
I had this same problem trying to edit commerce\_product form. For some reason the submit handlers are registered under actual submit button and custom handlers added to the #submit -element weren't registered.

```
$form['#submit'][] = 'my_custom_handler';
$form['actions']['submit']['#submit'][] = 'my_custom_handler';

```

So when I added that second line to register my custom handler to button and atleast it works.
> 6 votes

# Answer
In the **mymodule\_form\_alter()** function (replace mymodule with your module's name), override the **#submit** property of the form your want to handle.

```
function mymodule_form_alter(&$form, &$form_state, $form_id){
switch($form_id){
    case 'some_form_id':
      // some code to handle the form.
       $form['#submit'][] = 'mymodule_mysubmit_handler';
     break;
  }
}

```

Either you have to user **hook\_form\_alter()** or **hook\_form\_FORMID\_alter()** function. So you should write mymodule\_form\_formid\_alter() function.
> 4 votes

# Answer
Actually, it accessing your handler. BUT, after it, Drupal makes internal redirect to avoid some problems with page refreshing. On the redirected page your handler will not be called (it has been called already), and your JS will not be added to the page.
> 3 votes

---
Tags: forms
---


# Question
Title: Display content type in a tab of user profile
I have created content type **"Bloggers"**, with few fields -

1. first name
2. last name
3. picture

Now i want to add this content type to user profile, so only admin can change information about user. I want to see a tab called **Blogger Bio** near *VIEW, EDIT etc...* Basically i want to add (content type)Bloggers information to each user with a certain role and see this information in a tab in user profile and also edit this information.

# Answer
It sounds to me like you are trying to re-create what is essentially a combination of Profile2 and Field Permissions

***Profile 2***

> Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields!

***Field Permissions***

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: How can I make a link from user account page to its content profile node?
I could make a link from content profile to its user page by this method.

But how can I do the other way round from user account page to content profile?

# Answer
> 0 votes
Probably content\_profile\_load is the way to go.

The relevant issue here : http://drupal.org/node/680356

---
Tags: 6, users
---


# Question
Title: What do I do if a contributed module update is not available?
I am upgrading a project from D6 to D7, and I've noticed that some contributed modules I need is not available as stable D7 releases. Some contributed modules are not at all available for D7, and some contributed modules only exists as development releases for D7.

Example: The OneHourTranslation Service module. It doesn't have a D7 version, not even a development release.

1. What should I do if the module I need is not available for the upgraded D7 version?
2. What should I do if the module is only available as a development release?

# Answer
the safer approach is not to update to Drupal 7 and wait until all modules have at least a beta version for D7. If there are modules which do not have a D7 version at all, you can try to get a developer to convert the module(s) to D7
> 1 votes

---
Tags: 7, migrations
---


# Question
Title: How to exclude fields from print page version (html, pdf)?
As in question, excluding node fields from HTML print page is easy via CSS, but what about PDF version (PDF version module)?

# Answer
A quick peek in the code shows that the Print module utilizes "View Modes", which is a good thing. More info in Entity view mode and Drupal 7 custom node view modes.

You should create a new suitable view mode or re-use one you already have. This allows you to control the settings with the Field UI, while still allowing you custom templates if you need to.
> 4 votes

# Answer
You can try overriding the print template (print.tpl.php). The default template for that is in the directory of the print module. That's if you're using Drupal 6.
> 2 votes

---
Tags: theming, files
---


# Question
Title: How to make Drupal 7 render taxonomy tags as RSS categories?
In Drupal 7, taxonomy tags do not show up in the RSS feed. How do I make them visible in the feed, so that RSS reader users can filter out stories based on these tags?

(I found it difficult to find an answer to this, so posting my findings in the hope this helps others)

# Answer
This used to be the default behaviour in D6, but was accidentally removed from D7 after some refactoring. The latest versions of D7 contain a patch that allowed a third-party module to show RSS categories.

**Step 1:** download and install the RSS field formatters module.

**Step 2:** navigate to /admin/structure/types

**Step 3:** click "manage display" next to the desired content type

**Step 4:** expand "custom display settings" and make sure "RSS" is checked:

**Step 5:** select the "RSS" tab (after hitting Save if you had to enable the RSS checkbox). This one is a bit hard to notice:

**Step 6:** add the Tags to the fields list if not already there. Set the format to "RSS category":

Now save and enjoy your taxonomy tags in your RSS feed!
> 2 votes

---
Tags: 7, feeds
---


# Question
Title: Should I replace Magento with Drupal for my e-commerce solution?
I am working on an e-commerce project. Essentially, it's a 'expansive product catalog -\> shop cart; users database' type of thing. Everything is still in development environment. I am trying out Magento, I have mixed feelings about it. It is plug-n-play powerful, it seems to suit a lot of situations out of the box. However, now that I am getting to know it better, I see that I will have to get my hands dirty and code, customize, add features of my own, concerning website visual and non-visual design.

Is Drupal easier to work with for a developer/designer? How can product catalog importing/exporting be handled in Drupal? With Magento, I use Magmi and csv, which I love. I will definitely be implementing some kind of automated catalog updating, which I was planning to do with Magmi; that is very important to me.

In general, could you advise on your experiences on Drupal v. Magento for e-commerce?

## Edit:

# Conclusion:

I will be switching to Drupal, because I have found that even though Magento has many mature built in features, I only need a select few of them, and I have too little control over them, it feels like it is cluttered and rigid in my situation. I need something that is more friendly to 'going under the hood', and I think Drupal is it. I think if I was a better programmer, I could get Magento to suit my needs, but I'm afraid I'm not. Goodbye, Magento.

# Answer
> 7 votes
Having never used Magento, I'd say go with Drupal + Drupal Commerce ;-)

Check out the following articles though:

Drupal will allow you to import products with a combination of Feeds and Commerce Feeds or Commerce Migrate (the latter requiring a bit more work).

I think at the end of the day it comes down to your personal needs. If you don't need a fully functional CMS (or CMF...make your own mind up), then better the devil you know; might as well go with Magento.

If you want a whole integrated solution, then Drupal is clearly the winner. I'm pretty sure there are a couple of dev houses around where I am who are migrating sites from Magento to Drupal Commerce, but I've not heard of anyone doing it the other way around.

Lastly, depending on the complexity of your project you may have to get your hands dirty with Drupal too, but it's not that hard :).

# Answer
> 1 votes
From my experience with Magento I can tell you that theming it is very difficult compare to theming in Drupal. If you're using a custom theme for your site and not one of those premade themes then you're gonna have a hard time figuring out how to theme you Magento store. The support is also scarce if you're not subscribed to the very pricy enterprise version of Magento. Magento have lots of cool features out of the box but nothing you can't find in contributed modules for Drupal.

# Answer
> 1 votes
My two pennies!

If you want to just do eCommerce and can handle the headaches of troubleshooting in the dark a little, then go for Magento. It is rock solid and works pretty much out-of-the-box.

That said, it is a bit tricky to theme and customising it to your will is quite hard.

Drupal is much more friendly if you are a low-middle weight coder because the contributed modules all have so many options to fiddle with in the backend without ever getting your hands dirty with too much code.

I would suggest that you allocate three days to each platform and see how far you are able to get with each one and which you prefer. The three days that you loose on the 'wrong' platform will be made up for with the time that you save using your preferred solution.

Both are cool, both are different.

---
Tags: commerce
---


# Question
Title: How i change scripts in my custom theme in drupal 6
i write a custom theme for my site and i want to remove `misc/tableheader.js` script from site scripts and add my own `tableheader.js` instead.
is any way to i do it without changing original `misc/tableheader.js` file?

# Answer
It's been a while but I think this is the way to do it in Drupal 6:

```
function MYTHEME_preprocess_page(&$vars) {
  // Add your JS
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/my-tableheader.js'));

  // Get the cached JS
  $js = drupal_add_js();

  // Remove the core tableheader file
  unset($js['module']['misc/tableheader.js']);

  // Change the scripts var to reflect the new array
  $vars['scripts'] = drupal_get_js('header', $js);
}

```
> 2 votes

---
Tags: 6, javascript, theming
---


# Question
Title: Db_Query Fatal error: Unsupported operand types
I am simply trying to return the rows from a table in my db but i keep getting this error thrown back at me no matter what I do "Fatal error: Unsupported operand types in C:\xampp\htdocs\d7\includes\form.inc on line 1009". Am I missing a argument or something?

This is my function

Hook menu

```
function auto_form_menu() {
$items = array();
$items['admin/config/auto_form'] = array(
    'title' => 'My Module',
    'description' => 'description',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('auto_form_records'),
    'access arguments' => array('administer site configuration'),
    'file' => 'auto_form.admin.inc'
);

$items['admin/config/auto_form/manage'] = array(
    'title' => 'My Module',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'description' => 'description',
    'weight' => -10,
);
return $items;
}

```

'auto\_form.admin.inc'

```
function auto_form_records() {
  $header = array('First Name', 'Last Name');

  $dbresult = db_query("SELECT first, last FROM {auto}");

    $rows = array();
    foreach ($dbresult as $dbrow) {
        $rows[] = array(
        $dbrow->first,
        $dbrow->last
      );
    }
    return $output = theme('table', array('header' => $header, 'rows' => $rows));
}

```

Updated Code:

Any help is appreciated seeing how I am completely lost on figuring this out.

# Answer
I finally figured out what it was, it was hook\_menu in my module. It was looking for a form when there was no form in place by using drupal\_get\_form as a page callback. If i change the page callback to the function being used in the file the error goes away and the results come back. Please see the example below...

Hook menu

```
function auto_form_menu() {
$items = array();
$items['admin/config/auto_form'] = array(
    'title' => 'My Module',
    'description' => 'description',
    'page callback' => 'auto_form_records',
    'access arguments' => array('administer site configuration'),
    'file' => 'auto_form.admin.inc'
);

$items['admin/config/auto_form/manage'] = array(
    'title' => 'My Module',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'description' => 'description',
    'weight' => -10,
);
return $items;
}

```

Function in my inc file

```
function auto_form_records() {
  $header = array('First Name', 'Last Name');

  $dbresult = db_query("SELECT first, last FROM {auto}");

    foreach ($dbresult as $dbrow) {
        $rows[] = array(
        $dbrow->first,
        $dbrow->last
      );
    }
    return $output = theme('table', array('header' => $header, 'rows' => $rows));
}

```
> 0 votes

# Answer
I'm not sure exactly which one is causing the error but there are a couple of things:

* You're trying to loop over a variable called `$dbresult` which you haven't declared; you probably meant

```
$dbresult = db_query("SELECT first, last FROM {autoform}");

$results = '';
foreach ($dbresult as $dbrow) {

```
* It looks like you're using Drupal 7, and the call you're making to `theme_table` contains arguments in the style of the Drupal 6 call. Variables are all named in Drupal 7 so you need to invoke the function like this:

```
$output = theme('table', array('header' => $header, 'rows' => $data));

```
* `theme_table()` takes an array of rows, and each of those arrays will have the data for a number of columns, one for each that you've defined in your header. At the moment you're concatenating a single string and creating a single row containing one cell, with that single string in it.

I think something like this is more what you're after:

```
$rows = array();
foreach ($dbresult as $dbrow) {
  $rows[] = array(
    $dbrow->first,
    $dbrow->last
  );
}

$output = theme('table', array('header' => $header, 'rows' => $rows));

```

Also if you want a nice little shortcut leveraging some of the db API you could use this reduced code:

```
$header = array('first' => 'First Name', 'last' => 'Last Name');
$rows = db_query("SELECT first, last FROM {autoform}")->fetchAllAssoc();
$output = theme('table', array('header' => $header, 'rows' => $rows));

```

That last snippet will become less useful the more you need to customise the individual rows/cells of the table.
> 1 votes

---
Tags: routes
---


# Question
Title: Creating one view for taxonomy page teasers so I don't have a ton of views
this seems like a simple problem but I can't seem to find a straight forward answer for Drupal 7. I have a ton of taxonomy vocabulary pages and I just want to configure them the same all the way through the site. So I just want one view that formats them all.
Can someone point me in the right direction?
Thanks!

# Answer
> 0 votes
When you have the taxonomy and views module enabled you should see a couple of disabled views and one of them is a view that format the taxonomies pages and their XML feed. Enable them and you will be able to play with them as need it.

See image below:

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: How can I let a group of users edit anything in a specific section?
Our content editor wants to let the various authors have rights to edit things in only specific sections, and it will often be multiple people assigned to a given section. What's the best way to do this? (And sections do NOT map neatly to content-types. They're based on the menu/site structure.)

# Answer
It's not clear to me what your rule is for determining access control. I'm going to guess it's menu paths.

I had a similar problem recently. I needed to ensure that users trying to access /somePathName/\* were of a certain role. This is a bit of an odd scenario in that any path in the system could be aliased under one of my UAC paths and it will automatically become access controlled whether it was a term, node, user, whatever.

I looked into existing solutions and found none. I wrote my own module that managed access control based on "arg(1)" and a user's roles.

Access control in Drupal is one of those pieces that you understand after a few hours of studying, do the work, then completely forget how you did it. Or maybe that's just me.

d.org documentation is pretty good on this topic. And be sure to install devel and enable the node access modules it provides. These are very useful.
> 2 votes

---
Tags: nodes
---


title: Comments sorted by oldest first

text:
# Question
Title: Comments sorted by oldest first
I've set my comments display order to be oldest first. When there are more comments than the number allowed per page, the comments are spread across 2 pages and a pager is provided.

My issue is that when you first come to the node to see the comments, you see the older comments. You then have to click to the 2nd page to see the latest comments.

I understand from a logical perspective why it works this way, but I don't think its the best for usability. How can I make it so when you arrive at a node you see the last page of comments by default? Do I need to use a views override? Thanks

Note, in case its of interest this point has been raised by the drupal experts lullabot: http://www.lullabot.com/articles/drupal-usability-comment-configuration

> While shorter pages are generally more usable, setting the number of comments per page to a low number comes in conflict with my recommendation of setting the display order to oldest first. With a small number, it is very possible that the latest comments will not be listed on the initial page and will require several clicks and scrolling to get to them. This is bad. A better solution is to set the comments per page as high as possible. Users will intuitively scroll down to find the latest stuff.

# Answer
> 3 votes
you could do this with a view. I was about to post you a long detailed post on how to get this done, but found this post on the subject that explains it in great detail.

Basically, you create a view and from there you have sort options available for your comment fields.

Credits to DAO Design for the blog post, hope that helps, cheers!

# Answer
> 1 votes
Comment Goodness module does just that. Sort Comments is another option, but as of now only has a development release.

Here's a snapshot of Comment Goodness module, borrowed from the site.

---
Tags: comments
---


title: Set destination on comment post

text:
# Question
Title: Set destination on comment post
Short question: How do you modify the destination on comment post?

Long question: Say, my comment limit is set to 10 per page. When I post the 11th comment, Drupal takes me to /node/#?page-1#comment-#. Instead, I want it to take me to the node it was posted to, i.e. /node/#.

I need this because I'm using the More Comments module, which doesn't use pagers and not compatible with permalinks.

# Answer
> 0 votes
I haven't figured out how to manually set the destination on comment post, but I did found the Comment Goodness module that works with More Comments, to remove the ?page-1#comment-# query. And this solves my question.

---
Tags: 7, comments
---


# Question
Title: How to create a Sub-theme based on a Zen Sub-theme
I would like to modify the CTI Flex theme but would prefer to keep my changes as maintainable as possible. CTI Flex is already a Zen (7-x.3-x) sub-theme.

I have used the Zen starterkit in the past to create a Zen sub-theme, but never a sub-theme of another sub-theme.

How do I create a sub-theme of using another Zen sub-theme as a start point?

# Answer
It shouldn't be too hard ... I have a live site running a sub-theme of an AdaptiveTheme sub-theme (Sky). The only thing you have to is create your theme folder and copy the existing `zen-sub-theme.info` to your own `zen-sub-sub-theme.info` and rename the `base theme` value to the zen-sub-theme.

See this page, some magic inheritence occurs with CSS if you define 1 stylesheet for your theme: http://drupal.org/node/225125

By creating your own .info file you are defining regions / ccs files and theme specific variables. You will also probably want to copy the zen-sub-theme's template.php file as well (renaming the functions to your themes name).
> 1 votes

---
Tags: theming
---


# Question
Title: How to apply a patch for a Drupal module?
I'm trying to us this patch http://qa.drupal.org/pifr/test/298933

Save the patch file to the root directory of feeds module (`sites/all/modules/feeds`) then apply the patch by using git bash.

So I typed:

```
git apply -v fcollection.patch

```

and it returns the following error:

> checking patch field\_collection.module... error: field\_collection.module: No such file directory

I hve a field\_collection module installed in my site.

So what I did to experiment is to copy the patch to field\_collection module folder and run the patch from that folder.

Then I got this error:

> error: patch\_failed: field\_collection.module:1142 error: field\_collection.module: Patch does not apply.

How can I apply the patch successfully?

# Answer
This patch also exists at this #1063434 \- the original issue for the test you reference above. One easy way to apply this patch would be to use the Drush Issue Queue commands.

Install with:

```
drush dl drush_iq

```

Then use it like this:

```
cd /path/to/drupal/root
drush am 1063434-#40

```

Presto! Patch applied! Then `drush-iq` will work even better if you check out the module from git (i.e. `drush dl field_collection --package-handler=git_drupalorg`).

If you don't want to use `drush-iq`, try:

```
cd /path/to/drupal/root/sites/all/modules/field_collection
wget http://drupal.org/files/field_collection-feeds_integration-1063434-40.patch
patch -Np1 < field_collection-feeds_integration-1063434-40.patch

```
> 2 votes

---
Tags: 7, version-control
---


title: Removing /home url

text:
# Question
Title: Removing /home url
A little tricky this one --- I got handed this site and they have somehow messed the theming up on the home page, so they recreated a new home and redirected it there - both in the config section and in the .htacess but - - - they dont want the url ../home to appear

Is there a quick fix?

---- update Thanx but no luck still - I am now certain its an htacess issue. I have the following settings.

* RewriteEngine on RewriteCond %{HTTP\_HOST} mydomain.net \[NC\]
* RewriteCond %{REQUEST\_URI} ^/$ Rewriterule ^(.\*)$
* http://mydomain.net/home \[L,R=301\]

What I want to do is to remove the /home If I delete the /home I get a page with no themeing

# Answer
Navigate to /admin/config/system/site-information, and set "Default front page" to the path you want, without a leading slash (sounds like "home" in this case).

Then remove the redirect from htaccess.
> 4 votes

# Answer
You can achieve it with the Front Page module.

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
>
> * **Alias** \- Allows for another Drupal path to be shown as the home page without redirecting the user.
> * **Redirect** \- Allows you to redirect users to a local or remote URL.
> * **Themed** \- Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
> * **Full** \- Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.
> 0 votes

---
Tags: uri
---


# Question
Title: Commerce Feeds: Multiple values in one field or multiple fields?
### Goal

What I'm trying to ultimately accomplish is create tiered pricing based on quantities.
The client is selling different prices depending on quantity. I'm trying to figure out what is the simplest way to store, access and represent this data using fields. While at the same time i'm importing them through commerce feeds.

### About my feed/data

I have a CSV table header with the columns "P1 Price," "P2 Price," and "P3 Price." There are also "P1 Qty," "P2 Qty," and "P3 Qty."

Thus, P1 Price corresponds to P1 Quantity, etc.

### My question

Would it be simpler, in terms of less complex rules or views configuration, in the long run if i created separate fields to store each price/quantity, or if I combined them into one field that stores 6 different values?

My primary considerations include, scalability, maintainability, etc.

# Answer
Found an issue queue related to this: http://drupal.org/node/759966. Also, currently multivariable fields haven't been implemented in feeds.

There's also a commerce price table processor patch currently being reviewed.

Randy fay also shows how to utilize feeds\_tamper to add multivariable fields via a video screen cast.
> 0 votes

# Answer
It sounds like what you need is commerce price table. There isn't a stable release for it yet, but I have seen it demoed where it worked great.
> 1 votes

# Answer
Looks related to Feeds support for importing prices
> -1 votes

---
Tags: database, feeds, commerce
---


title: What does views_ensure_table() do?

text:
# Question
Title: What does views_ensure_table() do?
I see it often, $this-\>ensure\_my\_table() and I'm not sure what it does and why it is important when building Views handlers.

# Answer
> 1 votes
Taken from the API page:

views\_handler::ensure\_my\_table

> Ensure the main table for this handler is in the query. This is used a lot.

It's just to make sure that the base table (`node` or `user` for example) that your handler needs is referenced in the query/actually exists.

---
Tags: views
---


# Question
Title: What is your recommended Banner/Slider module for D7?
I am searching for module that create banner/slider effect for D7.

Have a check on this page: http://drupal.org/node/418616

Mostly not yet port to D7.

What are your recommend modules?

# Answer
> 4 votes
I have used Views Slideshow a couple of times and it was quite easy to use. It's based on the jQuery Cycle Plugin. The port to D7 is in alpha, so you might want to give it a go and contribute back to help the module reach a stable state.

That said, a module is not strictly necessary to do things like this. It's surprisingly easy to implement the (well documented) jQuery Cycle Plugin yourself, directly from your theme. Just add the plugin and write about 10 lines of jQuery in a custom .js file.

# Answer
> 1 votes
@marcavangend is mostly right.

There is one other to consider which is Drupal 7 only: Rotating Banner.

It may not match your exact needs, but it is quite nice.

> ### Features
>
> * Various transition effects (fade, wipe, etc)
> * Rich Editor where you can pick a background image and add headlines and text areas
> * Supports inline editing and drag and drop
> * Creates blocks, you can make a bunch of them
> * Can be a static size, or will grow to the size of your largest / smallest image or the size of the region you put it in automatically

# Answer
> 0 votes
Check the Nivo Slider module.

> Nivo Slider provides an easy and eye-catching way to showcase featured content. Nivo Slider gives administrators three important tools:
>
> * A simple method of adding slides to the slideshow.
> * An administration interface to configure slideshow settings.
> * Simple slider positioning using the Drupal block system.

---
Tags: 7
---


title: Center header logo in Bartik theme

text:
# Question
Title: Center header logo in Bartik theme
I am using the Bartik theme in Drupal 7.15 and would like to have the header logo centered rather than left-aligned, is there some little piece of CSS I can add in with `drupal_add_css()` that will center the logo image? I need it to center correctly based on the width of the header image, so fake centering just using left padding isn't an option.

Thanks in advance.

# Answer
> 1 votes
A rule like this should do it:

```
#logo {
  display: block;
  width: 100px; // width of the image
  margin: 0 auto;
}

```

# Answer
> 1 votes
Adding this CSS with `drupal_add_css()` makes the logo center:

```
#logo     { padding-left: 50%; }
#logo img { margin-left: -50%; }

```

---
Tags: theming
---


# Question
Title: Display Suite layouts not available for field collections Edit\Add forms
I'm using Drupal 7 with the Display suite and Field Collection contrib modules.

For nodes entities the "Layout for..." vertical tab provided by Display Suite is available in both "Manage fields" and "Manage display". This applies also to any node content type I created, so I'm able to rearrange forms layouts used when adding\editing *and* when viewing nodes.

But for field collections the "Layout for ..." vertical tab is missing in "Manage fields" and it's available only in "Manage display", so I'm not able to rearrange the layout used by the add\edit form specific to field collections.

Is this a limitation of Display Suite? Any other way to rearrange the edit\add form for field collections fields?

# Answer
> 1 votes
If you are using 7.x.1, you need rel module to edit forms from other entites than node type, like field collection, user, comment, etc. If you are using 7.x.2 you don't need that because this branch offers this feature out of the box. For editing forms, you must go to Manage fields of your entity.

edit: just to note that rel will stop this from working on the 7.x.2 branch.

---
Tags: 7, display-suite
---


title: Add a class to first query result

text:
# Question
Title: Add a class to first query result
How can I add a class to first query result?

```
$number_of_slides = '3';
$slides_result = db_query_range("SELECT nid FROM {term_node} WHERE tid = 1 ORDER BY nid DESC", array(), 0, $number_of_slides);
while ($slidesid = db_result($slides_result)) {
$slides = node_load($slidesid);
print $slides->title;
}

```

anyway I tried this but it doesn't work.

```
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$('.item')
    .eq(0).addClass('first').end()
    .eq(-1).addClass('last').end();
</script>
<style type="text/css">
.first, .last{
background-color:#0099FF;
}
</style>
</head>
<body>
<div class="item">aaa</div>
<div class="item">bbb</div>
<div class="item">ccc</div>
</body>
</html>

```

# Answer
> 2 votes
If you're going to use jQuery anyway, why not just use the `.first` and `.last` selectors?

```
$('.item').first().addClass('first');
$('.item').last().addClass('last');

```

---
Tags: theming, 6
---


# Question
Title: How do I make a Registration page in Druapl 7
im very new to Drupal 7, and I need help creating a register page with a few fields.

# Answer
> 3 votes
Using custom forms for registration is not at all Suggested ! Follow below steps to solve the issue.

* Login as super admin
* Go to admin/config/people/accounts/fields
* Add New Fields
* Check Display on User Registration form in field settings.

---
Tags: entities
---


# Question
Title: Make a div clickable using a render array
What is the (best) way to make a div clickable using a render array in code?

I am creating a module that outputs a title in a rounded box, so I use the markup type and specify a class with #prefix and #suffix and apply some css on that class. This gets me a box, but I want to make the box clickable with a different url for each box. What would be a good way to do this?

I could put an onclick in the prefix or put in the prefix and in the suffix. But both are not very pretty.

I'm using Drupal 7 and would like not to use additional modules like views.

# Answer
> 0 votes
I did some more digging and came across the container type. This is imo the best way to achieve this.

You use a container as wrapper to which you assign the class and onclick attributes. Then with markup you put whatever you want inside the container/div. It is possible to put more items in the container simply by adding more children to the $divwrapper class.

This is the code I ended up with (for several titles/boxes):

```
  $titles = array(1 => 'title 1', 2 => 'title 2', 3 => 'title 3');
  $output = array();
    foreach ($titles as $id => $title) {
      $onclick = "location.href='/node/{$id}'";
      $divwrapper = array(
          '#type' => 'container',
          '#attributes' => array('class' => array('rounded_box'), 'onclick' => $onclick)
      );
      $divwrapper["box_{$id}"] = array('#markup' => "<p>{$title}</p>");
      $output[] = $divwrapper;
    }
  return $output;

```

# Answer
> 0 votes
It sounds like you want to create an Accordion, I would look at Views Accordion because it sounds like what you want. I would try to stay away from custom javascript and html and attempt to theme views\_accordion as you want it to look.

---
Tags: 7, theming
---


# Question
Title: How can I display a Group Membership in custom user profile
I would like to display the group of a member in their user profile but I don't know the PHP syntax for getting the group. I'm using the render function, but I have an error. When I put `print_r($user_profile);`, I get the following array structure :

```
Array
(
    [#printed] => 1
    [user_picture] => Array
        (
            [#markup] =>
            [#weight] => -10
            [#type] => markup
            [#pre_render] => Array
                (
                    [0] => drupal_pre_render_markup
                    [1] => ctools_dependent_pre_render
                )
        [#children] =>
        [#printed] => 1
    )

[og_user_group_ref] => Array
    (
        [#theme] => field
        [#weight] => 0
        [#title] => Group membership
        [#access] => 1
        [#label_display] => above
        [#view_mode] => full
        [#language] => und
        [#field_name] => og_user_group_ref
        [#field_type] => entityreference
        [#field_translatable] => 0
        [#entity_type] => user
        [#bundle] => user
        [#object] => stdClass Object
            (
                [uid] => 11
                [name] => tmeddeb
                [pass] => $S$DRJpiD/FKXsAIoBKMv9YFcGMfhu/4jU0TfOaoeolVcS4ZhxP8KIA
                [mail] => tmeddeb@ccomptes.net
                [theme] =>
                [signature] =>
                [signature_format] => filtered_html
                [created] => 1348668493
                [access] => 1349771256
                [login] => 1349771256
                [status] => 1
                [timezone] => Europe/Berlin
                [language] => ar
                [picture] =>
                [init] => tmeddeb@ccomptes.net
                [data] =>
                [roles] => Array
                    (
                        [2] => authenticated user
                        [8] => الناشر
                        [10] => _user_role_11
                    )

                [og_user_group_ref] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [target_id] => 17
                                    )

                            )

                    )

                [og_other_user_group_ref] => Array
                    (
                    )

                [field_grade] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [value] => مستشار لدائرة المحاسبات
                                        [format] =>
                                        [safe_value] => مستشار لدائرة المحاسبات
                                    )

                            )

                    )

                [field_function] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [value] => مدير عام
                                        [format] =>
                                        [safe_value] => مدير عام
                                    )

                            )

                    )

                [field_firstname] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [value] => الطاهر
                                        [format] =>
                                        [safe_value] => الطاهر
                                    )

                            )

                    )

                [field_lastname] => Array
                    (
                        [und] => Array
                            (
                                [0] => Array
                                    (
                                        [value] => المؤدّب
                                        [format] =>
                                        [safe_value] => المؤدّب
                                    )

                            )

                    )

                [rdf_mapping] => Array
                    (
                        [rdftype] => Array
                            (
                                [0] => sioc:UserAccount
                            )

                        [name] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => foaf:name
                                    )

                            )

                        [homepage] => Array
                            (
                                [predicates] => Array
                                    (
                                        [0] => foaf:page
                                    )

                                [type] => rel
                            )

                    )

                [realname] => tmeddeb
                [entity_view_prepared] => 1
                [privatemsg_disabled] =>
            )

        [#items] => Array
            (
                [0] => Array
                    (
                        [target_id] => 17
                    )

            )

        ***[#formatter] => og_list_default
        [0] => Array
            (
                [#type] => link
                [#title] => غرفة الموارد البشرية
                [#href] => http://localhost/drupal/?q=node/17
            )***

        [#markup] =>
        [#children] => <div class="field field-name-og-user-group-ref field-type-entityreference field-label-above"><div class="field-label">Group membership: </div><div class="field-items"><div class="field-item even"><a href="http://localhost/drupal/?q=node/17">غرفة الموارد البشرية</a></div></div></div>
        [#printed] => 1
    )

```

But when I try to get the title value of \[formatter\] I get the following fatal error:

**Fatal error: Cannot use string offset as an array in C:\wamp\www\drupal\sites\all\themes\courdescomptes\user-profile.tpl.php on line 17**

The function for getting a title value for formatter is as follows:

```
print render($user_profile['og_user_group_ref']['#formatter'][0]['title'])

```

# Answer
From the looks of your output it should be `#title` not `title`:

```
print render($user_profile['og_user_group_ref']['#formatter'][0]['#title']);

```

Since `#title` is a string though you'll want to just print it directly and save yourself the tiny bit of overhead:

```
print $user_profile['og_user_group_ref']['#formatter'][0]['#title'];

```
> 1 votes

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


# Question
Title: What is the best choice to create a node through code?
The scenario goes this way, I have a node type which has lot of Taxonomy term fields in it. It does also have other fields like text, date etc but 90% of it is a taxonomy field. I am aware that a node can be created programatically in two ways,

* node\_save() - Creating a node object and saving it

```
$node =  new stdClass();

$node->type = 'article';

$node->field_term[LANGUAGE_NONE][0]['tid'] = 3128 // term id of the term

node_save($node);

```
* Form submit - creating a form array and submitting using drupal\_form\_submit

```
$node[field_first]['und'] => chennai;

$node[field_second]['und'] => "iphone5";

$node['type'] = 'article';

$form_state['values'] = $node;

$form_state['values']['op'] = t('Save');

drupal_form_submit($node_type . '_node_form', $form_state, (object)$node);

```

with $node having the POST values.

Advantage of using form submit method is Drupal will take care of creating new terms in vocabulary (I am supposed to get more new terms). Form submit can follow form validations which is needed for creating a node.

Is there any method to create nodes faster in to Drupal system which supposed to get more terms in it?

If there is no other method than the above mentioned, what is the best one?

# Answer
The safest method is to use drupal\_form\_submit(). If you take at look at the services module it does the same thing. Form validation should be important if you are creating nodes programmatically. Are you importing or creating multiple nodes at once? If this is the case and you are concerned about performance you can use Drupal's batch api or queue. Batch is great if you need user feedback but if you are creating nodes on cron and don't require a ui with feedback then queue is the way to go. In both cases they take care of memory management for you.

I wouldn't be to concerned about how long it takes to create one node as that is how long it would take with the ui. Unless the reason you are doing it through codes is to increase creation times.
> 4 votes

---
Tags: forms, nodes
---


title: How to theme /comment/# page

text:
# Question
Title: How to theme /comment/# page
Currently `example.com/comment/#` shows the contents of the node that the comment is posted to. I want the page to only show the comment.

I'm assuming the page does not theme via .tpl.php. And if it isn't, do I put something like this in the template.php, and how do I override the current content of that page:

```
$comment = _comment_load($cid);
return theme('comment',$comment);

```

# Answer
> 0 votes
There's no conventional way of doing this as far as I'm aware but if you want to do this it can probably be achieved with some processing in your theme.

```
function THEME_preprocess_page(&$variables) {

  // DO SOMETHING WITH request_uri() or similar

  if (isset($SOME_VARIABLE)) {
     $variables['theme_hook_suggestions'][] = "page__comments";
  }
}

```

Then create a copy of your page template as page--comments.tpl.php and take out what you dont need.

This is nasty though and not the 'Drupal' way of doing things.

---
Tags: 7, theming, comments
---


# Question
Title: Modify/hook into admin page of rate module
I'm creating a new widget type for the rate module with some custom settings. I plan to use multiple instances of the same widget each with different custom settings. Is it possible to hook into `rate_widget_form` to alter the admin page of the rate module ?

**Example :**

```
admin/structure/rate/add?template=widgetname
admin/structure/rate/%/edit

```

**Sample Image :**

# Answer
I found the solution for my problem. I used hook\_form\_FORM\_ID\_alter

```
function hook_form_rate_widget_form_alter(&$form, &$form_state, $form_id){
enter code here...
}

```
> 1 votes

---
Tags: 7, hooks, rating
---


# Question
Title: Target different database for a single query?
Can I set the target database on a db\_select()?

Example:

```
$result = db_select('table', 't')->fields('t')->db_target('db_name')->execute();

```

One can use db\_set\_active() to change to which database a query should be sent, but that requires one to manually "reset" the active db, which is a potential cause of bugs.

# Answer
From the comments above such as from @Clive, I do this alll the time:

```
$count_query = Database::getConnection('default', 'dew_remote_sources')
               ->select('survey', 's');
$count_query->addExpression('COUNT(DISTINCT(survey_number))', 'cnt');

```

For this to work you need to have various databases defined in your `$databases` value of settings.php (or you can add additional `$databases[key]` values to top of your module sometimes, or create such a connection on-the-fly using:

```
Database::addConnectionInfo('for_migration', 'default', array(
  'driver' => 'mysql',
  'database' => 'migration_database',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',
));

```

You see this pattern alot in the Migrate documentation pages, migrate examples and 3rd party modules that have implemented migrations. Because you are literally moving content from DatabaseX to DatabaseY alot and switching around with `db_set_active` can easily lead to confusion in such cases with the Object Oriented nature of the Migrate module.
> 3 votes

---
Tags: database
---


# Question
Title: How to highlight active teaser in Views?
Using Views and Panels, I have an unordered list of node teasers that appears on every page. When viewing a node, I would like to highlight that node's teaser in the list.

Class .active gets applied to the teaser link, but I'd like to apply it to the whole list item. Is this possible?

# Answer
> 2 votes
The following does the work for me:

```
function YOUR_THEME_preprocess_views_view_unformatted(&$vars) {

  if (arg(0) != 'node') return; // no active node

  $index = 0;
  foreach($vars['view']->result as $node) {
    if (arg(1) == $node->nid) {
      $vars['classes_array'][$index] .= ' active';
    }
    $index++;
  }

}

```

---
Tags: 7, views
---


# Question
Title: Ajax'ed file field doesn't find the form constructor function on rebuild
I'm manually printing the user profile form in a block using:

```
module_load_include('inc', 'user', 'user.pages');
$form = drupal_get_form('user_profile_form', $user);

```

That works great for displaying and submitting the form.

The form has an image field to add a picture. When I try to upload the picture through Ajax, I get a PHP notice that `drupal_retrieve_form()` is missing the form constructor function (`user_profile_form()`), and the image field isn't being shown anymore.

I'm guessing the image field's Ajax doesn't know about the user.pages file that I included, and can't find the form.

Any idea how to fix this?

# Answer
> 0 votes
You will need to include file by using the `$form_state['build_info']['files']` array.

For example:

```
$form_state['build_info']['files'][] = drupal_get_path('module', 'user') . '/user.pages.inc';

```

---
Tags: 7, forms, ajax
---


title: Undefined variables error

text:
# Question
Title: Undefined variables error
I was working on transferring my website to a new folder. Same database, just a new folder. Worked a bit on the new address, etc.

When I went back to the old address, website is not working anymore. More precisely, it throws a lot of "undefined variables" alerts that clearly have to do with the theme, but I'm pretty sure I have not touched any files there...

```
Notice: Undefined variable: site_logo in include() (line 16 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: site_logo in include() (line 18 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: site_logo in include() (line 21 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: hgroup_attributes in include() (line 28 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: site_name_attributes in include() (line 31 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: tag in include() (line 100 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: primary_local_tasks in include() (line 102 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).
Notice: Undefined variable: secondary_local_tasks in include() (line 117 of /hsphere/local/home/ulufenci/test.ulufencing.net/sites/all/themes/corolla/templates/page.tpl.php).

```

are the kind of errors that I get. I'm using the theme Corolla. Can you please provide any lead as to what might be causing the error?

Thank you!!!

# Answer
> 0 votes
I managed to clear the cache by emptying all the \_cache tables in the database. I then navigated to the theme (Corolla) settings page and clicked on save settings.

And gone. All errors now seem gone.

Thank you very much Patrick K, I wish I could vote your suggestion up! (Will do if you repost it as an answer rather than a comment.) Cheers!

---
Tags: theming
---


# Question
Title: How to prepopulate a node reference field (checkbox)
On a node/add page I have a node reference. The widget type is "checkboxes" and I'm using the "View used to select the nodes" feature to show up to 5 checkboxes on the node/add page.

I would like to prepopulate a checkbox with the prepopulate module.

The checkboxes use this HTML name value:

```
name="field_tribe_content[und][18824]"

```

Usually prepopulate works by adding this to the url, but it doesn't work in this case.

`?edit[field_tribe_content][und]=18824`

There is some info in the issue queue and I have also tried

```
?edit[field_tribe_content][0][nid]=18824
?edit[field_tribe_content][0][nid][nid]=18824
?edit[field_tribe_content][nid][nid]=18824

```

How can I get it to work or what else could I do to preopulate those checkboxes?

# Answer
Take a look here:

Prepopulate checkbox \[#checked\]

I have also been searching for a solution on how to do this.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Views templates: How to print file fields
I am creating a template for my table style view. I have several fields most of which are excluded from display. Inside my template I want to print those excluded from display fields. After some search I found that you can access all fields including those excluded by using:

```
$view->result[$row_count]->

```

Now the field I want to print is a file. This is the structure that dpm returns me:

> field\_field\_programme (Array, 1 element)

```
0 (Array, 2 elements)
    rendered (Array, 3 elements)
        #theme (String, 9 characters ) file_link
        #file (Object) stdClass
            fid (String, 4 characters ) 1011
            display (String, 1 characters ) 1
            description (String, 0 characters )
            uid (String, 1 characters ) 1
            filename (String, 10 characters ) seminar3.pdf
            uri (String, 40 characters ) public://seminaria/programmes/seminar3.pdf
            filemime (String, 15 characters ) application/pdf
            filesize (String, 6 characters ) 218882
            status (String, 1 characters ) 1
            timestamp (String, 10 characters ) 1333973478
            rdf_mapping (Array, 0 elements)
        #access (Boolean) TRUE
    raw (Array, 11 elements)
        fid (String, 4 characters ) 1011
        display (String, 1 characters ) 1
        description (String, 0 characters )
        uid (String, 1 characters ) 1
        filename (String, 10 characters ) seminar3.pdf
        uri (String, 40 characters ) public://seminaria/programmes/seminar3.pdf
        filemime (String, 15 characters ) application/pdf
        filesize (String, 6 characters ) 218882
        status (String, 1 characters ) 1
        timestamp (String, 10 characters ) 1333973478
        rdf_mapping (Array, 0 elements)

```

It is not as simple as using $field-\>content. How can I print my file? Do I need to create a link and add the information above? What code can I use so depending on the filemime the icon will change?

In other views I have created the output of files is:

```
<a type="xxx; length=xxx" href="xxx"><img src="/modules/file/icons/xxx" title="xxx" alt="" class="file-icon"></a>

```

With the information I get from the file I could create such a link. I am guessing length is the filesize? Maybe there is an api function that constructs file links?

# Answer
Using this seems to do exactly what I want

```
<?php print $view->style_plugin->rendered_fields[$row_count]['field_programme']; ?>

```

which is extremely useful since it can be used even for fields that have been excluded from the display of the view.
> 0 votes

---
Tags: views, entities, files, theming
---


# Question
Title: Which field type should I use for a telephone number, and how can I ensure each entry is unique?
I have created a field (field\_telephone) to store telephone numbers like 13712345678.

Which is the best field type to use?
I also want to make sure the values for this field are unique. How can I do that?

# Answer
For a basic telephone field without validation you could just use a text field, and set the maximum length to something sensible for telephone numbers in the regions you're targeting.

If you want a more advanced telephone field, check out the Phone module. There's a stable release for Drupal 6, but only a dev release for Drupal 7.

To make sure fields are unique, you can use the Unique Field module.
> 2 votes

---
Tags: entities
---