# Question
Title: User uploads media and community votes: How do I implement them?
I am a graphics guy who can fumble through code, but not write it from scratch. I have developed a NUMBER of sites, but this is my first Drupal experience. I've read all the starting documents, been playing with Drupal for DAYS now; I have even installed and modified different modules, so I'm somewhat familiar with it and the concepts (nodes, vocabularies, etc).

I have installed Drupal 7.2 on MDD Shared Hosting. I am looking to build a community site (actually a NUMBER of them very similar to this one once this is completed). They are very similar to these sites: \- colourlovers.com \- instructables.com \- gdgt.com (somewhat).

The concept is that the users will upload various pictures/video & a description to a page, and then the rest of the community will be able to 'like' it (not in a Facebook way, though). The pages with the most 'likes' will appear in the home page and various search/sideboxes (top rated by time/date, newest, most viewed, etc). For example, a user uploads a video and/or pictures of some artwork. He'll write a short statement about it and 'publish' it to the community. Once published, other users will be able to see it, comment on it, and rate it if they choose to. There are different categories for each type of upload (vocabularies, etc), as well as tagging, comments, etc.

Users can also 'follow' their favorite members to easily keep track of any new pictures/media they post, comments they make, etc. It would be fairly similar to the sites mentioned above.

My problem is that I just don't get where/how to go about doing this. I have designated various vocabularies, installed a few different gallery modules. I really don't think I want a gallery for this, as each 'project' a user uploads will be separate from all the others they upload (but it can still be found/visible in the author's profile page). Is there a module that pretty much does this functionality? Alternatively, is there a key concept that someone could explain to me on how to handle something like this? I could even pay a little bit to have someone set it up for me. However, I want to learn how to do it, so I can maintain the site later and build future sites in the same way.

# Answer
Surely you need Views, which allows you to create a view of specific nodes; if the users of your site are allowed to votes on the content, you probably want to offer a list of the most voted notes, or the less voted nodes.

As per rating a node, there are many modules that can be used. Part of them requires the Voting API module, such as Fivestar, Rate.
Which one to use depends on how the users are allowed to vote. The Rate module allows the users to up-vote and down-vote. With Fivestar, they are allowed to give a vote from 1 to X (where X is normally 5); they are not allowed to down-vote, which means the rate cannot be a negative number.

The Flag module allows the users to flag a node for a specific reason; by default the module comes with the "Add to my bookmarks" flag that can be, in your case, changed to "Add to my followed." Thanks to the integration with Views, Flag creates a view listing all the nodes flagged with a particular flag; such view can be per user, and in this case each user has a view for the nodes they flagged, which is visible as tab in their user profile, or it is global, and in this case the view is not specific for a user but every user can add nodes to that list.
> 2 votes

---
Tags: media, rating
---


# Question
Title: Newbie Simple D and Views question about grouping and "exclude from display"
First time Views project simple question about Views and a HTML list of nodes with Taxonomy term.

I have a basic list of nodes with shared taxonomy terms. The page displays all the nodes and taxonomy terms. When I add a group (under Style: HTML List), I see a new page element added duplicating the taxonomy term. Then, under fields is a checkbox, "Exclude from display" which has a description to suggest this fixes the duplicates when using groups.

Now all the data is excluded! None of the other Field items has this Exclude checked. Each time I made these updates the changes were made immediately. Still, I cleared the cache before posting this missive. Why is all my node data missing from the page with this one use of Exclude? Is this a bug?

# Answer
> 0 votes
What was the problem? After adding "Grouping", I mistakenly thought Filter might contain the Exclude solution. I added it. Then, I recall, clicking Remove, but evidently I did not, or whatever.

Next, I found the correct setting: "Fields: Exclude from display", and then saved. But, what I saw on my end-user page (not preview) between changes was, 1) Grouping take effect, 2) Filter do nothing, 3) Exclude make a "blank page". I'm thinking there are some changes which take effect on the end-user page right away and other that do not.

I'm going to try a new Views Development Workflow: 1) Export often, 2) Use save between each change, 3) Roll Back when things get weird. Repeat. And use the Preview instead of looking at my end-user page.

---
Tags: views
---


# Question
Title: how to get summary of content in following code
In my block code i have following code in one case:

```
$query = db_select('node', 'n');
    $query->condition('n.status', NODE_PUBLISHED);
    $query->condition('n.type', 'news');
    $nids = $query
    ->fields('n', array('nid'))
    ->orderBy('changed', 'DESC')
    ->range(0, 1)
    ->addTag('node_access')
    ->execute()
    ->fetchCol();
    $nodes = node_load_multiple($nids);
    $content = '<div class="white_rounded_box">
                    <div class="pos clearfix">
                        <h3><span><img src="'.base_path().path_to_theme().'/images/new_ico.png" width="15" alt="news" />Latest News</span></h3>';
    foreach($nodes as $record)
    {
        $content.='<p>'./*need summarry here*/.'</p>'.l('Read more', 'node/'.$record->nid);
    }
    $content .= '</div>
            </div>';
    $block['subject'] = t('Latest news');
    $block['content'] = $content;

```

How do i get summary of content in there?

# Answer
You'll need to look in `$record` in your `foreach` statement and find the content you want. (probably `$record->body`) Since you are polling the database manually (vs. using display\_modes like teaser / full) you'll probably have to create the summary yourself.

I suggest using the truncate\_utf8() function which "Truncates a UTF-8-encoded string safely to a number of characters.", it supports adding "...", word boundaries etc.

As for this "looking" into your `$record` var, I suggest using the Devel module, which ships with a function `dpm()` which can take basically any variable and output it in a pretty navigationable message on your page.
> 2 votes

---
Tags: 7, nodes, blocks
---


title: Create tab for related content types

text:
# Question
Title: Create tab for related content types
How do I link 2 content types (business, photo) together and able to display as a tab? is there a module for this?

# Answer
> 1 votes
Most simple way (i.e., without coding) would be to use Panels module, and create a node type view page override for the first content type. Then use a nodereference field to make the first content type reference a node of the second type. Lastly, use Panels' context system to generate a new context of that referenced node, and display it in whatever means you want on the overridden node view page.

---
Tags: views
---


title: Subscribe to issue queue

text:
# Question
Title: Subscribe to issue queue
In drupal.org I would like to get email notification when an issue that involves me is updated with a new comment. Right now I have to subscribe per project from URL http://drupal.org/project/issues/subscribe-mail/\[project-name\] by clicking "own issues" checkbox. This is pain. Sometimes I fail to subscribe to a project and I get no follow-up comments in email.

Is there a page where I can enable it globally to subscribe to all my own issues as against doing it for individual project ?

# Answer
> 3 votes
There was a page that would allow you to subscribe to different projects, but it has been removed.
The only way to subscribe to project issue queues is the one you described.

The link to subscribe to the issue queue of a project is present in two places:

* in the project page, in a block to the right side
* in the project issue queue, under the issue queue title

---
Tags: community-official-site
---


# Question
Title: Change the e-mail value during user registration ?  form_set_value()
I have a custom module (entitled ta\_module) : in the user registration form, it hides the e-mail field, and add a custom field where user have to enter what's before @ and then choose his e-mail domain name between the one proposed in a list next to it.

Here's the code :

```
<?php

/**
 * Implementation of hook_form_alter()
 */
function ta_module_form_alter(&$form, &$form_state, $form_id) {

   // If the form is the user_register form
    if ($form_id == 'user_register_form') {
        // Attach our custom validation function as the first validation function
        array_unshift($form['#validate'], '_ta_module_user_validate');
        // Hide the email address field
        $form['account']['mail']['#type'] = 'hidden';
        // Give the email address field a random default value (in this case a random number and a timestamp)
        // as we cannot unset it due to Drupal's validation rules
        $form['account']['mail']['#default_value'] = rand(1111, 9999) . '@' .time() . '.com';
        // Add our new text entry field
        $form['mail_first'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#default_value' => '',
      '#size' => 35,
      '#maxlength' => 64,
      '#required' => TRUE,
    );
        // Add our select list of possible email domain values
        $form['mail_last'] = array(
      '#type' => 'select',
      '#title' => 'Domaine',
      '#title_display' => 'before',
      '#options' => array(
              // These are the possible email address domains
              'myentreprise.net' => '@myentreprise.net',
              'myentreprise.com' => '@myentreprise.com',
            ),
      '#default_value' => 'myentreprise.net',
      '#required' => TRUE,
    );
    }
}

/**
 * Function to piece together our email address
 */
function _ta_module_user_validate(&$form, &$form_state) {
    // If our two form elements have values
    if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
        // Set the email address to the correct value
        $form_state['complete form']['account']['mail']['#value'] = $form_state['input']['mail_first'] . '@' . $form_state['input']['mail_last'];
    }
}

```

(see This Q/A for more infos).

All appear quite brightly, but when the user click on "create a new account", the user is created but the last function of my module doesn't work : the e-mail finally saved is the default value (something like 0129A@I1I101IZ10IZ.com) instead of the two pieces joined together...

**HOW TO FIX THIS : Thus how to assign to mail the value of mail-first + mail-last ?**

/!\ I'm working on Drupal 7, so I think it's an issue of uncorrect variables...

Thks for reading ! ;)

# Answer
> 3 votes
If you need to set the value for the form field used to contain the email address, then you should use code similar to the following one:

```
function _ta_module_user_validate(&$form, &$form_state) {
  if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
    form_set_value($form['account']['mail'], $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'], $form_state);
  }
}

```

As an example of how `form_set_value()` is used, see system\_site\_information\_settings\_validate(), which contains the following code:

```
// Check for empty front page path.
if (empty($form_state['values']['site_frontpage'])) {
  // Set to default "node".
  form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
}
else {
  // Get the normal path of the front page.
  form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
}

```

# Answer
> 2 votes
Instead of

```
$form_state['complete form']['account']['mail']['#value'] = $form_state['input']['mail_first'] . '@' . $form_state['input']['mail_last'];

```

Try using the form\_set\_value() function. Documentation says:

Use this function to change the submitted value of a form element in a form validation function, so that the changed value persists in $form\_state through to the submission handlers.

---
Tags: 7, forms, users, emails
---


# Question
Title: Create link with 'name' attribute only using l() function
Is it possible to create a link using Drupal's l() function without an href? For example, I'd like to create a link like the following:

```
<a name="my-anchor">A link here</a>

```

However, this seems to not be possible. The closest I can come is to use the following:

```
l(t('A link here'), '', array('external' => TRUE, 'attributes' => array('name' => 'my-anchor')));

```

This outputs:

```
<a href name="my-anchor">A link here</a>

```

... and that's not valid HTML. It also causes slightly strange behavior in some browsers depending on the CSS applied...

# Answer
Sadly this cannot be accomplish with the  function because the href is hard-coded in the theme\_link theme function.

You can accomplish this by using the html\_tag theme function.

It'll look something like this

```
return theme('html_tag', array('element' => array('#tag' => 'a', '#value' => 'A link here', '#attributes' => array('name' => 'my-anchor'))));

```

This will return

```
<a name="my-anchor">A link here</a>

```

Is a bit more work, but it does give you a properly formatted a tag with out the href.
> 6 votes

# Answer
It cannot be done with l() only, since the href attribute is hard-coded in theme\_link().

You could, however, override this them function, and add an extra key to the options array (something like 'anchor' =\> TRUE').
> 3 votes

# Answer
I don't believe you can create an `<a>` tag with Drupal without the `href` attribute. Doing so would be invalid HTML as `href` is a required attribute for `<a>` tags so it is not something I would suggest doing anyways.

Why don't you create a tag with `href="#"`or something similar?
> 0 votes

---
Tags: navigation
---


# Question
Title: Remove superfluous divs from views fields output?
I've set the Wrapper HTML Element option to none, and removed any wrapper divs in the templates presented in Theme Information, but my image fields are still getting wrapped in plain divs.

# Answer
There are several ways to strip HTML. You can under rewrite results Strip HTML tags or under style settings Customize the HTML. If you have tokens enabled you can exclude a bunch of fields then add a Global text markup field. Most of the wrapping markup will be removed and you can use the your own markup or not by typing HTML into the Global text field placing the placeholder tokens where in the HTML the field should be rendered. Another way to clean up Views markup is to create override theme templates by clicking on theme templates for the theme override template title and copying the default code changing anything you don't want in them before you save.
> 2 votes

# Answer
From the looks of things, you're using D7/Views 3.x... For 2.x, there's an excellent Views companion module, Semantic Views, that enables this kind of functionality.

And, yes, it's often a bit confusing as to which setting in the Style options of a views field will turn on or off which HTML element... Hopefully the ux for that improves over time.
> 2 votes

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


title: Moving custom content types and content

text:
# Question
Title: Moving custom content types and content
I'm rebuilding a Drupal 6 site in Drupal 7. So much needs to change, it doesn't seem worth trying to upgrade, so I'm starting from scratch.

I would love to know if there is an easy way to export all of my content. I have about 1000 nodes of two different custom content types. Is there a module to do this? If not, I guess I just have to sit down and figure out how data is stored in the database in both versions?

Thanks

# Answer
Both Feeds and Migrate are modules purpose-built for what you'd like to do. Migrate requires a little more coding at this point, but I like its ease of use a little more than Feeds.

Simply upgrading the site, using CCK for Drupal 7 to migrate your fields and content types, might be a better solution, though. I would create a backup copy of your site and at least give it an hour's worth of trying before resorting to a full-on content migration.
> 1 votes

# Answer
You can upgrade the site which should give you the nodes and content\_types. The content types can then be exported with features while the actual nodes can be moved by moving the nodes table or if you have fields, load all the nodes from the upgrade db and insert them into the new db.
> 0 votes

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


# Question
Title: OG how to contrain a group to a maximum number of users
I would like to restrict groups to a certain amount of members. Is there any ways to do so?

# Answer
Organic Groups join limit This module allows to set a join limit on a specific group.
> 2 votes

---
Tags: organic-groups
---


# Question
Title: What is the best way to retrieve the current menu object, regardless of it's type?
When you call menu\_get\_object(), the first argument defaults to 'node' if no arguments are passed to the function. The code uses the $type variable to check if the current object is of that type, using `$router_item['load_functions'][$position] == $type . '_load'`.

Sometimes, I just want to get the current menu object, regardless of it's type. In other words, when I'm looking at user/123, I want the user object, and when I'm viewing node/456, I want the node object.

Why does menu\_get\_object force a single entity type?

What is the best way to retrieve the current menu object, regardless of it's type?

# Answer
> 3 votes
As you can see in that function, it does nothing more than:

```
$router_item = menu_get_item($path);
return $router_item['map'][$position];

```

However, I'm not sure how that will help you, for pretty much all objects, you need to know what it is to work with it as there are just some attributes.

# Answer
> 0 votes
```
if (arg(0) == 'node') {
  $node = menu_get_object();
}
else if (arg(0) == 'user') {
  $user = menu_get_object('user');
}

```

:) or try this:

```
  $obj = menu_get_object(arg(0));

```

although that won't work in a url like this: `http://URL/some_arg0/REQUIRED_OBJECT/some_arg2`

---
Tags: 7
---


# Question
Title: Where do I place custom PHP code (functions, classes) when creating a theme?
WordPress has a place for it - functions.php, which is included automatically. Is there one for Drupal?

# Answer
> 5 votes
The theme's template.php is used for logic and data processing. See the Drupal theming guide.

From the guide:

> For all the conditional logic and data processing of the output, there is the template.php file. It is not required, but to keep the .tpl.php files tidy it can be used to hold preprocessors for generating variables before they are merged with the markup inside .tpl.php files. Custom functions, overriding theme functions or any other customization of the raw output should also be done here. This file must start with a PHP opening tag "`<?php`", but the close tag is not needed and it is recommended that you omit it.

---
Tags: theming
---


# Question
Title: Exclude a .js file on certain Drupal 6 paths
I've run into a dilemma with Drupal and SSL.

I'm utilising the Disqus module, however, Drupal loads the Disqus .js files on all pages including the cart and checkout addresses. This would be fine except that it includes non-secure paths to external JS files that contain more non-secure paths, which means that browsers show SSL errors.

I'm trying to find some way to just exclude these .js files on particular paths. I've seen information on excluding files entirely or including them, but not just from these path's.

Any help would be greatly appreciated, thanks!

# Answer
I think that this module spits out the reference to the JS file inline in the content. If this is true, then I would use some logic inside template\_preprocess\_page to determine whether you are on an HTTPS path, and then search/replace `$vars["content"]` and remove the string. You may also be able to use template\_preprocess\_comment\_wrapper to do the same thing.

This solution is pretty hackish, but I think it may be your only solution short of patching the module.
> 2 votes

# Answer
You can utilize `hook_preprocess_page` like in this thread.
But i'm not sure if `drupal_add_js` works with external js in D6. Check out this thread if it doesn't.
> 1 votes

---
Tags: ssl, ubercart
---


# Question
Title: updatedhow to set default value in a form field got from another page(form)?
All,

What I want to do: On the Home page, I have an input field in which a user can insert their invite code, the invite code gets validated via ajax and if correct, popups the registration form. Its important that the user cannot get access to the registration form without the correct invite code. How can I bullet proof this concept into my Drupal7 install? I am using Regcode module for registration purpose.

The problem I have is that if the user knows the address to the registration form, they can merely enter that into the browser's address bar and register without having to gain an invite code.

One solution I thought was that the invite code is needed on the actual registration form as well, so if they do access the form via the browser's address bar, they will still need to input the invite code. However, if they already did place the invite code in the input field (on the Home page), it would automatically populate the invite code field in the registration form.

What problem I am facing: Im not sure how to go about transferring the invite code (which the user inserted) into the registration form that pops up upon validation. The form(single field) on the front page is written by myself inside a block.

Here i am confused how to take the form value to the registration form and how to get the value of field and after getting how to set the value as default in the regcode text field.

```
 <form method="GET" action="?????"></form>

```

the modulea's part which alter the registration form is as follows

```
 function regcode_form_user_register_form_alter(&$form, &$form_state) {
  $code_optional = variable_get('regcode_optional', FALSE);
  $account = $form['#user'];

  $form['regcode']['regcode_code'] = array(
    '#type' => 'textfield',
    '#title' => variable_get('regcode_field_title', t('Registration Code')),
    '#description' => variable_get('regcode_field_description', t('Please enter your registration code.')),

    '#default_value' => ???????????,

    '#required' => !($code_optional || user_access('administer users')),
    '#element_validate' => array('regcode_code_element_validate'),
  );
  // Capture the code from the url and inject it into the registration form
  if (isset($_GET['regcode'])) {
    $form['regcode']['regcode_code']['#value']       = check_plain($_GET['regcode']);
    $form['regcode']['regcode_code']['#description'] = NULL;
    $form['regcode']['regcode_code']['#disabled']    = TRUE;
  }
}

```

i Hope, its understandable now

# Answer
> 1 votes
Drupal doesn't store the form state between forms, so you will need to do that yourself.

In this case I would use the session variable since you want to save it per user, but not permanently.

To do this you will need to add a custom submit handler to the form if you form is not created by you, this can be done with `hook_form_alter`

Then you can save the value you want to save in the session variable something like

```
 $_SESSION['my_value'] = $value;

```

should do the trick, then you can set the value in the form, either directly if you control it or via form alter.

That the form value is gotten from or is to be set to a field doesn't change things. The form field structure is a little more verbose, but the way to do it is pretty much the same.

# Answer
> 0 votes
Maybe try looking at the Contextual Administration module. I have personally not used it but it was described to me in way that it seems pertinent to the situation you are describing (I may be wrong though)

---
Tags: forms
---


# Question
Title: Using select expressions or derived field in Views2 as fields?
Is it possible to use a select expression or a derived field as a field in Views2 in Drupal 6?

The advanced help documentation seems to indicate that perhaps it is possible:

> though it is very common to use non-fields to display data that isn't directly in a field, such as data arrived from formulae...

But they don't provide examples there.

What I mean is I'm looking for some way to indicate that the query should be

```
SELECT field1, CONCAT(field3, ', ', field4) AS alias1, IF( field5 > 10, 1, 0) AS alias2 FROM table ...

```

Can I specify the expressions `alias1` and `alias2` in native views2 functionality? If so, what is the syntax?

Or do I need a separate module?

# Answer
> 2 votes
It looks like what I need to do is create a Custom Field Handler. From the linked article, a definition such as this

```
<?php
class scheduler_handler_field_scheduler_countdown extends views_handler_field {
  function query() {
    $this->ensure_my_table();
    $this->node_table = $this->query->ensure_table('node', $this->relationship);
    $this->field_alias = $this->query->add_field(NULL,
      'IF(publish_on AND publish_on > UNIX_TIMESTAMP(),
        publish_on - UNIX_TIMESTAMP(), NULL)',
      $this->table_alias . '_' . $this->field);
  }
}
?>

```

adds this to the query

```
SELECT node.nid AS nid,
       node.title AS node_title,
       IF(publish_on AND publish_on > UNIX_TIMESTAMP(),
           publish_on - UNIX_TIMESTAMP(),
           NULL) AS scheduler_publish_countdown
    FROM node node
    LEFT JOIN scheduler scheduler ON node.nid = scheduler.nid
    WHERE node.status = 0

```

---
Tags: views, 6
---


# Question
Title: altering form with hook_form_FORM_ID_Alter
```
function dental_form_simplenews_block_form_2_alter(&$form, &$form_state, $form_id)
{
    global $user;
    $form = array();
    $form['#attributes'] = array('class' => array('newsletter'));
    /*$form['subscribe'] = array(
        '#type' => 'fieldset',
        '#title' => '',
        '#weight' => 5,
        '#collapsible' => TRUE
    );*/
    if ($user->uid) {

    }
    else {
        $form['mail'] = array(
            '#type' => 'textfield',
            '#title' => t('Email'),
            '#size' => 20,
            '#maxlength' => 128,
            '#required' => TRUE,
            '#attributes' => array('class' => array('text_ip')),
        );
        $submit_text = t('Subscribe');
        $form['action'] = array(
          '#type' => 'value',
          '#value' => 'subscribe',
          '#attributes' => array('class' => 'submit'),
        );
    }

    return $form;

}

```

Above is the code i am using to alter form produced by simplenews plugin. But i am getting various error messages.

```
Notice: Undefined index: #parents in form_builder() (line 1713 of /home/sjd/www/example.com/includes/form.inc).
Warning: implode() [function.implode]: Invalid arguments passed in form_builder() (line 1713 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #tree in form_builder() (line 1743 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #array_parents in form_builder() (line 1766 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: process_input in _form_builder_handle_input_element() (line 1904 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: complete form in form_builder() (line 1723 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #tree in form_builder() (line 1743 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: #array_parents in form_builder() (line 1766 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: process_input in _form_builder_handle_input_element() (line 1904 of /home/sjd/www/example.com/includes/form.inc).
Notice: Undefined index: process_input in drupal_process_form() (line 817 of /home/sjd/www/example.com/includes/form.inc).

```

Can anybody tell me where i am going wrong.

# Answer
> 4 votes
You shouldn't reset the form completely by doing `$form = array();`, since you will delete some of the stuff Drupal expects to be there.

You should instead do something like this:

```
function dental_form_simplenews_block_form_2_alter(&$form, &$form_state)
{
    global $user;
    // Remove what you don't want..
    unset($form['fields']);
    // Add what you do want..
    $form['#attributes'] = array('class' => array('newsletter'));
   ...
}

```

---
Tags: forms
---


# Question
Title: Limiting allowed HTML tags in comments only
I can't figure out how I can limit my text format or HTML codes for the comment sections on a node. If I edit the input formats with user roles, it edits the entire thing, including the node body and other fields.

For example, I want to have filtered text on the body field of a node, but only plain text (or other custom text format) in the comments section.

The problem I'm running into is that I have added `<embed>`, `<param>`, `<iframe>`, `<object>` into the allowed HTML tags field in my filtered text format settings, but this also allows users to post Youtube videos into the comments section, and I don't want that.

How can I do this?

# Answer
> 3 votes
You need to create two "Filtered Text" formats, one that is used by people with the access to post nodes and one for comments.

If you can't separate the two forms by access control (e.g. users are allowed to post nodes and comments, but shouldn't be allowed to post videos in comments), you could use `hook_form_alter()` in a custom module to limit the allowed filters for the comment form.

---
Tags: forms, input-formats
---


title: Search for terms by name in admin panel

text:
# Question
Title: Search for terms by name in admin panel
Right now I only see a way to list all the terms of a particular taxonomy in the admin panel. I have to go through pages of terms if I want to locate a term I want to edit. How can I search by a term's name?

# Answer
You can create view for your needs. Access only to admin role and pin it to "Default Shortcuts" menu.
> 1 votes

# Answer
Try Taxonomy Manager
> 0 votes

---
Tags: 6, taxonomy-terms
---


title: Initial Aegir Setup

text:
# Question
Title: Initial Aegir Setup
This might be a dumb question, but the Aegir install instructions do not mention installing Drupal first. I am wondering if that matters at all?

Should Drupal 6 be installed separately from Aegir, and in what location? Sorry if this is obvious, but perhaps I am missing something small?

Thanks,

KM

# Answer
> 3 votes
There are two ways to install Aegir, the (recommended) automated way using a debian package or the manual (though mostly automated still) method. Both methods take care of downloading and installing Drupal 6 and all needed contrib modules and other libraries.

---
Tags: multi-sites, aegir
---


# Question
Title: Adding nodes to term instead of terms to nodes
Is there a way to easily add nodes to terms? In other other words, let's say I have a taxonomy called top 5 sellers and I have a collection of nodes that represent books.

Currently it's hard to manage something like that because I have to search and find each book, and then assign the taxonomy term to it. I'm looking for a way to do it 'the other way around' where I have a gui that lets me choose a taxonomy and then choose nodes to add and subtract to it.

I hope that is clear. Any ideas?

# Answer
> 1 votes
Try Views Bulk Operations

# Answer
> 1 votes
I've had a look around and I'm surprised I've not been able to find what you're looking for. It seems like functionality that people would want. The best I've been able to find is programmatically adding a node to a term. I'm not sure of your experience but if you've built any modules before, it probably wouldn't be too much of a task to add a user interface to this bit of code and develop your own module to do what you want to to (and then publish it on d.o for the rest of us :))

---
Tags: 6, taxonomy-terms
---


title: Block region not outputting anything?

text:
# Question
Title: Block region not outputting anything?
I have this on my template:

```
  <?php print render($page['left']); ?>

```

And no matter how many blocks I add to the left sidebar region, nothing prints.

Any ideas?

# Answer
> 1 votes
Ah. Finally figured it out. The Left Sidebar is actually called sidebar\_first. DSM'ed the $page variable.

---
Tags: 7, blocks
---


# Question
Title: How do I change html structure of menu (primary links for example) to my own?
The default HTML structure of the primary links menu is not what I'd like it to be. How can I override it with my own version?

# Answer
I am assuming you are working with drupal6 and you have basic understanding of variables and arrays. Default html structure of the primary links is formed at different places in drupal. First if you start with the wrapping div id, in your theme's page.tpl.php file where you print $primary\_links change it as the following example:

```
 <div id="dk_one">
 <?php print theme('links', $primary_links, array('class' => 'links primary-links dk_two')) ?>
</div>

```

In order to change what is in $primary\_links use the following code in template.php file of your theme.

```
    function yourThemeName_links($links, $attributes = array('class' => 'links')) {
  $output = '';

  if (count($links) > 0) {
    $output = '<ul' . drupal_attributes($attributes) . '>';

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

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

      // Automatically add a class to each link and also to each LI
      if (isset($link['attributes']) && isset($link['attributes']['class'])) {
        $link['attributes']['class'] .= 'dk_three ' . $key;
      }
      else {
        $link['attributes']['class'] = $key;
      }

      // Add first and last classes to the list of links to help out themers.
      $extra_class = '';
      if ($i == 1) {
        $extra_class .= 'first dk_four ';
      }
      if ($i == $num_links) {
        $extra_class .= 'last dk_five ';
      }
      $output .= '<li ' . drupal_attributes(array('class' => $extra_class . $class)) . '>';

      // Is the title HTML?
      $html = isset($link['html']) && $link['html'];

      // Initialize fragment and query variables.
      $link['query'] = isset($link['query']) ? $link['query'] : NULL;
      $link['fragment'] = isset($link['fragment']) ? $link['fragment'] : NULL;

      if (isset($link['href'])) {
        $output .= l($link['title'], $link['href'], $link['attributes'], $link['query'], $link['fragment'], FALSE, $html);
      }
      else if ($link['title']) {
        //Some links are actually not links, but we wrap these in <span> for adding title and class attributes
        if (!$html) {
          $link['title'] = check_plain($link['title']);
        }
        $output .= '<span' . drupal_attributes($link['attributes']) . '>' . $link['title'] . '</span>';
      }

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

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

  return $output;
}

```

Clear your cache and you will see dk\_one dk\_two dk\_four dk\_five div ids and classes in your html structure of your primary menu. Please let me know if it works for you.
> 2 votes

# Answer
In drupal 7 it can be found at admin/structure/menu/settings and in Drupal 6 it can be found at admin/build/menu/settings
> 1 votes

# Answer
Take a look at theme\_menu\_tree, theme\_menu\_item\_link and theme\_menu\_item. Override these functions in your template.php file.
> 1 votes

---
Tags: theming, routes
---


title: How to set up a Drupal 7 forum

text:
# Question
Title: How to set up a Drupal 7 forum
I have installed the core Forum module in Drupal 7. When I go to:

```
http://www.mysite.com/?q=forum

```

The forum list is displayed, however the links that allow me to post are not being displayed.

I'm surprised that I haven't been able to find a tutorial on the net on how to set up a Drupal 7 forum.

What am I doing wrong?

# Answer
> 3 votes
Your theme is probably not presenting the new action links in D7. In a default install of D7 and forum (using Bartik theme) I can see them. See http://definitivedrupal.org/suggestions/action-links for an explanation.

---
Tags: 7, nodes
---


# Question
Title: Which should I use and when: node_load() or entity_load()?
Title says it all.

I understand that entity\_load provides a performant and efficient means to load multiple nodes whilst reducing database queries, so I presume in that instance I should be using entity\_load(). But when I just want one node, which should I use? And will node\_load() be deprecated in d8 in favour of the more generic entity\_load() api?

I guess the same question goes for the familiar user\_load() too.

# Answer
> 33 votes
`node_load` is just a fancy wrapper for `entity_load`.

That is `node_load` calls `node_load_multiple` which is a wrapper for `entity_load`. This means that performance wise there isn't really much of a difference, which function you use, unless you have to load a lot of nodes.

`node_load` has many advantages over `entity_load`

* It's simpler
* It increases code readability
* it returns the node object instead of an array with the node object(s)

So in all, `node_load` is a convenience that you always should use whenever possible, then resort to `node_load_multiple` for cases where you need to load many more nodes.

`entity_load` should be used for loading entities when you don't know the type, or have it stored in a variable, in which case you can do

```
entity_load($type, ...);

```

# Answer
> 9 votes
Use node\_load() when you have a single node to load and node\_load\_multiple() when you have more of them. Use entity\_load() directly when you don't know the entity type in advance, for example `entity_load($type, array($id))`.

Note that entity\_load() is inconsistently named, it should actually be entity\_load\_multiple(), as it allows to load multiple results and returns an array of results.

# Answer
> 5 votes
`node_load()` is the function that existed before the entity API was introduced in Drupal 7. The difference with `entity_load()` is that it accepts parameters that are specific for the loading a node object, such as `$vid`. The function calls `node_load_multiple()`; it is helpful for compatibility reason, and because it requires less parameters.

```
$node = node_load($nid);

```

```
$nodes = entity_load('node', array($nid));

```

In Drupal 8, `node_load()`, `node_load_multiple()` and `entity_load()` are deprecated. This they are removed when Drupal 9 will have its stable release).
Furthermore, in Drupal 8 calls to those functions need to be changed, since in Drupal 8:

---
Tags: entities
---


# Question
Title: Ajax User login failing with "Username field is required", "Password field is required"
I am trying to set up an AJAX login box for a site, using the following code:

```
function THEME_form_user_login_alter (&$form, &$form_state) {
   $form['actions']['submit']['#ajax'] = array(

        'callback' => 'user_login_submit',
        'wrapper' => 'user-login',
        'effect' => 'fade',
        'speed' => 'fast',
        'method' => 'replace',
    );
}

```

I get an Ajax error on form validation, I am thinking I am using the wrong callback but I can't figure out which one would work, and I couldn't find any example out there.. Any suggestion?

This is the error message:

> An AJAX HTTP error occurred. HTTP Result Code: 200
> Debugging information follows.
> Path: /parce/system/ajax
> StatusText: OK ResponseText: \[{"command":"settings","settings":{"basePath":"/parce/","pathPrefix":"","ajaxPageState":{"theme":"parce","theme\_token":"PFPo8K2w-7tUSndM3muIGW4Gpq-X8TT4-fR4ZmVcxD0","css":\[\]}},"merge":true}\]
> Uncaught exception thrown in session handler.
> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048
> Column "uid" cannot be null:
> INSERT INTO {sessions} (sid, ssid, uid, cache, hostname, session, timestamp) VALUES
> (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6);
> Array(
> \[:db\_insert\_placeholder\_0\] =\> -nLyLCVNED-8LSAd6NoZ8znhzZAoUVMNutGmi7ObAQ8
> \[:db\_insert\_placeholder\_1\] =\>
> \[:db\_insert\_placeholder\_2\] =\>
> \[:db\_insert\_placeholder\_3\] =\> 0
> \[:db\_insert\_placeholder\_4\] =\> 183.16.201.97
> \[:db\_insert\_placeholder\_5\] =\> messages|a:1:{s:5:"error";a:2:{i:0;s:27:"Username field is required.";i:1;s:27:"Password field is required.";}}
> \[:db\_insert\_placeholder\_6\] =\> 1308899744
> ) in
> \_drupal\_session\_write() (line 203 of /home/sites/parce/includes/session.inc).

# Answer
> 4 votes
It looks like `user_login_submit` doesn't work well when called as an AJAX callback. The error you receive is because Drupal tries to create a session for the user that should be logged in, but no values for uid is present, which is required.

I believe that Drupal will call the form submit hooks when the form is submitted by ajax, so you might be able to simply add an empty callback function.

Alternatively you will need to call the form submit functions yourself, which should fix the problem.

# Answer
> 2 votes
As googletorp mentioned, submit functions are *not* ajax callbacks.

An ajax callback is a function that returns the part of the form that should be displayed withing the given specified wrapper or executes so called ajax commands (http://api.drupal.org/api/drupal/includes--ajax.inc/group/ajax\_commands/7)

See also http://api.drupal.org/api/examples/ajax\_example--ajax\_example.module/7

---
Tags: forms, ajax, users
---


# Question
Title: Passing node parameters into views block
I am on Drupal 7.

I have two content types. Content type 1 is called Bulletin and content type 2 is called Bulletin Text. I have a node reference field in Bulletin Text content type that allows me to link it to a certain Bulletin object.

Now, when my user is on a Bulletin Text node I want him/her to:

1. see all the other texts associated with that same Bulletin on a block to the side of the page;
2. remove the current Bulletin Text node from the list of bulletin texts, as it wouldn't make much sense, as the block would be something like "other texts from in this Bulletin".

Is there a pure Views solution for receiving the nodereference value from the current node being displayed on the page (passing that parameter into the Views block) and showing the list of nodes associated with it (also removing the current nid from the list), or do I have to play around with Contexts, Panels or custom code? What do you consider the best approach for me to solve this?

# Answer
> 1 votes
I can't give you the complete Views-based solution off the top of my head (although I think it must be possible) but the key to the solution is using 'Contextual filters' (they used to be called 'Arguments' in D6/Views2) and relationships.

Contextual filters are filters that take their value from the url, so you can narrow down the results to the current node currently. By adding a relationship for the node reference field, you can retrieve information from the nodes referenced by that field.

If I'm not mistaken, you can add a second contextual filter that makes use of the relationship, to exclude the current node from the related nodes.

Sorry this is not a complete how-to, but I hope it gets you started.

# Answer
> 1 votes
There is an issue for this: http://drupal.org/node/1083902 it allows you to use a relationship in views to load the other end of the reference.

Together with the relationship and one contextual filter and "exclude" argument in the contextual filter you can do it.

---
Tags: nodes, views
---


title: AJAX in a calendar view block

text:
# Question
Title: AJAX in a calendar view block
I have a month-view calendar block and would like to change months without page reload. How can I achieve it?

# Answer
> 1 votes
I've used FullCalendar instead (following Jody's comment - thanks!). It does everything I need. Here is a quote about it (from the module's project page):

> Provides a Views display, style and row plugin for displaying nodes using Adam Shaw's FullCalendar jQuery plugin.

# Answer
> 2 votes
This has been coming to Calendar for a while now, and I believe is currently in dev (issue queue). Having said that, I notice that fullcalendar has 666 sites using it, so it might be good to increase that number and make it less devilish :)

---
Tags: 7, views
---


# Question
Title: Ecommerce site with square area calculation in price
I am currently looking to make a shop selling carpets. For this I need to use a system that calculates a price per Square area. I have seen Posts where people are in the same position as I am but had no feedback. Is Magneto the answer or Ubercart Druple 6 or 7. I am a developer with no Drupal experience and I am using this as an introduction to Drupal.

Any advice for the best solution would be much appreciated.

# Answer
I strongly recommend you get some formal instruction, such as the book "Pro Drupal Development" or "Front End Drupal" as well as get accounts at BuildAModule.com and/or Drupalize.me to get a deeper look into Drupal. The decision is ultimately one where you need to figure out your own level of technical competence - creating an eCommerce web site is complex, with legal ramifications if you screw up. So, this is serious.

Magneto is a good platform, but they just got bought by eBay, and in my mind that places their structure (support, UI, community) in an uncertain position. Drupal's not going anywhere but up.

I suggest you create one or two non-eCommerce Drupal sites first, just to learn the environment. Do this on your local machine, so you get personal experience with where files go, their organization, how to add and remove AND update modules. How to configure a what-you-see-is-what-you-get editor, and so on. These are all essential Drupal skills that take time to develop; not a huge amount of time, but time none-the-less that you NEED to spend before you take on the larger and more serious task of creating your online store. After that, move one of your web sites to an online host; forcing you to learn how to manage and maintain a remotely hosted Drupal site. Another essential skill you do not want to be developing with live customers.

Frankly, I would never recommend creating an online store as your first exposure to any eCommenrce environment. You need to be familiar with the CMS first, to insure you are not doing basic entry-level mistakes; such mistakes in a live online store could bankrupt you, land you in jail, or even expose your customers to massive credit card fraud.
> 2 votes

---
Tags: ubercart, commerce
---


# Question
Title: Change the amount of content displayed per page in Content Management -> Content
I'm trying to do a CSV export of all my content, but it only shows 50 per page and I have 50+ pages. I want to be able to check all and export as one csv. Is there a way to change the pagination settings for Content Management -\> Content?

# Answer
Use Views to generate a list of all your contents, create a new view of type node, add fields what you like, then use Views Bonus Pack to export content list as CSV.
> 1 votes

# Answer
You can create a view and directly export that as CSV with Views Bonus Pack.

However, with 50 * 50 nodes, you might run into memory problems if you try to display them all on a single page.
> 0 votes

---
Tags: 6, nodes, importing-exporting
---


# Question
Title: What causes the error "Call-time pass-by-reference has been deprecated?"
My understanding is that objects in PHP 5.3 are all passed by reference so using the &$ notation is not necessary. My problem is using date\_views module where I'm getting this error.

```
Deprecated function: Call-time pass-by-reference has been deprecated in
 _registry_check_code() (line 2701 of C:\wamp\www\cruzr\includes\bootstrap.inc).

```

The affected lines of the code are:

```
  // $type is either 'interface' or 'class', so we only need the first letter to
  // keep the cache key unique.
  $cache_key = $type[0] . $name;
  if (isset($lookup_cache[$cache_key])) {
    exit;
    if ($lookup_cache[$cache_key]) {
      require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
    }
    return (bool) $lookup_cache[$cache_key];
  }

```

How do I test if a variable is passed by reference? With several classes being loaded how do I approach debugging this problem?

# Answer
The cause of the "Call-time pass-by-reference has been deprecated in \_registry\_check\_code()" is a file that holds a class being loaded that contains a variable that is passed by reference that is not in a function definition.

Drupal 7 requires PHP 5.2 or higher and PHP 5 always passes objects into functions by reference

This was a difficult bug to find because enabling a feature of the Date Views module is what triggered it. However, the problem was in the Workbench Moderation module. What I did was set the breakpoint in the debugger on function drupal\_set\_message() then worked back through the call stack till I found the offending variable.

Problem was not exactly in the Date module but was nonetheless triggered by the Date module in line 53 of date\_views\_fields.inc.

```
// If we don't have a filter handler, we don't need to do anything more.
if (!$handler = views_get_handler($table_name, $field_name, 'filter')) {
  continue;
}

```

This would iterate through all the view's handlers including workbench\_moderatioin\_handler\_filter\_user\_can\_moderate which passed a variable by reference not in a function definition, parent::options\_form(&$form, &$form\_state);. Simply the Workbench moderation module needs to be patched to reflect changes in code in PHP 5.3
> 2 votes

---
Tags: debugging
---


# Question
Title: Can region be defined outside of the theme's .info file?
Basically I'm trying to reverse-engineer a theme that was developed by another guy. The problem is that I'm not yet quite firm on Drupal ground.

So I'm looking onto a management page for blocks and see a specific region, which is not defined in theme's .info file...

Can regions be defined elsewhere? Or inherited from somewhere else (another theme maybe)?

**UPDATE**: Since to inherit something this should be a sub-theme, which should be denoted by:

> base theme = themeName

line in *themeName.info* file. But there is no such line in this theme... :( This undefined region should be coming from somewhere else...

# Answer
> 1 votes
Ok, it turned out that it was the region defined in .info file after all. It's just that Drupal I was working with was using different language pack and simply silently translated region names were it could. That's what confused me - one region got translated and the rest stayed intact.

Might be useful for someone hitting the same problem.

# Answer
> 2 votes
Drupal 7 has 5 default regions:

* regions\[sidebar\_first\] = Left sidebar
* regions\[sidebar\_second\] = Right sidebar
* regions\[content\] = Content
* regions\[header\] = Header
* regions\[footer\] = Footer
* regions\[highlighted\] = Highlighted
* regions\[help\] = Help

Regions aren't inherited by parent themes: https://drupal.org/node/225125.

If I'm not mistaken you used to be able to define regions in theme\_region(), but I believe that's no longer being used.

---
Tags: theming, .info
---


# Question
Title: Inserting Fields from A Custom Content Type into Custom Form
I created a custom content type called 'Building Location' that contains a custom field called 'US\_States'.

Is there a way I can access and include the 'US\_States' field into a custom form I'm building without having to re-create it with the Form API?

I'm looking to include the same drop down list, 'US\_States,' from the 'Building Location' content type in a custom form that is part of a module I'm building, ensuring the two will always have the same options available.

# Answer
> 1 votes
There isn't an API for attaching a single field from an entity to a form, there is one to attach all fields. `field_attach_form`. I wouldn't suggest you doing that do, since it can quickly become unmaintainable.

Instead I would suggest that you simply get the field options, or allowed values as they are called. That is pretty simple as well.

```
$info = field_info_field('field_machine_name');
$options = $info['settings']['allowed_values'];

```

---
Tags: 7, forms
---


title: How to render the form tag

text:
# Question
Title: How to render the form tag
I am using this code to make the user\_profile\_form available on my user-profile.tpl.php so the user profile filed can be edited directly from the sure page.

```
function parce_preprocess_user_profile(&$variables) {
  $variables['user_edit']  = drupal_get_form('user_profile_form', menu_get_object('user'));
}

```

Then, I can correctly print them individually using this code:

```
<?php print drupal_render($user_edit['account']['mail']); ?>

```

It works fine, but the problem is that the `<form>` tag doesn't appear on the page, and the form doesn't submit. When I add it manually in the template page, it works, but I was wondering how to get Drupal to insert these tags automatically.

I tried something like this (out of pure guess):

```
function parce_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'profile_edit',
      'template' => 'user-profile',
    ),
  );
}

```

It doesn't work. Am I doing anything wrong?

# Answer
> 0 votes
I didn't find a way around that; I ended up printing the form tag manually.

# Answer
> 2 votes
You have to render the full form, so `drupal_render($user_edit)` is needed.

---
Tags: theming, users
---


# Question
Title: With several user profile pages built in Views as tabs, how do I build a menu linking to those pages?
I can't just use the menu UI to create menu links because the links need to be dynamic. The best solution I have found so far is in OpenAtrium. Are there any others?

```
   $block['content'] .= "<h3>". t('My account') ."</h3>". theme('links',
atrium_account_links());

```

and

```
/**
 * Generates an array of account links suitable for use in theme_links().
 */
function atrium_account_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}" => t('Profile'),
    "user/{$user->uid}/dashboard" => '',
    "user/{$user->uid}/edit" => '',
    "user/{$user->uid}/notifications" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
      );
    }
  }
  drupal_alter('atrium_account_links', $links);
  return $links;
}

```

# Answer
> 1 votes
I went ahead and implemented the OpenAtrium code in Drupal 7 which I'll use unless somebody comes up with a better answer.

```
/**
* implements hook_block_info()
*/
function helper_block_info () {
  $blocks['helper_user_links'] = array(
    'info' => t('Menu user links'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/**
* implements hook_block_view()
*/
function helper_block_view($delta = ''){
  $block = array();

    case 'helper_user_links':
      $block['subject'] = NULL;
      $block['content'] = array(
        '#markup' => theme('links', array(
          'links' => helper_user_links(),
          'attributes' => array('class' => 'menu'),
        )),
      );
    break;
  }

  return $block;
}

/**
 * Generates an array of account links suitable for use in theme_links().
 */
function helper_user_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}/businesses/reviews" => '',
    "user/{$user->uid}/content" => '',
    "user/{$user->uid}/workbench" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
        'class' => $_GET['q'] == $item['path'] ? 'leaf active-trail active' : 'leaf',
      );
    }
  }
  drupal_alter('helper_user_links', $links);
  return $links;
}

```

---
Tags: routes, navigation
---


# Question
Title: Creating a new menu item that links to /user
How do I format an array item using `hook_menu()` that links to /user but has a new title and is only accessible to logged in users?

Currently I'm using

```
    $items['user'] = array(
      'title' => 'Account Settings',
      'path' => 'user',
      'router_path' => 'user',
      'description' => 'Manage your username, password and contact information here.',
      'access callback' => 'user_is_logged_in',
      'type' => MENU_NORMAL_ITEM,
      'weight' => -20,
    );

```

Then end goal is to have a link that is titled 'Account Settings' that links to /user and that is only available to logged in users.

Edit: I guess to clarify, how can I incorporate the system menu `/user` item into my modules menu without using the UI?

# Answer
> 1 votes
If you want to duplicate the /user path, then you can use define the following menu item in the implementation of `hook_menu()` in your module:

```
  $items['your module path'] = array(
    'title' => 'User account',
    'description' => 'Manage your username, password and contact information here.',    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'file' => 'user.pages.inc',
    'file path' => drupal_get_path('module', 'user'),
  );

```

Replace "your module path" with the path used by your module, which cannot be the path already used by another module.

If you just want to alter the existing /user path, and avoid is accessible to everybody, then you need to implement hook\_menu\_alter() using code similar to the following:

```
function mymodule_menu_alter(&$items) {
  if (isset($items['user'])) {
    $items['user']['access callback'] = 'user_is_logged_in';
  }
}

```

# Answer
> 2 votes
To move an existing menu item to a different menu in code, you can implement hook\_menu\_alter() and change menu\_name and weight for `$items['user']`.

# Answer
> 1 votes
$items\['user'\] is already defined by user.module - menu items must be unique, so you can't redeclare it in your hook.

Is there a reason you can't use the "My Account" item supplied by the user module? You can override the title on the menu admin page.

---
Tags: 7, routes
---


# Question
Title: Aren't the Article content type and the Blog module the same?
Here's a small question, if Drupal already has an `Article` Content Type, what then is the use of the `blog` module? Aren't they supposed to be the same?

# Answer
> 4 votes
The blog module allows several users to have different blogs. It adds more features that are typically found in a blog to the article. If you are making a single author blog it might be better to build with Views using the Article content type than use the blog module.

# Answer
> 4 votes
You are comparing a content type with a module.

The Blog module implements specific routes, such as:

* /blog, the list of all the blog posts existing on the site
* /blog/feed, the feed for the previous page
* /blog/\[uid\], the list of the blog posts for the user whose ID is \[uid\]
* /blog/\[uid\]/feed, its feed

Using only article nodes you would not get those pages, as the Node module doesn't provide them. You could possibly create something similar using the Views module, but (as far as I know) it could not add link to the user's blog in the page listing all the blog posts, as in the following screenshot, taken from the Blog module.

>

If there is just an author of the blog, or the blog has multiple authors but the single posts are not listed separately basing on the author, then using the Article content type, and a view should be sufficient for your purposes.

Still, the Blog module and the Article content type are not the same thing.

---
Tags: 7, nodes
---


title: How do I use query conditions?

text:
# Question
Title: How do I use query conditions?
I want execute the query `SELECT * FROM table WHERE type = 'AAA' AND id = 'BBB'`.

The following code works.

```
$res = db_select('table', 's')
  ->fields('s')
  ->condition('type', $type)
  ->execute()
  ->fetch();

$res = db_select('table', 's')
  ->fields('s')
  ->condition('id', $id)
  ->execute()
  ->fetch();

```

The following code doesn't work.

```
$res = db_select('table', 's')
  ->fields('s')
  ->condition('type', $type)
  ->condition('id', $id)
  ->execute()
  ->fetch();

```

I get an error about the ID not being unique.

**UPDATE:**

Thanks and sorry. This code works well. I found error in another site.

# Answer
> 1 votes
The code:

```
$res = db_select('table', 's')
->fields('s')
->condition('type', $type)
->condition('id', $id)
->execute()
->fetch();

```

is not faulty in itself. The problem is probably that you don't have a record with matches both id and type. If you want to make an or query, you need to use `db_or`

---
Tags: 7, database
---


title: Content in Lightbox dialog

text:
# Question
Title: Content in Lightbox dialog
Is this possible to pass some content (cck fields values) to Lightbox dialog when image belongs to the same content type is opened?

# Answer
> 1 votes
Lightbox is specifically design to preview images. For General purpose overlay preview for images, videos, iframe and any custom html/text I recommend to use Fancybox. Fancybox module is available for integration in druapl.

```
$.fancybox("Your HTML");

```

# Answer
> 1 votes
You can also use the Colorbox module which allows to load inline content and url content.

> Colorbox is a light-weight, customizable lightbox plugin for jQuery 1.3 through 1.6. This module allows for integration of Colorbox into Drupal.
>
> Images, iframed or inline content etc. can be displayed in a overlay above the current page.

---
Tags: 6, hooks, forms
---


# Question
Title: Drupal 7.2, Views: Adding Author's Name of a node
I'm sure this is VERY basic, but after 1/2 day or searching, I am finally posting for help.

I have a simple view that is displaying a list of node titles & other fields (view count, comment count, etc). I can't find how to add the name of the author who wrote the corresponding node to a field.

For example- the final result SHOULD look like this-

Title by: Author Name Views: # Comments: #

I have everything else working- just can't figure out how to add the author name field. What's the secret? Thanks guys!

# Answer
You need to add a connection between users and content. This is done through relationships. Go to relationships and select Content: Author. Then if you add fields you will see several new fields to choose from including User: Name. When configuring User: Name there will be a drop down that lets you choose which relationship since there is only one choose that one.
> 8 votes

---
Tags: views, entities
---


title: problem with .install file

text:
# Question
Title: problem with .install file
I tried to write the schema for a table as given below, but it did not work. let me know what is the mistake i have made.

```
<?php
/*** Implementation of hook_schema()*/
function sparsh_module_schema(){
    $schema['commissions_impt_data'] = array(
        'description' => 'Holds the imported data from different APIs like CJ and LinkShare for the sales done.',
        'fields' => array(
            'r_id' => array(
                'type' => 'serial',
                'description' => 'The record ID',
                'not null' => TRUE,
                'disp-width' => '11'
            ),
            'member_id' => array(
                'type' => 'varchar',
                'description' => 'Member Id for the Record(User name)',
                'length' => '255',
                'not null' => TRUE
            ),
            'member_type' => array(
                'type' => 'varchar',
                'description' => 'Member Plane Type',
                'length' => '255',
                'not null' => TRUE
            ),
            'transs_date' => array(
                'type' => 'int',
                'description' => 'Transaction Date',
                'not null' => TRUE,
                'disp-width' => '11',
                'default' => 0
            ),
            'source' => array(
                'type' => 'varchar',
                'description' => 'Income Source',
                'length' => '50',
                'not null' => TRUE
            ),
            'merchant' => array(
                'type' => 'varchar',
                'description' => 'Merchant Name',
                'length' => '50',
                'not null' => TRUE
            ),
            'commission_income' => array(
                'type' => 'numeric',
                'description' => 'Commission Income',
                'precision' => '10',
                'scale' => '2',
                'not null' => TRUE
            ),
            'sale_amt' => array(
                'type' => 'numeric',
                'description' => 'Total Sale Amt.',
                'precision' => '10',
                'scale' => '2',
                'not null' => TRUE
            ),
            'user_comm_perc' => array(
                'type' => 'numeric',
                'description' => 'User commission %',
                'precision' => '10',
                'scale' => '2',
                'not null' => TRUE
            ),
            'user_comm_amt' => array(
                'type' => 'numeric',
                'description' => 'User commission amt',
                'precision' => '10',
                'scale' => '2',
                'not null' => TRUE
            ),
            'dat' => array(
                'type' => 'text',
                'description' => 'Serialized Array of Data for the record received from the API',
                'serialize' => TRUE
            ),
            'st' => array(
                'type' => 'serial',
                'description' => 'status of the record.',
                'not null' => TRUE,
                'disp-width' => '11'
            ),
        ),
        'primary key' => array('r_id'),
    );

    return $schema;
}
/**
* Implementation of hook_install().
*/
function sparsh_module_install(){
    drupal_install_schema('sparsh_module');
}
/**
* Implementation of hook_uninstall().
*/
function sparsh_module_uninstall(){
    drupal_uninstall_schema('sparsh_module');
}
//===============================================
//      Helper Functions
//===============================================

function sparsh_module_write_record($table, $object) {
  $schema = drupal_get_schema($table);

  $fields = $values = $placeholders = array();

  foreach ($schema['fields'] as $field => $info) {
    // For inserts, populate defaults from Schema if not already provided
    if (!isset($object->$field) && isset($info['default'])) {
      $object->$field = $info['default'];
    }

    // Build arrays for the fields, placeholders, and values in our query.
    if (isset($object->$field)) {
      $fields[] = $field;
      $placeholders[] = db_type_placeholder($info['type']);

      if (empty($info['serialize'])) {
        $values[] = $object->$field;
      }
      else {
        $values[] = serialize($object->$field);
      }
    }
  }

  $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')';
  return db_query($query, $values);
}

```

# Answer
I used two autoincrement columns in the schema (r\_id & st); that is the mistake.
> 2 votes

# Answer
The `sparsh_module_write_record()` function you wrote seems a reduced version of drupal\_write\_record() that doesn't consider the case the row being written is already present in the database table.
If the code tries to save a row that uses the same value of the primary key used by another row, then you get an error.
> 1 votes

---
Tags: 6, installation
---


# Question
Title: Drupal 7.2: Horizontal & Vertical Tabs- HOW?
Using d7.2. I'm looking to create this setup, possibly w/ JQuery (or something similar that would provide real time tabs w/o refreshing the page).

```
         Popular        Visits       Comments      Recent

```

Category 1

Category 2

Category 3

Category 4

So the user would click on one of the category tabs on the left side (vertical), and then they can sort w/ the links at the top w/ real-time refresh/results, no page refreshing or loading required.

I like the look of JQuery tabs- but want the best solution here. By best I mean easiest, lightest, and most compatible with most browsers.

I can setup various views to execute the searches/results- but do I make those 'pages', or 'blocks'? How do I create the tabs and links for sorting?

Thanks for all the help guys!

# Answer
> 7 votes
The best solution is using the Quick Tabs module. It allows you to create static or dynamic Ajax loaded tabs with nodes, blocks, and views.

---
Tags: views
---


# Question
Title: After I overrode a block template for a primary links, block-edit-link doesn't show anymore...?
I just created **block-menu-primary-links.tpl.php** file in the root of my theme, in order to strip off some default structures I have for other blocks, but now that I did that, *block-edit-link* which was displaying itself by default on hover, doesn't appear anymore. It's not that I want it to back, but I just wonder why did it go away and how can I control it?

**UPDATE**:

Here is what I have in my **block-menu-primary-links.tpl.php**:

```
<div id="block-menu-primary-links">
    <?php echo $block->content; ?>
</div>

```

When I inspect html structure after it is rendered I see that contextual links are in there, but hidden and obviously block has lost something that made the logic tick.

# Answer
> 1 votes
Ok, tracked down the reason - every block requires to have a *className* of **block**:

```
<div id="block-menu-primary-links" class="block">
    <?php echo $block->content; ?>
</div>

```

Once I added this, contextual links regained the functionality. Still not sure where it comes from though, or if it's the only thing sufficient in all cases.

---
Tags: blocks, theming
---


# Question
Title: Views, adding I like, Retweet - best approach
I have several views.

Now I need to add FB I like and retweet button to those views.

I search for modules, but all I get doesn't goes with Views well.

I would like to pass nid of node as excluded field and use Views Custom Field to create those links, but is this possible to get data from another field in custom field?

# Answer
> 3 votes
I also searched for modules that would allow Social Sharing - what I ended up doing was just adding the code manually to the templates. It's just a couple lines of javascript, usually. I ended up using AddThis for the main group and then just pulled the Facebook like code from their website.

IMO, somtimes a module is overkill.

---
Tags: views, 6
---


title: Custom field for block's edit form?

text:
# Question
Title: Custom field for block's edit form?
I would like to add an additional field to block's edit screen and be able to retrieve it's value upon rendering. Is it possible?

# Answer
The Drupal Examples modules has an example of adding extra configuration to blocks. However, you will responsible for handling the data and how it's saved to the database which means it can get complicated fast. If it is a field with a value that is used on each of the blocks then the example which uses variable\_set() and variable\_get() will work. You do not want to much data saved to the variable table.

If the data needs to be more dynamic and you are not building a site with 2,000,000 visitors a day, you can make a node type and use Views to render the values in a block.
> 2 votes

---
Tags: blocks, entities
---


title: Thickbox module not loading all images

text:
# Question
Title: Thickbox module not loading all images
I just started using the ThickBox module to to create a simple gallery. However, only some of the photos will load. A couple will work, than one will just give the loading line and freeze on it. I have the image module working fine and image caching as well. Any idea what might be going on? Thank you.

# Answer
Thickbox -- nothing to do with Drupal -- is no longer supported. I highly recomend using Colorbox. (On Drupal)

(edit) The problem doesn't have anything to do with a modal image viewer. I inspected the code to find the URL of each image and they don't work. Chances are that the images are not being uploaded complete because of an upload limit or they are too large for image cache to successfully manipulate.

In php.ini make sure that:

```
max_execution_time to around 120 and
realpath_cache_size to 512K, 1M or even 2M.
max_input_time to around 120.
post_max_size = 12M to 16M (or large enough for your images)
upload_max_filesize = 12M to 16M (or large enough for your images)

```

In the content type widget configuration make sure that Upload Max size is set accordingly.
> 2 votes

---
Tags: 7
---


# Question
Title: Pathauto module doesn't translate urls generated by l(), url() to aliases, should it?
Pathauto **readme** says:

> If you use the "system path" (i.e. node/10) for menu items and settings like that, Drupal will replace it with the url\_alias.

But in my case links stay the same:

```
echo l('test', 'node/329'); // returns: node/329, should return: about-us

```

It is first time I'm using Pathauto, I was expecting it to work out-of-the-box as I followed all the instructions and there was nowhere mentioned any special url-translation activation procedure or something (is there one?).

When I paste domain.com/about-us into the browser address bar it manages to load proper page. But it doesn't translate my links.

Any idea what could be wrong or where I should I start to repair it?

# Answer
> 2 votes
Ok, found the reason. My admin area is dual-languaged and while I generate aliases in English, front-end runs in Dutch. Once I switched admin and front-end to the same language I got it working as expected.

---
Tags: 7, path-aliases
---


# Question
Title: Captcha doesn't come out in my multiform webform
I have a multiform webform with 3 steps. Why can't I seem to get the CAPTCHA to appear at the end of the form, even when I've already checked *Add CAPTCHA administration links to forms*? Am I missing anything?

I am using Drupal 7 and Captcha 7.x-1.0-alpha3.

# Answer
admin forms is not the same as webforms. You need to manually add the webform to the captcha settings.

Go to admin/config/people/captcha/captcha/settings in the blank text box under "Form Protection" enter the form\_id of the webform and save the configuration. Go to the webform page and you should be able to see the captcha there.

To quickly find the form\_id of the webform, take the node id and append it to "webform\_client\_form\_", for example if the node id is 3 your webform form\_id will be "webform\_client\_form\_3". If this is not your case, you can always use firebug to inspect the hidden form\_id field.
> 2 votes

---
Tags: captcha
---


# Question
Title: I want to put values from additional database in drupal 7. How can I do it?
I wanted to include additional values to the drupal site. Since it has around 3000 records and it is divided into categories ( a:1, a:2, a:3, b:1, b:2, c:1, c:2, c:3), I had set additional database and connected to drupal. My question is: How can I get those values into drupal? views? They have to be included in two forms as a checkboxes and value lists on other form to choose.

Thank you.

# Answer
This thread: https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data discusses this issue quite thoroughly.
> 1 votes

# Answer
If you were using Drupal 6, I would suggest using the Data module, however in Drupal 7 there isn't an equivalent. The Data module would have connected data in two different databases in Drupal if they were described in settings.php.

If you know a little PHP and basics of the Drupal API you can use the new Field API. It's pretty straight forward using the hook\_field\_scheme() to define the database table and the standard Field API hooks to create fields that can be attached to entities in the Drupal Admin UI.

You can use hook\_theme() to define different templates that renders the data in different ways and hook\_field\_formatter\_view() to call different theme functions and templates that you create. Views integration is wonderful because if you create several different formatters when you select the field in the Field section of Views UI it will give you a drop down choice of what formatter to use.

In this case if you're importing the data you don't need to attach the field to a content type, nevertheless, if the data at some point needs to be updated, added to, or deleted dynamically it is already to go with only using four or five different functions.

I have a case where I have a single address field defined but it includes city, state, country, zip, lat, lng, ect. in each row of the database table. However, I have 5 different formatters, one with only lat and lng converted to degrees, another with only the city and state, and one with the entire address as a vcard with a call to google to return a static map with a marker. In views I just choose which formatter to use with the information.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Difference between hook_page_alter and preprocess_page?
I don't completely understand when I should use hook\_page\_alter(&$page) or template\_preprocess\_page(&$vars, $hook) in Drupal 7.

What is the best practices about that to use in template.php?

Thanks

# Answer
> 17 votes
The difference is their purpose.

hook\_page\_build() and hook\_page\_alter() are used to remove, alter, or add elements at the page level.
The $page array passed to `hook_page_alter()` contains the top level elements for each block region. By default they are the following ones:

* page\_top
* header
* sidebar\_first
* content
* sidebar\_second
* page\_bottom

An example of implementation could be the following one:

```
function mymodule_page_alter(&$page) {
  // Add help text to the user login block.
  $page['sidebar_first']['user_login']['help'] = array(
    '#weight' => -10,
    '#markup' => t('To post comments or add new content, you first have to log in.'),
  );
}

```

The preprocess functions are called to alter the variables that are passed to the template file. They cannot change the structure of the page, but they can alter the content of some elements of the page changing the content of those variables.
For example, the Overlay module removes the primary tabs when the page being visualized is the overlay.

```
function overlay_preprocess_page(&$variables) {
  if (overlay_get_mode() == 'child') {
    unset($variables['tabs']['#primary']);
  }
}

```

---
Tags: 7, theming
---


# Question
Title: How to manipulate different regions from a module
My module has a menu callback which outputs data to a custom template using `hook_theme()`.

Normally, Drupal includes this output into the content region that is rendered at the page.tpl.php level using `render($page['content'])`.

How can I simultaneously output stuff from my module but into other regions of page.tpl.php? For example `$page['sidebar_first']` or `$page['footer']`.

Is this possible?
Alternatively, how can I tell Drupal to use a custom page.tpl.php when the menu callback is called?

# Answer
> 2 votes
If you want to exactly put content in `$page['sidebar_first']`, then you can implement hook\_page\_build() or hook\_page\_alter(). The difference between the hooks is that the latter is used when the module needs to alter some elements added by another module with `hook_page_build()` as the first hook is executed first.

Examples of `hook_page_build()` are the following functions.

```
function toolbar_page_build(&$page) {
  $page['page_top']['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#access' => user_access('access toolbar'),
    'toolbar_drawer' => array(),
  );
}

```

```
function dashboard_page_build(&$page) {
  global $theme_key;

  if (dashboard_is_visible()) {
    $block_info = array();

    // Create a wrapper for the dashboard itself, then insert each dashboard
    // region into it.
    $page['content']['dashboard'] = array('#theme_wrappers' => array('dashboard'));
    foreach (dashboard_regions() as $region) {
      // Do not show dashboard blocks that are disabled.
      if ($region == 'dashboard_inactive') {
        continue;
      }
      // …
    }
    // …
  }
}

```

As alternative, your module could define a block, but in that case, the block will be placed in the region set by the administrator users (or any user with the right permission), which could be place the block in a different region. If there isn't a reason to place the content your module is adding in a specific region, then I would rather opt for implementing blocks.

---
Tags: theming
---


title: The module is not working as expected

text:
# Question
Title: The module is not working as expected
I can't figure out why this module is not working. What is wrong with it?

```
/* hook_menu() */
function profilepage_menu() {
  $items['p'] = array(
    'title' => 'Profile page',
    'page callback' => 'profile_exe',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/* Callback function */
function profile_exe($id) {
  $ar = array('uid' => $id, 'profilesload' => profile2_load_by_user($id));

  return theme('profilebuild', array('collected' => $ar));
}

/* Custom theme function. */
function theme_profilebuild($variables) {
  return "";
}

/* hook_theme() */
function profilebuild_theme() {
  return array(
    'profilebuild' => array(
      'variables' => array('profilesload' => array()),
      'template' => 'profilepage',
    ),
  );
}

```

The module is installed and a page called profilepage.tpl.php is in my theme directory AND in the module directory.

The output I'm expecting should be the text in the profilepage.tpl.php page along with the contents of the $variables array which I plan to use in my template.

However, when I open http://example.com/?q=p in my browser, the page loads without errors but the expected content is not there.

What am I doing wrong?

# Answer
> 0 votes
The problem I can see with your code is the file name for the template file that you declare in your `hook_theme()` implementation. The file name for the template file should be the theme identifier used as array index in the array returned by `hook_theme()` (in your case, "profilebuild"); where the identifier uses underscores, the template name should use hyphens.

As example of how the template files are named, see the following `hook_theme()` implementations for Drupal core modules.

```
function book_theme() {
  return array(
    'book_navigation' => array(
      'variables' => array('book_link' => NULL),
      'template' => 'book-navigation',
    ),
    'book_export_html' => array(
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
      'template' => 'book-export-html',
    ),
    'book_admin_table' => array(
      'render element' => 'form',
    ),
    'book_title_link' => array(
      'variables' => array('link' => NULL),
    ),
    'book_all_books_block' => array(
      'render element' => 'book_menus',
      'template' => 'book-all-books-block',
    ),
    'book_node_export_html' => array(
      'variables' => array('node' => NULL, 'children' => NULL),
      'template' => 'book-node-export-html',
    ),
  );
}

function aggregator_theme() {
  return array(
    'aggregator_wrapper' => array(
      'variables' => array('content' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-wrapper',
    ),
    'aggregator_categorize_items' => array(
      'render element' => 'form',
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_feed_source' => array(
      'variables' => array('feed' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-feed-source',
    ),
    'aggregator_block_item' => array(
      'variables' => array('item' => NULL, 'feed' => 0),
    ),
    'aggregator_summary_items' => array(
      'variables' => array('summary_items' => NULL, 'source' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-items',
    ),
    'aggregator_summary_item' => array(
      'variables' => array('item' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-item',
    ),
    'aggregator_item' => array(
      'variables' => array('item' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-item',
    ),
    'aggregator_page_opml' => array(
      'variables' => array('feeds' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_page_rss' => array(
      'variables' => array('feeds' => NULL, 'category' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
  );
}

```

Drupal 7 implementations of that hook is slightly different from the implementation done in Drupal 6, but the "template" index is used in the same way in both the versions.

```
function block_theme() {
  return array(
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
      'file' => 'block.admin.inc',
      'arguments' => array('form' => NULL),
    ),
  );
}

```

---
Tags: 7, theming
---


# Question
Title: How can I add the og to a menu when a new organic group is added?
I want to create organic groups that represent counties, and have a menu with some states already Set up, so the user can just select the state for the organic group to be listed under. The title of the organic group will be the name of the county, which should be the same as the link in the menu.

Is there a way that this can be set up when the organic group is being created?

I'm using the latest release of drupal 6, and organic groups 6.x-2.1.

Is there a module that allows you to automatically assign a sub menu for group content without the user being able to change what the menu title is called? I guess that, ideally, I'd like to have an About page that has the same title and menu path for each group.

# Answer
You can try this module : http://drupal.org/project/auto\_menutitle. It allows to automatically generate menu items based on the node title. If you enable this module on your og content type, it should do it.
> 1 votes

---
Tags: 6, routes, organic-groups
---


title: Adding an image upload table

text:
# Question
Title: Adding an image upload table
How is it possible to add an image upload table in the code of a custom module in Drupal 7?

In other words, I want to add the "Images Table" (the one with drag-able rows) to a custom form I'm creating in my custom module. And I need all it's options too, like thumbnail, title and description fields for each uploaded image row plus the remove button, with the ability to limit the number of uploaded images of course.

What is the code to be used to achieve that?

Thanks for your time and help in advance.

# Answer
Image upload fields and drag & drop tables are two separate elements that you can combine in your module by using a form callback function to declare your fields and a theme function to theme the upload fields in a drag & drop table.

D7 Form API provides an upload field named 'managed\_file'. The documentation provides a clear example:

```
<?php
// Use the #managed_file FAPI element to upload an image file.
$form['image_example_image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
  '#default_value' => variable_get('image_example_image_fid', ''),
  '#upload_location' => 'public://image_example_images/',
);
?>

```

Then you can have a look at the documentation to setup the field with your desired settings. This element does not have a #multiple setting. So you can either generate many fields, either add new fields using ajax as in cck in D6.

Finally you can check this documentation on how to use drupal\_add\_tabledrag();
> 4 votes

---
Tags: 7, media
---


# Question
Title: How can you group multiple answer fields?
Firstly, apologies if I don't use correct Drupal or database terminology - I'm still learning!

I am using Drupal 6 with the latest stable versions of CCK, Views and Date.

I have a content type that requires two 'sections' of fields - the first would be for standard fields, the second would be multiple entry fields where all the fields are related.

It's probably best explained with an example, so here goes:

Let's say the content type is for episodes of a TV show.

Firstly, we want to know the title of the episode, so there'll be a title field.

Secondly, we want a reference number for the episode, so there'll be an ID field.

Now for the grouped fields:

We want to know when the episode was broadcast, and on what channel. However, it may be that the episode is repeated - and that repeat could be on another channel. For example:

Top Gear was on BBC2 this evening (26/06/11) at 8pm. It will be repeated on BBC2 on 28/06/11 at 11.20pm. It will be repeated again on 29/06/11 at 7pm, this time on BBC3.

So I want to have an unlimited value datetime field. However, this needs to be bound to an unlimited value text field for the channel (and likewise for any other field with unlimited value data).

How do I achieve this?

Thanks in advance for any assistance! Please bear in mind that I'm not much more than a novice - I can install a module but I won't know how to do any advanced stuff without guidance!

# Answer
The drupal 6 version of cck comes with a sub-module called multigroup. This will allow you to group multiple fields together and allow for unlimited inputs per group.
> 2 votes

---
Tags: 6, entities
---


title: Discovering cookie session data

text:
# Question
Title: Discovering cookie session data
Can anyone advice me on how I can discover the active cookie details for a user logged into a Drupal website?

# Answer
All cookie data is in the PHP superglobal $\_COOKIE. However a typical Drupal site only stores the a random session identifier in the cookie, so it may not be what you're looking for. If $\_COOKIE doesn't answer your question please post more details about what you're trying to accomplish.
> 1 votes

---
Tags: cookies
---


# Question
Title: How to display "NEW" label in comments list
1. How do I display the "(new)" label in comments listing page.
2. What is the logic of displaying the "(new)" label. How does it work?

# Answer
There is a database table called history that records a users history to check against. There is an option in Views to add a 'new' marker to content that has not been viewed by the user and had been created within a certain time frame. If you are further interested in how the 'new' marker works, you can find the query that Views uses in views/modules/comment/views\_handler\_field\_node\_new\_comments.inc to add the 'new' tag to a list of fields.

(edited for clarity)
> 4 votes

---
Tags: comments
---


# Question
Title: Dynamic loading using Tabs module and CCK Fieldgroup tabs
I am currently using the Tabs and CCK Fieldgroup Tabs modules to display views in a tabbed format on nodes of a custom type. However, pages take a long time to load because the content in every tab is loaded at once. I want to dynamically load each tab only when it is clicked. How can I accomplish this? For example, look at the first node on this page

# Answer
> 1 votes
That example page uses Quick Tabs module.

> I want to dynamically load each tab only when it is clicked. How can I accomplish this?

Quick Tabs gives the option to dynamically load content with ajax. Here is demonstration linked to by the Quick Tabs project page. To get that solution please read the Quick Tabs documentation.

Yes, the example you give uses the Quick Tabs module. It says so in the markup. `class="clear-block quicktabs_tabs quicktabs-style-excel ui-tabs-nav tabs primary"`

---
Tags: 6, routes
---


title: Drupal as a 3-tier system model

text:
# Question
Title: Drupal as a 3-tier system model
We are planning to create an 'agency' site on drupal. The 'agency' site will serve as 3-tiered system model composed of the following levels: 1. Agents (users) 2. Agency (agent users will belong to a specific agency) 3. Super Administrator (controls everything, permissions etc)

The idea behind the site is to have the ability to register an 'agency' (only by the super admin), that will in-turn have the ability to create their own users (Agents).

If Agency1 logs in, he should be able to register their own sets of users. So goes with other agencies. New users created should belong exclusively to their respective agencies, automatically upon registration.

Are there any modules out there that can be configured to do this? I have 'Profile 2' Module but I don't think this fits the bill. I am looking at the Groups Module but not sure if this is really the right one.

# Answer
> 2 votes
You could use Organic groups.

In that case, every agency would be a group with a group administrator that could set the users that are part of that agency. Every agency could have its own content, which would be created from the users that are associated with the agency. A user of another agency would not be able to create content for another agency, if not in the case the user is member of both the agencies.

# Answer
> 1 votes
Organic groups is the only way to go.

Besides that, you should disable the option for the users to registers themselves (in User Management / User settings / **Only site administrators can create new user accounts**). You can then create users with administrator privileges to create users (agency managers) and agencies.

With organic groups you can also customize if a user can / cannot see the content from another agency. Here are more modules which work with OG: link.

A Drupal distribution built on top of Drupal and OG is Drupal Commons: here's a live site with that functionallity (also in this case, you should disable user registration and group creation by normal users).

Install the OG module with others modules or the DC distribution and give it a test. Good luck!

---
Tags: 7
---


# Question
Title: Problem with views recent comments block
I have a problem with the recent comments block created with Views. I have overridden the view fields in the view template (views-view-fields--comments-recent--block.tpl.php) and printed out the fields:

```
print '<div class="subj">'. $fields['subject']->content .'</div>';
print '{ <span> '.$fields['name']->content. '</span>' .', '. '<span>'. $fields['timestamp']->content .'</span> }';

```

It displays the name of user that created that node. For example, I've created a node titled "blahblahblah" and I added a comment on my node; the block displays "blahblah - posted by heihachi." If another user (jessica) posts a comment in that node, the block still displays " blahblah - posted by heihachi," not "by jessica."
Why?

# Answer
This is because the title and author being shown belongs to the node not the comment. There are some options under the comment group of a views fields or you can use a relationship to specify the node's author or the comment's author.
> 1 votes

---
Tags: views, comments
---


title: Pass an array of nids to a view

text:
# Question
Title: Pass an array of nids to a view
How do I pass a view an array of node ids? I can create the view using the ui, but the query I want to run is outside the scope of views. I want to run the db query independently, gather the node ids into an array, and then pass it to the view for display. Howvian I make this happen, if at all?

# Answer
You can add a "Content: Nid" contextual filter to your view, so your view will narrow down the content to the NIDs you provided. Make sure you check the "Allow multiple values" box when configuring the contextual filter. This will allow a url like `example.com/myview/12+45+78` which would limit the results to node IDs 12, 45 and 78.
> 4 votes

# Answer
If you want to display these nodes formatted with a view\_mode, and not for example in a table, you could also use the API for that: node\_view\_multiple().

Simply pass the array of nid's with the desired $view\_mode to that function and it will return an render array that you can return in a block or page callback or directly render with `drupal_render()`.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Administration Theme switches to front-end theme
I am using administration theme "Seven".

When I clear cache or I work with some module and then I save its settings, the administration theme *switches* to front-end theme.

If i reload browsers current page, then the front-end theme *switches* back to the admin theme.

Is there any setting that can fix this?

# Answer
Overlay does not work with prefixed URL paths. http://drupal.org/node/1075096
> 0 votes

---
Tags: 7
---